我对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
循环为每个容器项目构造一个字典,但实际上没有其他替代方法可能更具可读性吗? 最佳答案
您可以将调用抽象为find_element_by_xpath
;这样可以避免代码重复,并使代码更具可读性:
def _find_element_by_xpath(body, xpath)
try:
return body.find_element_by_xpath(xpath).text
except Exception: # <-- Be specific about the Exception to catch
return 'Error'
def get_a_specific_xpath(element):
return f'./div[contains(@class, "discoverableCard-{element}")]'
然后您的代码变为:
project_type = _find_element_by_xpath(body, get_a_specific_xpath('project_type'))
title = _find_element_by_xpath(body, get_a_specific_xpath('title'))
description = _find_element_by_xpath(body, get_a_specific_xpath('description'))
category = _find_element_by_xpath(body, get_a_specific_xpath('category'))
...
关于python - 连续尝试/排除块的替代方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51072895/