Marco T.
Marco T.

Reputation: 57

Beautifullsoup Attribute Error

Stupid problem...

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

Sometimes the page don't contain any strong balise, so I have:

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

How to avoid it?

Upvotes: 0

Views: 119

Answers (2)

Happy001
Happy001

Reputation: 6383

change your print statement to:

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

Upvotes: 0

user2555451
user2555451

Reputation:

You can test for a None object with the is not operator:

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

Or, you can use a try/except block to catch the error:

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

Upvotes: 1

Related Questions