`

selenium webdriver学习(十一)------------如何等待页面元素加载完成

阅读更多

web的自动化测试中,我们经常会遇到这样一种情况:当我们的程序执行时需要页面某个元素,而此时这个元素还未加载完成,这时我们的程序就会报错。怎么办?等待。等待元素出现后再进行对这个元素的操作。

在selenium-webdriver中我们用两种方式进行等待:明确的等待和隐性的等待。


明确的等待


明确的等待是指在代码进行下一步操作之前等待某一个条件的发生。最不好的情况是使用Thread.sleep()去设置一段确认的时间去等待。但为什么说最不好呢?因为一个元素的加载时间有长有短,你在设置sleep的时间之前要自己把握长短,太短容易超时,太长浪费时间。selenium webdriver提供了一些方法帮助我们等待正好需要等待的时间。利用WebDriverWait类和ExpectedCondition接口就能实现这一点。



下面的html代码实现了这样的一种效果:点击click按钮5秒钟后,页面上会出现一个红色的div块。我们需要写一段自动化脚本去捕获这个出现的div,然后高亮之。

Wait.html:



<html>  
   <head>  
       <title>Set Timeout</title>  
       <style>  
           .red_box {background-color: red; width = 20%; height: 100px; border: none;}  
       </style>  
       <script>  
            function show_div(){  
                setTimeout("create_div()", 5000);  
            }  
    
            function create_div(){  
                d = document.createElement('div');  
                d.className = "red_box";  
                document.body.appendChild(d);  
            }  
        </script>  
    </head>  
    <body>  
        <button id = "b" onclick = "show_div()">click</button>  
    </body>  
</html>  

 
 

下面的代码实现了高亮动态生成的div块的功能:

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class TestWait {

	public static void main(String[] args) {
		WebDriver driver = new FirefoxDriver();
		String url = "file:/C:/Users/jgong/Desktop/wait.html";
		driver.get(url);

		WebDriverWait wait = new WebDriverWait(driver, 10);

		driver.findElement(By.id("b")).click();

		WebElement wl = wait.until(new ExpectedCondition<WebElement>() {

			@Override
			public WebElement apply(WebDriver d) {
				return d.findElement(By.cssSelector(".red_box"));
			}
		});

		((JavascriptExecutor) driver).executeScript(
				"arguments[0].style.border='5px solid yellow'", wl);

	}

}

 
隐性的等待
隐性的等待其实就相当于设置全局的等待,在定位元素时,对所有元素设置超时时间。

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class TestWait {

	public static void main(String[] args) {
		WebDriver driver = new FirefoxDriver();
		// 设置10秒
		driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

		String url = "file:/C:/Users/jgong/Desktop/wait.html";
		driver.get(url);

		driver.findElement(By.id("b")).click();

		/*
		 * WebDriverWait wait = new WebDriverWait(driver, 10); WebElement wl =
		 * wait.until(new ExpectedCondition<WebElement>() {
		 * 
		 * @Override public WebElement apply(WebDriver d) { return
		 * d.findElement(By.cssSelector(".red_box")); } });
		 */

		WebElement wl = driver.findElement(By.cssSelector(".red_box"));
		((JavascriptExecutor) driver).executeScript(
				"arguments[0].style.border='5px solid yellow'", wl);

	}

}

 

两者选其一,第二种看起来一劳永逸呀。哈哈

 

分享到:
评论
10 楼 qi_ling2005 2013-11-26  
wb136959813 写道
JF,

是的
9 楼 wb136959813 2013-08-30  
JF,
8 楼 stephenwang1011 2013-01-29  
没有转载 按钮呢
7 楼 qi_ling2005 2012-08-28  
duangang312 写道
什么意思,是指所有的findElement操作都会默认等待10秒?


就是查找的最大时间是10秒。找到马上返回。找不到最多找10秒,报错
6 楼 duangang312 2012-08-21  
什么意思,是指所有的findElement操作都会默认等待10秒?
5 楼 qi_ling2005 2012-07-16  
shine22fmf 写道
运行第一个脚本的时候,可以正常运行并显示,但是下面也有错误
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"css selector","selector":".red_box"}
Command duration or timeout: 16 milliseconds
这是啥意思呢?


没有找到页面的元素,超时了
4 楼 shine22fmf 2012-07-13  
老师,第二个脚本可以正常显示,下面一个红条子,边缘是黄色的,第一个确实没有,请教下。
3 楼 shine22fmf 2012-07-13  
运行第一个脚本的时候,可以正常运行并显示,但是下面也有错误
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"css selector","selector":".red_box"}
Command duration or timeout: 16 milliseconds
这是啥意思呢?
2 楼 qi_ling2005 2012-05-11  
uniquepig 写道
博主 用隐性等待是查找之前会等么 不管元素出现与否?

对的,如果一个无素没有出现都会默认等待你所设定的时间,直到超时或者元素出现
1 楼 uniquepig 2012-05-11  
博主 用隐性等待是查找之前会等么 不管元素出现与否?

相关推荐

    Selenium WebDriver Practical Guide-Code

    通过深入研究这个压缩包中的代码示例,学习者不仅可以理解Selenium WebDriver的工作原理,还能掌握如何在实际项目中应用这些知识,提升自动化测试的技能。同时,这也有助于理解和调试测试脚本,解决在自动化测试过程...

    selenium webdriver 学习

    1.11 selenium webdriver学习(十一)------------如何等待页面元素加载完成 . . . . . . . . . . . . . . . . . .33 1.12 selenium webdriver学习(十二)------------如何利用selenium-webdriver截图 . . . . . . ...

    selenium-webdriver-api文档

    此外,还有`implicitly_wait`和`WebDriverWait`机制,用于设置等待时间,确保元素在执行操作前已经加载完成。 ### 6. 断言与验证 虽然WebDriver本身并不包含断言功能,但可以结合第三方库(如Python的unittest或...

    selenium WebDriver原理介绍

    此外,还能处理异步加载的页面元素,等待特定元素出现或消失,确保测试的准确性。 6. **异常处理**: 在测试过程中,WebDriver 会捕获并处理可能出现的错误和异常,例如找不到元素、超时等,这有助于调试和优化...

    Selenium-3.11.0-Java源码包

    3. **Support Classes**:Selenium 提供了一些辅助类来帮助编写测试脚本,如 ExpectedConditions、 WebDriverWait 和 FluentWait,这些可以帮助处理异步加载的页面和元素。 4. **Browser Specific Drivers**:每个...

    selenium webdriver第三版

    总之,《Selenium WebDriver(Python)第三版》这本书是学习和掌握Selenium WebDriver与Python结合进行Web自动化测试的宝贵资源,它不仅讲解了基础操作,还涵盖了高级特性和实战经验,对提升测试工程师的技能大有裨益...

    selenium webdriver基于python源码案例.zip

    5. **等待技术**:讲解显式等待(`WebDriverWait`)和隐式等待的概念,以及在实际测试中如何灵活运用它们,确保元素加载完成后再进行操作。 6. **异常处理**:介绍如何编写健壮的测试脚本,包括错误捕获和异常处理...

    selenium webdriver

    ### Selenium WebDriver 知识点详解 #### 一、Selenium WebDriver 概述 - **定义**: Selenium WebDriver 是一个用于自动化 Web 测试的工具,它直接与浏览器交互,模拟真实用户的操作行为,支持多种浏览器和平台。 ...

    selenium-webdriver-java api文档

    Selenium提供了等待功能,确保元素在执行操作前已经加载完成。`WebDriverWait`和`ExpectedConditions`配合使用,可实现智能等待。 ```java WebDriverWait wait = new WebDriverWait(driver, 10); wait.until...

    selenium-WebDriver的API文档

    同时,为了确保元素加载完成,可以使用`WebDriverWait`进行等待,如`WebDriverWait(driver, timeout).until(condition)`。 **6. JMeter 中文使用手册** JMeter 是一个功能强大的性能测试工具,可以用来模拟大量并发...

    selenium_webdriver学习

    比如,使用`implicitly_wait`设置隐式等待,等待页面元素加载完成;使用`switch_to.frame()`切换到iframe;使用`switch_to.alert`处理弹窗;使用try-except语句捕获和处理可能出现的错误。 在软件测试中,Selenium ...

    selenium-webdriver-java-course:我的免费Selenium WebDriver for Java教程的源代码-java source code

    当网页元素是动态加载或者页面加载时间较长时,源代码将展示如何等待元素可见或页面完全加载,使用`WebDriverWait`和`ExpectedConditions`等工具。 7. **异常处理** 在编写自动化测试时,错误和异常处理是必不可...

    Selenium WebDriver精讲

    这种等待策略有助于避免由于页面元素尚未加载完成而导致的测试失败问题。 **智能等待技术**: - 使用显式等待(Explicit Wait)。 - 使用隐式等待(Implicit Wait)。 - 使用Fluent Wait等更灵活的等待机制。 ####...

    selenium-java-2.41.0,selenium-java-2.33

    7. **等待与同步**:在自动化测试中,网页加载和元素出现的时间可能不固定,因此Selenium提供了显式等待和隐式等待机制,确保在执行操作前元素已经准备好。 8. **测试框架集成**:Selenium可以很好地与JUnit、...

    selenium2.44 webdriver

    6. **断言验证**:使用断言库验证页面元素的状态或内容。 7. **关闭和退出**:测试完成后,使用`quit()`方法关闭浏览器实例。 **5. 示例代码** ```python from selenium import webdriver # 创建FirefoxDriver...

    Mastering-Selenium-Webdrivers-3.0-V-:Packt出版的Mastering Selenium Webdrivers 3.0(V)的代码存储库

    3. **元素交互**:掌握如何与页面元素进行交互,如输入文本、提交表单、点击链接、选择复选框和单选按钮等。 4. **断言和验证**:学习如何使用各种断言方法来验证页面状态,确保测试用例的正确性。 5. **处理弹出...

    selenium webdriver基于python源码案例

    Selenium WebDriver ...元素定位是用于定位网页元素的,元素操作是用于模拟用户操作的,等待机制是用于等待元素加载的。 本教程将指导您如何安装和使用 Selenium,如何编写自动化测试脚本,以及如何解决常见的问题。

Global site tag (gtag.js) - Google Analytics