【问题标题】:Selenium Fluent Wait Implementation in the code still gives "org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element:"代码中的 Selenium Fluent Wait Implementation 仍然给出“org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element:”
【发布时间】:2026-01-16 11:25:01
【问题描述】:

代码中提到的 URL 需要 5 秒来显示登录屏幕,为了在登录页面上输入详细信息,我在我的代码中实现了流畅的等待 10 秒。即使正确提到了等待,由于某种原因,这种等待没有被遵守,我总是显示 org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element:

代码:

public class FluentWaitDemo {

    public static void main(String[] args) throws InterruptedException 
    {

        WebDriverManager.chromedriver().setup();
        WebDriver driver = new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://app.hubspot.com/login");
        By email = By.xpath("//input[@type='email']");
        WebElement userId = FluentWaitForElement(driver, email);
        userId.sendKeys("*******@gmail.com");
        driver.close();
    }

    public static WebElement FluentWaitForElement(WebDriver driver, By locator)
    {
        Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                              .withTimeout(Duration.ofSeconds(10))
                              .pollingEvery(Duration.ofSeconds(2))
                              .ignoring(NoSuchElementException.class);

        return wait.until(ExpectedConditions.presenceOfElementLocated(locator));
    }
}

错误:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//input[@type='email']"}
  (Session info: chrome=83.0.4103.97)
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html

【问题讨论】:

  • 如果需要 10 秒才能得到,等待工作正常。我只会使用 webdriverwait ......它也是一个流利的等待,但已经设置了你需要的东西......忽略,轮询等......
  • 知道为什么上面的代码在正确提及所有内容时仍然没有抛出这样的元素异常。
  • 它会忽略 10 秒,是在 10 秒结束之前还是之后发生?
  • 10 秒后不抛出此类元素异常。理想情况下,我的代码应该禁止显示此消息,但仍然没有看到此类元素异常,因此...我无法在登录页面上输入电子邮件地址。这种情况由 Webdriverwait 完美处理,但我想了解我的代码在流畅等待时有什么问题。
  • 假设相同的 XPATH,不确定发生了什么... webdriverwait 确实将轮询设置为 1/2 秒,所以有可能在 8.5-9.5 秒时出现该选项?我也会尝试/捕捉 wait.until 调用,看看是否会引发超时。

标签: java selenium xpath css-selectors nosuchelementexception


【解决方案1】:

要在电子邮件地址字段中发送字符序列,您必须为elementToBeClickable() 引入WebDriverWait,您可以使用以下任一Locator Strategies

  • 使用cssSelector

    driver.get("https://app.hubspot.com/login");
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input#username"))).sendKeys("Bimlesh@gmail.com");
    
  • 使用xpath

    driver.get("https://app.hubspot.com/login");
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@id='username']"))).sendKeys("Bimlesh@gmail.com");
    

浏览器快照:


参考

您可以在NoSuchElementException 上找到一些详细的讨论:

【讨论】:

    最近更新 更多