python - 在 Python 中执行延迟执行并获取异常的默认值
问题描述
我正在解析 HTML 并且在文件中有很多可选的属性,如果在我阅读它们时引发异常,我会使用一些默认值。有没有办法准备一个通用函数来尝试检索属性并在异常时返回默认值?目前,我有这样的东西,但它非常难看。
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_attribute_text(soup, 'h1', {}, 'b/d')
location = get_attribute_text(soup, 'a', {'href': '#map'}, 'none')
...
incremental = get_attribute_text(soup, 'div', {'aria-label': 'incremental'}, '1', 3)
...
推荐阅读
- python - 在python中模拟一个类
- c# - 获取 InterpolatedStringExpressionSyntax 的值
- asp.net-core-2.1 - 没有配置 IAuthenticationSignInHandler 来处理方案的登录:Identity.Application
- sorting - 对具有 2 个值的子列表进行排序,其中 id 由最后带有连续数字的字符串组成
- c# - C# - 检查是否在 Windows10 上安装了 UWP 应用
- mercurial - HG 命令行输入在 THG 中自动接收不需要的默认输入
- linkedin-api - 领英 API 参考
- docker - 如何查看分离的 docker 容器?
- sql - 如何将 ISO 8601 格式“ID:HH24:MI”的 varchar 字符串转换为时间?
- sharepoint - Flow 将从 Outlook 附件在 Sharepoint 中创建文件,但不会完成更新文件属性操作