愚蠢的问题......
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'
如何避免它?
答案 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