WebDriver - 使用Java等待元素

tom*_*tom 73 java webdriver selenium-webdriver

我正在寻找类似于waitForElementPresent检查元素是否在我点击之前显示的东西.我认为这可以通过implicitWait,所以我使用以下内容:

driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
Run Code Online (Sandbox Code Playgroud)

然后单击

driver.findElement(By.id(prop.getProperty(vName))).click();
Run Code Online (Sandbox Code Playgroud)

不幸的是,有时它等待元素,有时候不等.我找了一会儿找到了这个解决方案:

for (int second = 0;; second++) {
            Thread.sleep(sleepTime);
            if (second >= 10)
                fail("timeout : " + vName);
            try {
                if (driver.findElement(By.id(prop.getProperty(vName)))
                        .isDisplayed())
                    break;
            } catch (Exception e) {
                writeToExcel("data.xls", e.toString(),
                        parameters.currentTestRow, 46);
            }
        }
        driver.findElement(By.id(prop.getProperty(vName))).click();
Run Code Online (Sandbox Code Playgroud)

它等了很久,但在超时前它必须等待5次,50秒.有点多.所以我把隐式等待设置为1秒,直到现在一切都好了.因为现在有些事情在超时之前等待10秒,但是其他一些事情在1秒之后会超时.

您如何覆盖代码中存在/可见元素的等待?任何提示都很明显.

Ash*_*bhu 138

这就是我在代码中的做法.

WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));
Run Code Online (Sandbox Code Playgroud)

要么

wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));
Run Code Online (Sandbox Code Playgroud)

确切地说.

也可以看看:

  • 谢谢!如果我早点知道这门课,我的生活会更轻松:) (2认同)

anu*_*ain 9

您可以使用显式等待或流利等待

显式等待的示例 -

WebDriverWait wait = new WebDriverWait(WebDriverRefrence,20);
WebElement aboutMe;
aboutMe= wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("about_me")));     
Run Code Online (Sandbox Code Playgroud)

流利等待的例子 -

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)                            
.withTimeout(20, TimeUnit.SECONDS)          
.pollingEvery(5, TimeUnit.SECONDS)          
.ignoring(NoSuchElementException.class);    

  WebElement aboutMe= wait.until(new Function<WebDriver, WebElement>() {       
public WebElement apply(WebDriver driver) { 
return driver.findElement(By.id("about_me"));     
 }  
});  
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请查看此教程.

  • 此方法已被弃用。 (2认同)

and*_*rej 5

我们有很多比赛条件elementToBeClickable。见https://github.com/angular/protractor/issues/2313。即使有些蛮力,沿着这些思路的工作也相当不错

Awaitility.await()
        .atMost(timeout)
        .ignoreException(NoSuchElementException.class)
        .ignoreExceptionsMatching(
            Matchers.allOf(
                Matchers.instanceOf(WebDriverException.class),
                Matchers.hasProperty(
                    "message",
                    Matchers.containsString("is not clickable at point")
                )
            )
        ).until(
            () -> {
                this.driver.findElement(locator).click();
                return true;
            },
            Matchers.is(true)
        );
Run Code Online (Sandbox Code Playgroud)