【发布时间】:2012-02-14 12:37:19
【问题描述】:
尝试在我的代码中不添加 buku try / except 语句的情况下实现简单的错误处理。
我的 if_error 函数尝试在 excel 中模拟 iferror(value,value_if_error) 公式。
If the value (another formula) is valid,
return its resulting value
else
return value_if_error
如何将带有参数的 beautifulsoup 对象(汤)的方法调用传递给泛型 try/except 函数?
- 尝试了 lambda,但理解不够,无法使其与参数和汤一起使用。
- 看了Partial,但没看出来怎么叫美汤法
- 看了this 但没看到汤怎么传?
我的代码:
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
错误:
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'
soup.find 方法在 if_error 函数到达之前一直触发。我该如何解决这个问题?
【问题讨论】:
-
您可能已经知道这一点,但使用裸露的
except是危险的做法,因为它几乎可以捕获所有可能的问题。您应该提供您愿意转换为if_error值的异常。
标签: python beautifulsoup