python - 将方法调用作为变量传递给错误处理函数

标签 python beautifulsoup

尝试在不向我的代码中添加 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,但对参数和 soup 的理解程度不够。
  • 查看了 Partial 但没有看到如何调用漂亮的 soup 方法
  • 查看了 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 函数之前一直触发。我该如何解决这个问题?

最佳答案

这个怎么样:

def if_error(fn, fail_value, *args, **kwargs):
    try:
      return fn(*args, **kwargs)
    except:
        return fail_value

def test_fail(x):
    raise ValueError(x)

def test_pass(x):
    return x

if __name__=='__main__':
    print if_error(test_fail, 0, 4)
    print if_error(test_pass, 0, 5)

关于python - 将方法调用作为变量传递给错误处理函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8933065/

相关文章:

python - Azure SQL 数据库与 pyodbc 连接

python - 为什么只有最里面的嵌套 while 循环起作用?

python - BeautifulSoup 返回空的 span 元素?

python - 在 django 中使用 google recaptcha V3 的最佳方式

python - Python 中的 "find . -regex ..."或如何查找全名(路径+名称)与正则表达式匹配的文件?

python - 使用 Python 的资源 (resx)

python - 在Python中抓取一个url

python - 从交易所网页获取最新价格

python - 如何从 python 中的 HTML 表格中的特定单元格获取数据?

python - BeautifulSoup 在 Instagram html 页面中查找