Python try/except: trying multiple options

前端 未结 1 658
梦毁少年i
梦毁少年i 2021-02-20 13:30

I\'m trying to scrape some information from webpages that are inconsistent about where the info is located. I\'ve got code to handle each of several possibilities; what I want

相关标签:
1条回答
  • 2021-02-20 14:23

    If each lookup is a separate function, you can store all the functions in a list and then iterate over them one by one.

    lookups = [
        look_in_first_place,
        look_in_second_place,
        look_in_third_place
    ]
    
    info = None
    
    for lookup in lookups:
        try:
            info = lookup()
            # exit the loop on success
            break    
        except AttributeError:
            # repeat the loop on failure
            continue
    
    # when the loop is finished, check if we found a result or not
    if info:
        # success
    else:
        # failure
    
    0 讨论(0)
提交回复
热议问题