繁体   English   中英

Try-except不会在for循环内重新运行整个代码

[英]Try-except doesn't re-run the entire code inside a for loop

我真的是Python和编写代码的新手,在遇到异常之后,这段代码似乎并没有重新运行。 我希望它在遇到异常后从try函数重新开始。 在代码运行的这40个Web元素中,也许像4-5一样没有此元素(id =“ tt_single_values_spent)并会给出NoSuchElementException。我想要的是,一旦我的代码遇到错误,它将跳过该错误并继续收集信息。我100%确信问题出在代码而不是网站本身。

for i in range(40):
    try:
        act4 = browser.find_element_by_css_selector('dd[id="tt_single_values_spent"]').get_attribute('innerText')
        time_log = re.sub('h', '', act4)
        if time_log != str("Not Specified"):
           total_time.append(float(time_log))
           print(act4)
        pyautogui.press("down", 1);time.sleep(0.5)
    except NoSuchElementException:
        print('Not found')
My result:
1h
45h
4h
13h
1h
31.8h
34.2h
5h
Not found
Not found
Not found
Not found
Not found
Not found
Not found

您的代码在遇到单个“未找到”元素时反复输出“未找到”的原因是,您的代码仅在try块中推进了元素。

相反,您应该始终前进。 您可以使用finally块或try-except块之外的代码来执行此操作:

for i in range(40):
    try:
        act4 = browser.find_element_by_css_selector('dd[id="tt_single_values_spent"]').get_attribute('innerText')
        time_log = re.sub('h', '', act4)
        if time_log != str("Not Specified"):
           total_time.append(float(time_log))
        print(act4)
    except NoSuchElementException:
        print('Not found')
    finally:
        pyautogui.press("down", 1)
        time.sleep(0.5)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM