简体   繁体   English

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

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

I'm really new to Python and writing code, and this code doesn't seem to rerun through all the lines after it hits the exception. 我真的是Python和编写代码的新手,在遇到异常之后,这段代码似乎并没有重新运行。 I want it to start again from the try function after it hits the exception. 我希望它在遇到异常后从try函数重新开始。 Among these 40 web elements that the code is running through, maybe like 4-5 do not have this element (id="tt_single_values_spent) and will giveNoSuchElementException. What I want is that once my code will hit the error, it will skip it and continue to gather the information. I am 100% sure the problem is with the code and not the site itself . 在代码运行的这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

The reason your code repeatedly outputs "Not found" once it encounters a single "Not found" element, is that your code only advances elements within the try block. 您的代码在遇到单个“未找到”元素时反复输出“未找到”的原因是,您的代码仅在try块中推进了元素。

Instead, you should always advance. 相反,您应该始终前进。 You can do this with a finally block, or with code outside of the try-except block: 您可以使用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