前言

在自动化测试中,我们经常会碰到编写脚本过程中操作某个元素的时候, 需要等待页面加载完成后,才能对元素操作,否则会报错,提示页面元素不存在异常,我们需要等待元素加载完成后,
才能继续操作,而Selenium为我们提供了对应的等待方法,来判断元素是否存在。

下面将用一个例子,针对元素等待操作做逐一讲解

实际案例

场景:点击【创建div】按钮,3秒后,页面会出现一个绿色的div块,同时显示文字“我是div,我出现了,哈哈!”,我们需要代码去判断这个div是否存在, 然后高亮,并正常显示文字。

被测html代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>等待练习案例</title>
</head>
<style type="text/css">
#green_box {
background-color: chartreuse;
width: 400px;
height: 200px;
border: none;
}
</style> <script type="application/javascript">
function wait_show() {
setTimeout("create_div()", 3000);
} function create_div() {
var divElement = document.createElement('div');
divElement.id = "green_box";
var pElement = document.createElement('p');
pElement.innerText = "我是div,我出现了,哈哈!";
document.body.appendChild(divElement);
divElement.appendChild(pElement);
}
</script>
<body>
<button onclick="wait_show()">创建div</button>
</body>
</html>

  

1、强制等待

强制等待,就是硬等待,使用方法Thread.sleep(int sleeptime),使用该方法会让当前执行进程暂停一段时间(你设定的暂停时间)。弊端就是,你不能确定元素多久能加载完全,如果两秒元素加载出来了,你用了30秒,造成脚本执行时间上的浪费。

具体示例代码如下:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; public class TestWaitDemo { WebDriver driver;
@BeforeClass
public void beforeClass(){
System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe");
driver = new ChromeDriver();
} @Test
public void testByThread() {
//打开测试页面
driver.get("file:///C:/Users/Administrator/Desktop/waitDemo.html");
driver.manage().window().maximize();
driver.findElement(By.id("wait")).click();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//获得div块级元素
WebElement element = driver.findElement(By.id("green_box"));
//获取该元素css样式中background-color属性值
String cssValue = element.getCssValue("background-color");
//输出属性值
System.out.println("cssValue: "+cssValue);
} @AfterClass
public void afterClass(){
driver.quit();
}
}

2、页面等待

有时候我们打开一个网页,网页本身加载速度就比较慢,只能等网页完全加载完毕,才能执行操作,那么就可以用pageLoadTimeout(pageLoadTime,TimeUnit.SECONDS)这个方法,如在设定时间内,网页还没有还没完全加载就会报错,剩下的时间将不再等待。

具体示例代码如下:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; public class TestWaitDemo { WebDriver driver;
@BeforeClass
public void beforeClass(){
System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe");
driver = new ChromeDriver();
} @Test
public void testByPageLoad() {
//打开测试页面
driver.get("file:///C:/Users/Administrator/Desktop/waitDemo.html");
//设置等待时间为3秒,如果3秒页面没有全部加载出来,就会报错,如果小于3秒就全部加载出来了,剩下的时间将不再等待,继续下一步操作
driver.manage().timeouts().pageLoadTimeout(3, TimeUnit.SECONDS);
driver.manage().window().maximize();
} @AfterClass
public void afterClass(){
driver.quit();
}
}

3、隐式等待

WebDriver 提供了三种隐性等待方法:

  • implicitlyWait

识别对象时的超时时间。过了这个时间如果对象还没找到的话就会抛出NoSuchElement 异常。

  • setScriptTimeout

异步脚本的超时时间。WebDriver 可以异步执行脚本,这个是设置异步执行脚本,脚本返回结果的超时时间。

  • pageLoadTimeout

页面加载时的超时时间。因为 WebDriver 会等页面加载完毕再进行后面的操作,所以如果页面超过设置时间依然没有加载完成,那么 WebDriver 就会抛出异常。

隐式等待(implicit),方法implicitlyWait(long time, TimeUnit.SECONDS),即全局设置,对整个driver都有作用,如在设定时间内,特定元素没有加载完成,则抛出异常,如果元素加载完成,剩下的时间将不再等待。

具体示例代码如下:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; public class TestWaitDemo { WebDriver driver;
@BeforeClass
public void beforeClass(){
System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe");
driver = new ChromeDriver();
} @Test
public void testByImplicitlyWait() {
//打开测试页面
driver.get("file:///C:/Users/Administrator/Desktop/waitDemo.html");
//设置等待时间为3秒,如果3秒元素没有加载出来,就会报错,如果小于3秒元素加载出来了,剩下的时间将不再等待,继续下一步操作
driver.manage().timeouts().implicitlyWait(3, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.findElement(By.id("wait")).click();
//获得div块级元素
WebElement element = driver.findElement(By.id("green_box"));
//获取该元素css样式中background-color属性值
String cssValue = element.getCssValue("background-color");
//输出属性值
System.out.println("cssValue: "+cssValue);
} @AfterClass
public void afterClass(){
driver.quit();
}
}

4、显式等待

显示等待,就是明确的要等到某个元素的出现或者是某个元素的可点击等条件等到为止,才会继续执行后续操作,等不到,就一直等,除非在规定的时间之内都没找到,那么就抛出异常了

方法一:

具体代码如下:

package com.brower.demo;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; public class TestWaitDemo { WebDriver driver; @BeforeClass
public void beforeClass() {
System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe");
driver = new ChromeDriver();
} @Test
public void testByShowWaiting() {
//打开测试页面
driver.get("file:///C:/Users/Administrator/Desktop/waitDemo.html");
driver.manage().window().maximize();
driver.findElement(By.id("wait")).click();
/**
*等待时间为3秒,WebDriverWait默认每500ms就调用一次ExpectedCondition直到定位到div,如果3秒内div显示出来,则继续下一步,
* 如果超过3秒没有显示出来,那么则until()会抛出org.openqa.selenium.TimeoutExceptionn异常
*/
WebDriverWait wait = new WebDriverWait(driver, 3);
//元素是否存在,如果超过设置时间检测不到则抛出异常。
wait.until(new ExpectedCondition<WebElement>() {
@Override
public WebElement apply(WebDriver driver) {
//重写方法
return driver.findElement(By.id("green_box"));
}
});
//获得div块级元素
WebElement element = driver.findElement(By.id("green_box"));
//获取该元素css样式中background-color属性值
String cssValue = element.getCssValue("background-color");
//输出属性值
System.out.println("cssValue: " + cssValue);
} @AfterClass
public void afterClass() {
driver.quit();
}
}

方法二

示例代码如下:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; public class TestWaitDemo { WebDriver driver; @BeforeClass
public void beforeClass() {
System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe");
driver = new ChromeDriver();
} @Test
public void testByShowWaiting() {
//打开测试页面
driver.get("file:///C:/Users/Administrator/Desktop/waitDemo.html");
driver.manage().window().maximize();
driver.findElement(By.id("wait")).click();
/**
*等待时间为3秒,WebDriverWait默认每500ms就调用一次ExpectedCondition直到定位到div,如果3秒内div显示出来,则继续下一步,
* 如果超过3秒没有显示出来,那么则until()会抛出org.openqa.selenium.TimeoutExceptionn异常
*/
WebDriverWait wait = new WebDriverWait(driver, 3);
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("green_box")));
//获得div块级元素
WebElement element = driver.findElement(By.id("green_box"));
//获取该元素css样式中background-color属性值
String cssValue = element.getCssValue("background-color");
//输出属性值
System.out.println("cssValue: " + cssValue);
} @AfterClass
public void afterClass() {
driver.quit();
}
}

显式等待使用ExpectedConditions类中自带方法, 可以进行显式等待的判断,常用的判断条件如下表:

等待的条件方法名称 描述
elementToBeClickable(By locator) 页面元素是否在页面上可用和可被单击
elementToBeSelected(WebElement element) 页面元素处于被选中状态
presenceOfElementLocated(By locator) 页面元素在页面中存在
textToBePresentInElement(By locator) 在页面元素中是否包含特定的文本
textToBePresentInElementValue(By locator, java.lang.String text) 页面元素值
titleContains(java.lang.String title)   标题 (title)

显式等待常跟以下三种方法一起使用,用来判断元素

  • isEnable()    检查元素是否被启用
  • isSelected()   检查元素是否被选中
  • isDisplay()     检查元素是否可见

运行结果

