Wizard
Wizard

Reputation: 22103

Multiple try-except without exec() solution

I have such multiple try-except

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)

Following the answers from other question, I refactor the codes:

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) 

I feel bad about it, might because using exec()

How could I refactor it not ugly?


Thanks to the Zakharov's helpful answer, I refactor codes as

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

Upvotes: 1

Views: 105

Answers (2)

Lev Zakharov
Lev Zakharov

Reputation: 2427

You can store Python functions in list as objects (because they're objects) and call them in loop:

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)

Upvotes: 7

Swift
Swift

Reputation: 1711

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)

To appease those in the comments, from my perspective of the question and the code provided, the code above amends how the try blocks are handled. The original code would check for both, the code I posted will only check for the class if the link text cannot be found. E.g. if the first element he wants to select by text is the same one he wants to select by class, then if the link text is present then it will not waste time checking if the alternative exists.

Had those people in the comments been patient, they would have seen the explanation. Even if they just asked politely. For some reason people think it's their God given right to be rude to others on SO...

Upvotes: -3

Related Questions