【问题标题】:Beautifullsoup Attribute ErrorBeautifulsoup 属性错误
【发布时间】:2014-07-14 09:51:06
【问题描述】:

愚蠢的问题...

for page in range(xxx, yyy):
url =  "%s%d" % (program_url, page)
opener = urllib2.build_opener() 
response = opener.open(url)
soup = BeautifulSoup(response)

print soup.find("strong").text

有时页面不包含任何强大的应答器,所以我有:

AttributeError: 'NoneType' object has no attribute 'text'

如何避免?

【问题讨论】:

    标签: python beautifulsoup attributeerror


    【解决方案1】:

    您可以使用is not 运算符测试None 对象:

    result = soup.find("strong")
    if result is not None:
        print result.text
    

    或者,您可以使用try/except 块来捕获错误:

    try:
        print soup.find("strong").text
    except AttributeError:
        pass  # You should probably handle the error instead of use pass
    

    【讨论】:

      【解决方案2】:

      将您的打印语句更改为:

      if soup.find("strong"):
          print soup.find("strong").text
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-20
        相关资源
        最近更新 更多