如何在网页未完全加载时强制WebDriver执行命令?

时间:2013-08-30 16:21:04

标签: java selenium

网页从上到下加载。

1) <html ...
2) <head ...
3) <body ...
  etc

我需要我的WebDriver明确等待<title标记可见。然后阅读标题的内容,继续执行其他操作 ,而无需等待整个页面加载!!!

WebDriver driver = new ChromeDriver();
driver.get("http://");
WebDriverWait wait = new WebDriverWait(driver, 0) // This line is probably the one to be transformed in order to correspond to my requirements
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//title")));
// The problem is that the following commands do not start off until the whole page is loaded
if(driver.getTitle().equals("whatever")) {
driver.get("http://");
}
else {
...
}

1 个答案:

答案 0 :(得分:1)

您可以使用pageLoadTimeout。将超时设置为0,然后捕获TimeoutException,然后执行特定的标题声明等。

driver.manage().timeouts().pageLoadTimeout(0, TimeUnit.SECONDS);

<强>更新

driver.manage().timeouts().pageLoadTimeout(0, TimeUnit.SECONDS);
WebDriverWait wait = new WebDriverWait(driver, 30);
try {
    driver.get("http://");
} catch (TimeoutException e) {
    wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//title")));
}

了解更多info

理想情况下,您应该使用ExpectedConditions.titleIs() 有关可用选项的更多信息,请访问here