多次尝试,没有exec()解决方案

时间:2018-08-21 17:14:56

标签: python

我有多次尝试-

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

2 个答案:

答案 0 :(得分:7)

您可以将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)

答案 1 :(得分:-3)

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 e1:
        errors_log.add(e1)

为了安抚注释中的内容,从我对问题和提供的代码的角度来看,上面的代码修改了try块的处理方式。原始代码会同时检查这两个类,如果找不到链接文本,我发布的代码只会检查该类。例如。如果他要按文本选择的第一个元素与他要按类选择的元素相同,则如果存在链接文本,则不会浪费时间检查是否存在替代项。

如果评论中的那些人有耐心,他们会看到解释的。即使他们只是礼貌地问。由于某些原因,人们认为在这样的情况下对他人无礼是他们的上帝赋予的权利。