java:睡眠直到网站完全加载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14047797/
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
java: Sleep until website is fully loaded
提问by Michael
I want to open a website with selenium and extract some text via xpath. It's working but I can get the text only if I wait a few seconds until the whole website is loaded, but it would be nicer to check if the website is fully loaded. I guess I should check for any background connections (ajax calls, GETs, POSTs or whatever), what is the best way to do it? At the moment I'm trying to extract the text in a while loop (ugly solution):
我想用 selenium 打开一个网站并通过 xpath 提取一些文本。它正在工作,但只有等待几秒钟直到整个网站加载完毕,我才能获取文本,但最好检查网站是否已完全加载。我想我应该检查任何后台连接(ajax 调用、GET、POST 或其他),最好的方法是什么?目前我正在尝试在 while 循环中提取文本(丑陋的解决方案):
WebDriver driver = new FirefoxDriver();
driver.get("http://www.website.com");
// Try to get text
while (true) {
try {
WebElement findElement = driver.findElement(By.xpath("expression-here"));
System.out.println(findElement.getText());
break;
// If there is no text sleep one second and try again
} catch (org.openqa.selenium.NoSuchElementException e) {
System.out.println("Waiting...");
Thread.sleep(1000);
}
}
How would you solve this?
你会如何解决这个问题?
回答by Walery Strauch
Selenium has already timeouts for this.
Selenium 已经为此超时。
Look here: http://seleniumhq.org/docs/04_webdriver_advanced.jsp
看这里:http: //seleniumhq.org/docs/04_webdriver_advanced.jsp
I have solve it with:
我已经解决了:
webDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
回答by Alex Okrushko
Prefer explicit waits:
1) more readable
2) been using those for long time
3) what if you know the element is not there (your test is to verify it) and don't need to poll for 10 seconds? With implicit you are now wasting time.
更喜欢显式等待:
1)更具可读性
2)长时间使用那些
3)如果你知道元素不存在(你的测试是为了验证它)并且不需要轮询 10 秒怎么办?使用隐式,您现在正在浪费时间。
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(new ExpectedCondition<WebElement>(){
@Override
public WebElement apply(WebDriver d) {
return d.findElement(By.id("myDynamicElement"));
}});