Javascript Selenium:我如何告诉Selenium等待按钮元素?

Javascript Selenium:我如何告诉Selenium等待按钮元素?,javascript,jquery,selenium,selenium-webdriver,browser-automation,Javascript,Jquery,Selenium,Selenium Webdriver,Browser Automation,我有一个验证按钮,在我点击它后(点击它后,它会显示一个包含元素的网格),会有一些延迟,然后会出现一个NEXT按钮,该按钮会重定向到下一页。我有以下代码: ((JavascriptExecutor)driver).executeScript("arguments[0].click()",driver.findElement(By.cssSelector("div#button-verify-wrapper > a"))); Thread.sleep(18000); driver.findEl

我有一个验证按钮,在我点击它后(点击它后,它会显示一个包含元素的网格),会有一些延迟,然后会出现一个
NEXT
按钮,该按钮会重定向到下一页。我有以下代码:

((JavascriptExecutor)driver).executeScript("arguments[0].click()",driver.findElement(By.cssSelector("div#button-verify-wrapper > a")));
Thread.sleep(18000);
driver.findElement(By.xpath(".//*[@id='select-a-data-source-footer']/div/div/a")).click();
Thread.sleep(5000);
但是我想点击
NEXT
按钮,在所有的网格充电之后(这需要一段时间,取决于当时的服务器),因为NEXT按钮只在网格出现之后出现


是否有selenium语句可以做到这一点?

selenium提供以下两种类型:-

  • :-

    显式等待是您定义的代码,用于在继续执行代码之前等待特定条件发生。最糟糕的情况是
    Thread.sleep()
    ,它将条件设置为等待的确切时间段。提供了一些方便的方法,可以帮助您编写只在需要时等待的代码。结合使用是实现这一目标的一种方法。因此,您应该尝试:-

    WebDriverWait wait = WebDriverWait(drive, 10);
    wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("div#button-verify-wrapper > a"))).click();
    
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath(".//*[@id='select-a-data-source-footer']/div/div/a"))).click();
    //Now find further element with WebDriverWait for the process
    
  • :-

    隐式等待是告诉
    WebDriver
    在尝试查找一个或多个元素(如果它们不立即可用)时轮询
    DOM
    一段时间。默认设置为0。一旦设置,隐式等待将被设置为
    WebDriver
    对象实例的生命周期

    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
    
    driver.findElement(By.cssSelector("div#button-verify-wrapper > a"))).click();
    driver.findElement(By.xpath(".//*[@id='select-a-data-source-footer']/div/div/a")).click();
    //Now find further element for the process 
    

我主张显式等待,您甚至可以使用显式等待将其作为一种常用方法进行重用。许多与click的交互都会有一个显式的等待,等待元素变得可点击。虽然不推荐,但我确实理解,在更好的方法实现之前,Thread.sleep可能是唯一可行的选择

一个是Saurabh Gaur提到的WebDriverWait。另一个类似的选项提供了更细粒度的控制和自定义轮询

另一个是FluentWait:


但请注意,使用FluentWait,您可能会被愚弄,以为可以忽略其他类异常,例如StaleElementReference,编译器不会抱怨。StaleElementReference仍然可以发生,TimeoutException类也是如此。

我建议您使用FluentWait语句嘿,谢谢您的回答。我尝试了“隐式等待”,它给了我这个异常:当您要单击时,异常状态元素当前不可见,您应该按照这里的建议尝试显式等待,并让我知道..不,它不是同一个错误,它看起来像是在某处抛出空指针异常,检查它,它可能在另一行代码上。
// Waiting 30 seconds for an element to be present on the page, checking
   // for its presence once every 5 seconds.
   Wait wait = new FluentWait(driver)
       .withTimeout(30, SECONDS)
       .pollingEvery(5, SECONDS)
       .ignoring(NoSuchElementException.class);

   WebElement foo = wait.until(new Function() {
     public WebElement apply(WebDriver driver) {
       return driver.findElement(By.id("foo"));
     }
   });