Beautifulsoup属性错误

时间:2014-05-25 14:25:18

标签: python beautifulsoup attributeerror

愚蠢的问题......

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'

如何避免它?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

将您的print语句更改为:

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