等待使用Selenium加载元素

时间:2015-05-28 10:11:16

标签: java selenium selenium-webdriver

我在这里看得很清楚但是他们的web元素等待似乎不适合我的代码。

我是Java和Selenium的新手。我想在它超时之前尝试等待元素进入我的代码。

有什么建议吗?

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

eventOccured

3 个答案:

答案 0 :(得分:5)

您需要使用WebDriverWait。例如,明确等待元素变为可见:

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

String actualValue = element.getText();

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

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

答案 1 :(得分:1)

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

显式等待的示例 -

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

流利等待的示例 -

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

查看此TUTORIAL了解详情。

答案 2 :(得分:0)

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

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

<强>睡眠 在这种情况下,Thread.sleep(2000L);使用throws InterruptedException

希望它会有所帮助