selenium 隐式等待如何使用_Selenium等待:sleep、隐式、显式和Fluent

本文介绍了在自动化测试中等待页面加载的重要性,特别是使用Selenium时的几种等待类型:Thread.Sleep()、隐式等待、显式等待和Fluent等待。强调了Thread.Sleep()的不足,详细解释了隐式等待的全局应用和动态特性,以及显式等待的灵活性,通过预期条件实现更精确的等待。同时,提到了Fluent等待的自定义轮询频率和异常处理能力。
摘要由CSDN通过智能技术生成

Selenium等待页面加载在Selenium自动化测试中起着重要的作用。它们有助于使测试用例更加稳定,增强健壮性。Selenium提供多种等待,根据某些条件在脚本执行相应的等待,从而确保Selenium执行自动化测试时不会导致脚本失败。

在本文中,我们将介绍Selenium等待和睡眠的类型,并提供演示Demo以及对它们的比较分析。

为什么需要等待

大多数应用程序的前端都是基于JavaScriptAjax构建的,使用诸如ReactAngularVue之类的框架,都是需要花费一定时间才能在页面上加载或刷新Web元素。因此,如果测试用例在脚本中找到尚未加载到页面上的元素,则Selenium会向抛出ElementNotVisibleException的异常。

下面的代码片段将展示与使用Selenium执行自动化测试时的问题。在此代码段中,使用的是某一航空订票网站的示例,在该示例中,post用户选择行程日期的FromTo目的地,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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值