Python 如何在异常时忽略BeautifulSoup AttributeError/Continue
我用Python和漂亮的汤构建了一个web刮板 有时某些元素存在,有时它们不存在。我有很多。为每个“find”和/或“find_all”设置自定义异常对我来说没有意义 我只想忽略错误,这样我的刮板就不会在异常时停止。以下是我的终端的错误输出:Python 如何在异常时忽略BeautifulSoup AttributeError/Continue,python,beautifulsoup,Python,Beautifulsoup,我用Python和漂亮的汤构建了一个web刮板 有时某些元素存在,有时它们不存在。我有很多。为每个“find”和/或“find_all”设置自定义异常对我来说没有意义 我只想忽略错误,这样我的刮板就不会在异常时停止。以下是我的终端的错误输出: Traceback (most recent call last): File "listing-scraper.py", line 80, in <module> 'engine_size':soup.find("span",{"
Traceback (most recent call last):
File "listing-scraper.py", line 80, in <module>
'engine_size':soup.find("span",{"id":"infoEngine Size"}).contents[0],
AttributeError: 'NoneType' object has no attribute 'contents'
考虑以下情况:
def getcontents(item, index):
if item is None:
return None
return item.contents[index]
motorcycle = {
'insert_date':time.time() * 1000,
'year':getcontents(soup.find("span",{"id":"infoYear"}), 0),
...
通常,如果可以避免首先导致异常,则不应忽略异常。使用
try?
def getcontents(item, index):
if item is None:
return None
return item.contents[index]
motorcycle = {
'insert_date':time.time() * 1000,
'year':getcontents(soup.find("span",{"id":"infoYear"}), 0),
...