selenium Java中常见等待的几种形式的更多相关文章

  1. Java中常见的5种WEB服务器介绍

    这篇文章主要介绍了Java中常见的5种WEB服务器介绍,它们分别是Tomcat.Resin.JBoss.WebSphere.WebLogic,需要的朋友可以参考下 Web服务器是运行及发布Web应用的 ...

  2. java中常见的六种线程池详解

    之前我们介绍了线程池的四种拒绝策略,了解了线程池参数的含义,那么今天我们来聊聊Java 中常见的几种线程池,以及在jdk7 加入的 ForkJoin 新型线程池 首先我们列出Java 中的六种线程池如 ...

  3. java中for循环的6种写法

    有些写法上的说明写的过于武断,可能有很多不当之处,仅供参考.   package ForLoop; import java.util.ArrayList; import java.util.Itera ...

  4. Java基础-JAVA中常见的数据结构介绍

    Java基础-JAVA中常见的数据结构介绍 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.什么是数据结构 答:数据结构是指数据存储的组织方式.大致上分为线性表.栈(Stack) ...

  5. Java 中的等待唤醒机制透彻讲解

    线程的状态 首先了解一下什么是线程的状态,线程状态就是当线程被创建(new),并且启动(start)后,它不是一启动就进入了执行状态(run),也不是一直都处于执行状态. 这里说一下Java 的Thr ...

  6. Java中Compareable和Comparator两种比较器的区别

    Java中Compareable和Comparator两种比较器的区别 参考原文链接:https://www.cnblogs.com/ldy-blogs/p/8488138.html 1.引言 在ja ...

  7. Java中HashMap遍历的两种方式

    Java中HashMap遍历的两种方式 转]Java中HashMap遍历的两种方式原文地址: http://www.javaweb.cc/language/java/032291.shtml 第一种: ...

  8. JAVA中集合输出的四种方式

    在JAVA中Collection输出有四种方式,分别如下: 一) Iterator输出. 该方式适用于Collection的所有子类. public class Hello { public stat ...

  9. Java中常见的Exception种类

    Java中常见的Exception种类 1.ClassNotFoundException 2.IOException 3.NoSuchFieldException 4.NoSuchMethodExce ...

随机推荐

  1. .NET Core 3.0之深入源码理解Kestrel的集成与应用(一)

      写在前面 ASP.NET Core 的 Web 服务器默认采用Kestrel,这是一个基于libuv(一个跨平台的基于Node.js异步I/O库)的跨平台.轻量级的Web服务器. 在开始之前,先回 ...

  2. Fabric1.4源码解析:Peer节点背书提案过程

    以前从来没有写过博客,从这段时间开始才开始写一些自己的博客,之前总觉得写一篇博客要耗费大量的时间,而且写的还是自己已经学会的,觉得没什么必要.但是当开始用博客记录下来的时候,才发现有些学会的地方只是自 ...

  3. (Demo分享)利用JavaScript(JS)实现一个九宫格拖拽功能

    利用JavaScript(JS)实现一个九宫格拖拽功能   Demo实现了对任意方格进行拖拽,可以交换位置,其中Demo-1利用了勾股定理判断距离! Demo-1整体思路: 1.首先div实现自由移动 ...

  4. Salesforce Admin篇(一)Duplicate Management

    参考资料:https://help.salesforce.com/articleView?id=managing_duplicates_overview.htm Salesforce 很重要的一个平台 ...

  5. X-Admin&ABP框架开发-数据字典

    在业务型的系统开发中,我们需要维护各种个样的类型,比如客户类型.客户行业.商品类型等等,这些类型往往信息量不多,并且相似度极高,如果采用一类型一表去设计,将会造成极大的工作量,通过将这部分类型的信息进 ...

  6. (数据科学学习手札65)利用Python实现Shp格式向GeoJSON的转换

    一.简介 Shp格式是GIS中非常重要的数据格式,主要在Arcgis中使用,但在进行很多基于网页的空间数据可视化时,通常只接受GeoJSON格式的数据,众所周知JSON(JavaScript Obje ...

  7. 存储账户静态网站与Azure CDN

    背景 把静态网站或文件托管在对象存储上,有很多可能很多好处,比如说:可以节省成本,因为相对虚机更便宜:性能更优,因为可以依赖于对象存储本身的高吞吐以及 CDN 的:更好的高可用性,因为也可以依赖于对象 ...

  8. 基于Django框架 CRM的增删改查

    思路: 创建表------从数据库读出数据展示出来------配置路由-----写视图函数------写对应页面 练习点: 数据库建表 ORM 数据库数据读取 数据 ModelForm  (form组 ...

  9. 测试调试-利用fiddler修改response返回结果

    测试前端过程中,经常需要验证各种功能状态.不同数据层级等返回后的展示效果.一般会通过以下三种方式进行测试: 1.构造满足条件的测试数据:(耗时费力) 2.修改数据库:(前提需要了解数据库数据存储.沟通 ...

  10. php的开始之路

    三大核心:封装,继承,多态 三大核心无处不在,不管是php传统的面向过程化编程,还是后来加入的oop面向对象编程,都一直贯穿整个php的发展进步史. 面向对象,面向接口五大原则:单一职责,封闭-开放, ...