Trying to implement simple error handling without adding buku try / except statements to my code.
My if_error function tries to emulate the iferror(value,value_if_error) formula in excel.
If the value (another formula) is valid,
return its resulting value
else
return value_if_error
How can I pass a method call from a beautifulsoup object (soup) with parameters to a generic try/ except function?
- Tried lambda but didn't understand enough to make it work with parameters & soup.
- Looked at Partial but didn't see how that would call the beautiful soup method
- Looked at this but didn't see how soup would be passed?
My Code:
def if_error(fn,fail_value):
try:
value = fn
except:
value = fail_value
return value
def get_trulia_data(soup):
d = dict()
description = if_error(soup.find('div', attrs={'class': 'listing_description_module description'}).text,'')
sale_price = if_error(soup.find('div', attrs={'class': 'price'}).text,'0')
sale_price = re.sub('[^0-9]', '', sale_price)
details = if_error(soup.find('ul', attrs={'class': 'listing_info clearfix'}),'')
bed = if_error(soup.find('input', attrs={'id': 'property_detail_beds_org'})['value'],'')
bath = if_error(soup.find('input', attrs={'id': 'property_detail_baths_org'})['value'],'')
...
return d
Error:
Traceback (most recent call last):
data_dict = get_trulia_data(url)
description = if_error(soup.find('div', attrs={'class': 'listing_description_module description'}).text,'')
AttributeError: 'NoneType' object has no attribute 'text'
The soup.find method keeps firing before the if_error function is reached. How can I fix this?