mutantChickenHer0 mutantChickenHer0 - 1 year ago 128
Python Question

BeautifulSoup - check for attribute / if no attribute

I have a function that scrapes information from a list of input URL's.

def scraper(inputlist):
for url in inputlist:
fullurl = baseurl + url
hotelresponse = requests.get(fullurl)
hotelsoup = BeautifulSoup(hotelresponse.text, "lxml")
hoteltitle = hotelsoup.find('div', attrs={'class': 'vcard'})
hotelhighprice = hotelsoup.find('div', attrs={'class': 'pricing'}).text
for H1 in hoteltitle:
hotelName = hoteltitle.find('h1').text
return (hotelName, hotelhighprice, fullurl)

In this particular case, "hotelhighprice" may not always have a value.

I want to

A) If hotelhighprice is there / has a value, I want to return it.
If not, then print a string "empty".

then, to iterate on that

B) If hotelhighprice is not there, look for a different value (that I will specify as a variable.

Current error message -

File "", line 35, in scraper
hotelhighprice = hotelsoup.find('div', attrs={'class': 'pricing'}).text
AttributeError: 'NoneType' object has no attribute 'text'

Answer Source

You can use

text_value = getattr(hotelsoup.find('div', attrs={'class': 'pricing'}), "text", my_default_value)