【发布时间】:2018-12-06 22:42:52
【问题描述】:
我对 Python 还很陌生,所以我想知道是否有比运行大量连续的 try/except 块更简洁的替代方法,如下所示?
try:
project_type = body.find_element_by_xpath('./div[contains(@class, "discoverableCard-type")]').text
except Exception:
project_type = 'Error'
try:
title = body.find_element_by_xpath('./div[contains(@class, "discoverableCard-title")]').text
except Exception:
title = 'Error'
try:
description = body.find_element_by_xpath('./div[contains(@class, "discoverableCard-description")]').text
except Exception:
description = 'Error'
try:
category = body.find_element_by_xpath('./div[contains(@class, "discoverableCard-category")]').text
except Exception:
category = 'Error'
...
正如this thread 或this thread, 中所建议的那样,我想我可以创建变量名和查询列表,然后使用for 循环为每个容器项构造一个字典,但真的没有其他选择哪些可能更具可读性?
【问题讨论】:
标签: python error-handling try-catch