在Python中执行延迟执行并获取异常的默认值
我正在解析HTML,文件中有许多可选的属性,如果在读取它们时引发异常,我将使用一些默认值。 是否有某种方法可以准备一个泛型函数,该函数将尝试检索属性并在异常情况下返回默认值? 目前,我有这样的东西,但它是非常丑陋的在Python中执行延迟执行并获取异常的默认值,python,exception,default,Python,Exception,Default,我正在解析HTML,文件中有许多可选的属性,如果在读取它们时引发异常,我将使用一些默认值。 是否有某种方法可以准备一个泛型函数,该函数将尝试检索属性并在异常情况下返回默认值? 目前,我有这样的东西,但它是非常丑陋的 try: title = soup.find('h1').text except: title = "b/d" try: location =
try:
title = soup.find('h1').text
except:
title = "b/d"
try:
location = soup.find('a', attrs={'href': '#map'}).text
except:
location = "none"
try:
downside= soup.find('strong', attrs={'aria-label': 'downside'}).text
except:
downside = "0"
try:
incremental = soup.find('div', attrs={'aria-label': 'incremental'}).contents[3].text
except:
incremental = "1"
try:
difference = soup.find('div', attrs={'aria-label': 'difference'}).contents[1].text
except:
difference = "2"
try:
part = soup.find('div', attrs={'aria-label': 'part'}).contents[1].text
except:
part = "3"
- 不要捕捉赤裸裸的异常
def get_attribute_text(soup, element, attrs, default_value, contents_index=None):
try:
if contents_index:
return soup.find(element, attrs=attrs).contents[contents_index].text
return soup.find(element, attrs=attrs).text
except AttributeError:
return default_value
并使用类似于:
title=get_属性_文本(soup,'h1',{},'b/d')
location=get#u attribute_text(soup,'a',{'href':'#map'},'none')
...
增量=获取属性文本(soup,'div',{'aria-label':'incremental'},'1',3)
...
谢谢您的回答。我想知道是否还有一种更通用的方法将任何代码传递给该方法,而不是在内部准备它。类似于:def lazy_execute(a,默认值):try:return执行(a)except:returndefault@MJavaDev您可以轻松地将函数传递给您的函数,例如def foo():pass;定义栏(func):func();吧台(foo)