java 使用 Selenium 等待元素加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30503518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:14:29  来源:igfitidea点击:

Waiting for an element to load using Selenium

javaseleniumselenium-webdriver

提问by afcbpete

I've had a good look through here but the web element waits don't seem to fit into my code.

我已经仔细浏览了此处,但 Web 元素等待似乎不适合我的代码。

I'm fairly new to Java and Selenium. I want to try and get a wait for element into my code before it times out.

我对 Java 和 Selenium 还很陌生。我想尝试在它超时之前将等待元素放入我的代码中。

Any suggestions?

有什么建议?

It's crashing when it hits this point because the page does take a while to search for this address.

当它到达这一点时它会崩溃,因为该页面确实需要一段时间来搜索此地址。

@Step ("Verifying landmark")
public void validatingLandmark(String s){
    String actualValue = getDriver().findElement(By.id("MainContent_lblLandmarkUPRN")).getText();
    assertEquals(s, actualValue);
    TimeOut();
}

回答by alecxe

You need to use WebDriverWait. For instance, explicitly wait for an element to become visible:

您需要使用WebDriverWait. 例如,显式等待元素变为可见:

WebDriverWait wait = new WebDriverWait(getDriver(), timeOut);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("MainContent_lblLandmarkUPRN")));

String actualValue = element.getText();

You can also use textToBePresentInElementExpected Condition:

您还可以使用textToBePresentInElement预期条件:

WebElement element = wait.until(ExpectedConditions.textToBePresentInElement(By.id("MainContent_lblLandmarkUPRN"), s));

回答by anuja jain

You can use Explicit wait or Fluent Wait

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

Example of Explicit Wait -

显式等待示例 -

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

Example of Fluent Wait -

Fluent 等待示例 -

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"));     
 }  
});  

Check this TUTORIALfor more details.

查看此教程以获取更多详细信息。

回答by Kumrun Nahar Keya

You can use implicit wait or sleep here

您可以在此处使用隐式等待或睡眠

Implicit wait:driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

隐式等待:driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

SleepThread.sleep(2000L);in this case use throws InterruptedException

SleepThread.sleep(2000L);在这种情况下使用 throws InterruptedException

Hope it will help

希望它会有所帮助