我有这么多次尝试
errors_log = set()
try:
page_element = chrome.find_element_by_link_text("Next Page")
except Exception as e:
errors_log.add(e)
try:
page_element = chrome.find_element_by_class_name("pager_next")
except Exception as e:
errors_log.add(e)
根据其他问题的答案,我重构了代码:
page_elements = ['chrome.find_element_by_link_text("Next Page")',
'chrome.find_element_by_class_name("pager_next")',]
for page_element in page_elements:
try:
exec(page_element)
except Exception as e:
errors_log.add(e)
我对此感到难过,可能是因为使用
exec()
我如何重构它并不难看?
感谢Zakharov的有用回答,我将代码重构为
actions = [chrome.find_element_by_class_name,
chrome.find_element_by_link_text]
next_pages = ["pager_next ", "Next Page"]
prev_pages = ["pager_prev ", "Prev Page"]
def get_page_element_by_multiple_tries(actions, pages):
"""
Try different context.
"""
for action, page in zip(actions, pages):
try:
page_element = action(page)
except Exception as e:
errors_log.add(e)
print(e)
# print(errors_log)
return page_element
最佳答案
您可以将Python函数作为对象存储在列表中(因为它们是对象)并在循环中调用它们:
actions = [chrome.find_element_by_link_text, chrome.find_element_by_class_name]
pages = ["Next Page", "pager_next"]
for action, page in zip(actions, pages):
try:
page_element = action(page)
except Exception as e:
errors_log.add(e)