Selenium
等待页面加载在Selenium
自动化测试中起着重要的作用。它们有助于使测试用例更加稳定,增强健壮性。Selenium
提供多种等待,根据某些条件在脚本执行相应的等待,从而确保Selenium
执行自动化测试时不会导致脚本失败。
在本文中,我们将介绍Selenium
等待和睡眠的类型,并提供演示Demo
以及对它们的比较分析。
为什么需要等待
大多数应用程序的前端都是基于JavaScript
或Ajax
构建的,使用诸如React
、Angular
、Vue
之类的框架,都是需要花费一定时间才能在页面上加载或刷新Web元素
。因此,如果测试用例在脚本中找到尚未加载到页面上的元素,则Selenium
会向抛出ElementNotVisibleException
的异常。
下面的代码片段将展示与使用Selenium
执行自动化测试时的问题。在此代码段中,使用的是某一航空订票网站的示例,在该示例中,post
用户选择行程日期的From
和To
目的地,Web应用程序
需要花费一些时间来加载所需的航班详细信息。在正常用户使用情况下,可以从列表中预订某一班航班。现在,由于页面尚未完全加载,测试脚本无法找到立即预订按钮。结果抛出NoSuchElementException异常。下面的代码段和控制台输出:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import com.gargoylesoftware.htmlunit.javascript.background.JavaScriptExecutor;
public class NoWaitImplemented {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", ".\\Driver\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.***.com/");
driver.findElement(By.id("FromSector_show")).sendKeys("北京", Keys.ENTER);
driver.findElement(By.id("Editbox13_show")).sendKeys("上海", Keys.ENTER);
driver.findElement(By.id("ddate")).click();
driver.findElement(By.id("snd_4_08/08/2020")).click();
driver.findElement(By.className("src_btn")).click();
driver.findElement(By.xpath("//button[text()='立即预定']")).click();
}
}
控制台输出:
*** Element info: (Us ing=xpath, value=//button(text()='立即预定']
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance (Unknown Source )
at sun.reflect.DelegatingConstructorAcces sorImp1.newInstance (Unknown Source )
at java.lang.reflect.Constructor.newInstance (Unknown Source )
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187)at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode (W3CHttpResponseCodec.java:122)
at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode (W3CHttpResponseCodec.java:49)
at org.openqa.selenium.remote.HttpC ommandExecutor.execute (HttpC ommandExecutor.java:158)
at org.openqa.selenium.remote.service.DriverCommandExecutor.e