如何在BeautifulSoup中捕获此异常

时间:2012-12-09 23:35:44

标签: python beautifulsoup

  

可能重复:
  Using BeautifulSoup, how to guard against elements not being found?

使用BeautifulSoup查找页面中的所有选项时出现以下Python错误:

   for item in soup.find(id="start_dateid").find_all('option'):
AttributeError: 'NoneType' object has no attribute 'find_all'

问题是当页面没有id =“start_dateid”时,会产生错误:AttributeError:'NoneType'对象没有属性'find_all'

如何防止此错误?

1 个答案:

答案 0 :(得分:2)

首先将“subsoup”分配给变量:

thing = soup.find(id="start_dateid")
if thing:
    for option in thing.find_all('option'):
        # potato potato potato