我可以使用try / except重新启动python代码吗?

时间:2018-10-12 03:13:42

标签: python error-handling try-catch try-except

我有一个程序,可以转到reddit.com网站并从中获取一个html元素。但是,大约有1/10的时间,旧的reddit网站出现了,我必须重新启动该程序。有没有更短的方法来处理此错误(基本上从顶部重新开始)?我似乎无法通过try / except弄清楚。

browser = webdriver.Chrome(executable_path=r'C:\Users\jacka\Downloads\chromedriver_win32\chromedriver.exe')

browser.get("https://www.reddit.com/")

# grabs the html tag for the subreddit name
elem = browser.find_elements_by_css_selector("a[data-click-id='subreddit']")

#in the case that old reddit loads, it restarts the browser.
if len(elem) == 0:
    browser.close()

    browser = webdriver.Chrome(executable_path=r'C:\Users\jacka\Downloads\chromedriver_win32\chromedriver.exe')

    browser.get("https://www.reddit.com/")

    # grabs the html tag for the subreddit name
    elem = browser.find_elements_by_css_selector("a[data-click-id='subreddit']")

2 个答案:

答案 0 :(得分:1)

就像@HSK在评论中提到的那样,您可以使用无限while循环来不断尝试,直到获得所需的内容为止。离开前,请添加一个finally子句以关闭browser句柄。

while True:
    browser = webdriver.Chrome(executable_path=r'C:\Users\jacka\Downloads\chromedriver_win32\chromedriver.exe')
    try:
        browser.get("https://www.reddit.com/")
        elem = browser.find_elements_by_css_selector("a[data-click-id='subreddit']")
        break
    except Exception:
        pass
    finally:
        browser.close()

答案 1 :(得分:0)

感谢@HSK。我将代码放入while循环中,直到获得正确版本的reddit为止。

#had to initalize elem so the loop would run
elem = ""
while len(elem) == 0:
    browser = webdriver.Chrome(executable_path=r'C:\Users\jacka\Downloads\chromedriver_win32\chromedriver.exe')

    browser.get("https://www.reddit.com/")

    # grabs the html tag for the subreddit name
    elem = browser.find_elements_by_css_selector("a[data-click-id='subreddit']")