How to fix TypeError: 'NoneType' object is not iterable

How to fix TypeError: 'NoneType' object is not iterable

我试图用 Beautiful Soup 收集一些信息,我在 for 循环中放了一个 try ... except 但它似乎效率不高。我一定是做错了什么,但我不知道在哪里。

这从名为 occupations_list 的 URL 列表中获取 html。 URL 示例:https://candidat.pole-emploi.fr/offres/emploi/horticulteur/s1m1

for occupation in occupations_list:
  offers_page = requests.get(occupation)
  offers_soup = BeautifulSoup(offers_page.content, 'lxml')
  offers = offers_soup.find('ul', class_='result-list list-unstyled')

这在 html 我上了头条

for job in offers:
    try:
      headline = job.find('h2', class_='t4 media-heading').text
    except Exception as e:
      pass
    print(headline)

问题是在抓取了一些标题后我收到了以下错误消息:

TypeError                                 Traceback (most recent call last)
<ipython-input-77-cbf6b87ac0f9> in <module>()
      3   offres_soup = BeautifulSoup(offres_page.content, 'lxml')
      4   offres = offres_soup.find('ul', class_='result-list list-unstyled')
----> 5   for job in offres:
      6     try:
      7       headline = job.find('h2', class_='t4 media-heading').text

TypeError: 'NoneType' object is not iterable

None 表示没有找到,你可以使用 if ... is None 检查而不是 try-except 如果没有找到则跳过

for occupation in occupations_list:
  offers_page = requests.get(occupation)
  offers_soup = BeautifulSoup(offers_page.content, 'lxml')
  offers = offers_soup.find('ul', class_='result-list list-unstyled')
  if offers is None:
    continue
  print("Processing offers")

用您的实际处理替换print("Processing offers")