Skip to main content
 首页 » 编程设计

python之如何在 python 中迭代跳过 TypeError、AttributeError 和 IndexError

2025年05月04日8hnrainll

我试图使用 BeautifulSoup 从维基百科表格中获取信息。现在我被堆叠起来了,因为我无法循环遍历一个对象。

这是代码:

import requests 
from bs4 import BeautifulSoup 
 
url='http://de.wikipedia.org/wiki/Liste_der_in_der_Europ%C3%A4ischen_Union_zugelassenen_Lebensmittelzusatzstoffe' 
raw_data=requests.get(url) 
soup=BeautifulSoup(raw_data.content) 
table= soup.find_all("table",{"class":"wikitable sortable"}) 
 
for i in table: 
    print i.contents[i].find_all("td") 

这是错误:

Traceback (most recent call last): 
  File "<stdin>", line 2, in <module> 
TypeError: list indices must be integers, not Tag 

如果我使用 try: 和 except: 则不会打印任何内容。

有人可以帮助我吗?

非常感谢!

请您参考如下方法:

嗯,你是对的,一般来说,你可以迭代跳过 TypeError、AttributeError 和 IndexError 来处理异常。

但是这里的错误是:

TypeError: list indices must be integers, not Tag 

这个错误是由于:

i.contents[i] 

这里的 i 不是一个整数,而是一个 beautifulsoup 元素标签。所以你不能索引列表。

>>> type(i) 
<class 'bs4.element.Tag'> 

所以我相信您正试图找到其中的所有 td 标签。现在,当您遍历 table 时,您已经选择了该元素。所以,只需执行 find_all 就会给你所有的 td 元素:

i.find_all("td") 

所以,你的代码应该是:

import requests 
from bs4 import BeautifulSoup 
 
url = 'http://de.wikipedia.org/wiki/Liste_der_in_der_Europ%C3%A4ischen_Union_zugelassenen_Lebensmittelzusatzstoffe' 
raw_data = requests.get(url) 
soup = BeautifulSoup(raw_data.content) 
table = soup.find_all("table", {"class": "wikitable sortable"}) 
 
for i in table: 
    print i.find_all("td")