get(url) 方法等待网页完全加载。如果页面上有很多东西,加载速度可能会很慢。
有没有办法导航到目标网页并只等待感兴趣的 WebElement? (即不是横幅、广告等)
谢谢!
最佳答案
您可以使用 Page load timeout .据我所知,FirefoxDriver
和 InternetExplorerDriver
肯定支持此功能,但我不确定其他驱动程序是否支持。
driver.manage().timeouts().pageLoadTimeout(0, TimeUnit.MILLISECONDS);
try {
driver.get("http://google.com");
} catch (TimeoutException ignored) {
// expected, ok
}
或者您可以使用 JavaScript 执行非阻塞页面加载:
private JavascriptExecutor js;
// I like to do this right after driver is instantiated
if (driver instanceof JavascriptExecutor) {
js = (JavascriptExecutor)driver;
}
// later, in the test, instead of driver.get("http://google.com");
js.executeScript("window.location.href = 'http://google.com'");
这两个示例都会加载 Google,但它们会立即将对 driver
实例的控制返回给您,而不是等待整个页面加载。然后,您只需等待您正在寻找的一个元素即可。
如果您不希望只在 WebDriver#get()
上使用此功能,但您也想要一个非阻塞的 click()
,您可以这样做其中之一:
- 如上所示使用页面加载超时。
使用 The Advanced User Interactions API ( JavaDocs )
WebElement element = driver.findElement(By.whatever("anything")); new Actions(driver).click(element).perform();
再次使用 JavaScript:
WebElement element = driver.findElement(By.whatever("anything")); js.executeScript("arguments[0].click()", element);
关于java - Selenium WebDriver get(url) 速度问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19311161/