繁体   English   中英

Selenium NoSuchElement 异常仍在尝试块中抛出

[英]Selenium NoSuchElement exception is still being thrown in a try block

我正在尝试使用 try 和 except 来确保测试脚本即使在抛出异常时也能继续运行,但是我已经被问题困住了几天。 这就是问题所在,即使在 try 块中仍然会抛出“NoSuchElementException”,代码和屏幕截图附在下面。

从 selenium.common.exceptions 导入 NoSuchElementException

    try:         
        invalid = self.driver.find_element_by_css_selector("input[value='Maintain Agency']")
    except NoSuchElementException:
        print("Error detected")
    else:
        print("Nothing went wrong")

这是屏幕截图的链接:[1]: https://i.stack.imgur.com/cK3XS.png

我建议您查看此页面: https://www.toolsqa.com/selenium-webdriver/page-factory-in-selenium/

这很可能是因为在搜索元素时页面未正确加载。 您可能需要显式使用等待语句。

您可以尝试使用这样的等待:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get(WEBSITE_URL)

element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, "input[value='Maintain Agency']"))
)

暂无
暂无

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

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