问题描述
我正在编写一些Java Webdriver代码来使我的应用程序自动化.如何正确检查页面是否已加载?该应用程序也有一些Ajax调用.
I am writing some Java Webdriver code to automate my application. How can I correctly check whether the page has been loaded or not? The application has some Ajax calls, too.
我已经声明隐式等待WebDriver.
I have declared an implicit wait for WebDriver.
推荐答案
Selenium为您做到了.或者至少它会尽力而为.有时它不够用,您必须稍微帮助一下.常见的解决方案是 Implicit Wait
,它可以解决大多数问题.
Selenium does it for you. Or at least it tries its best. Sometimes it falls short, and you must help it a little bit. The usual solution is Implicit Wait
which solves most of the problems.
如果您真的知道自己在做什么,以及为什么要这么做,则可以尝试编写一个通用方法,该方法将检查页面是否已完全加载.但是,这并不是针对每个网络和每种情况都可以做到的.
If you really know what you're doing, and why you're doing it, you could try to write a generic method which would check whether the page is completely loaded. However, it can't be done for every web and for every situation.
相关问题: Selenium WebDriver :等待使用JavaScript(JS)加载复杂的页面,在那儿查看我的答案.
Related question: Selenium WebDriver : Wait for complex page with JavaScript(JS) to load, see my answer there.
更短的版本:您将永远不确定.
Shorter version: You'll never be sure.
正常"加载很容易- document.readyState
.当然,这是由Selenium实现的.有问题的是异步请求,AJAX,因为您永远无法判断它是否是永久完成的.当今的大多数网页都具有永久运行的脚本,并且始终会轮询服务器.
The "normal" load is easy - document.readyState
. This one is implemented by Selenium, of course. The problematic thing are asynchronous requests, AJAX, because you can never tell whether it's done for good or not. Most of today's webpages have scripts that run forever and poll the server all the time.
您可以做的各种事情都在上面的链接下.或者,与95%的其他人一样,使用 Implicit Wait
隐式和 Explicit Wait
+ ExpectedConditions
在需要的地方.
The various things you could do are under the link above. Or, like 95% of other people, use Implicit Wait
implicity and Explicit Wait
+ ExpectedConditions
where needed.
例如单击后,页面上的某些元素应该变得可见,您需要等待它:
E.g. after a click, some element on the page should become visible and you need to wait for it:
WebDriverWait wait = new WebDriverWait(driver, 10); // you can reuse this one
WebElement elem = driver.findElement(By.id("myInvisibleElement"));
elem.click();
wait.until(ExpectedConditions.visibilityOf(elem));
这篇关于如何检查网页驱动程序中是否已完全加载页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!