天行健,君子以自强不息;地势坤,君子以厚德载物。
每个人都有惰性,但不断学习是好好生活的根本,共勉!
文章均为学习整理笔记,分享记录为主,如有错误请指正,共同学习进步。
执行程序前请先配置驱动:
关于Java selenium使用前浏览器驱动的下载和环境变量的配置
关于Selenium自动化测试工具的Java实现详情请参考文章:
如何查看页面对应的Selenium定位参数
Java实现 selenium Web自动化测试(简单篇)
Java实现 selenium Web自动化测试(详细篇)
1. Thread的sleep
使用线程类Thread的sleep方法来让操作延时执行
sleep()的参数值为Millis毫秒,1000就是1000ms等于1秒
//等待5秒
Thread.sleep(5000);
2. Actions的pause
使用Selenium的Actions类中的pause方法进行延时操作
pause()的参数值为Duration类的子方法,有多种时间单位选择,如秒ofSeconds、分钟ofMinutes等
//创建actions对象
Actions actions = new Actions(webDriver);
//设置等待时间5秒
actions.pause(Duration.ofSeconds(5)).perform();
Duration对应的时间单位选择截图
3. 完整代码
可通过以下完整代码进行测试等待时间的设置
WaitTimeSetTest.java
package com.libai.test.selenium.chrome;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
/**
* @ClassDescription: 等待时间设置
* @JdkVersion: 1.8
* @Author: 李白
* @Created: 2024/5/9 13:22
*/
public class WaitTimeSetTest {
public static void main(String[] args) throws InterruptedException {
//指定驱动,第一个参数为驱动名称,不同浏览器的参数名称不一样,请根据浏览器查询到对应的浏览器参数名,第二个参数为驱动文件路径,即驱动完整文件路径
System.setProperty("webdriver.chrome.driver", "D:\\JavaSoftWares\\Google\\driver\\chromedriver-win64\\chromedriver.exe");
// 谷歌驱动
ChromeOptions cops = new ChromeOptions();
// 允许所有请求
cops.addArguments("--remote-allow-origins=*");
//默认设置开始打开网页时窗口最大化
cops.addArguments("--start-maximized");
//创建驱动对象
WebDriver webDriver = new ChromeDriver(cops);
// 启动需要打开的网页
webDriver.get("https://www.baidu.com");
//指定窗口大小--最大化
// webDriver.manage().window().maximize();
//第一种
//等待5秒
Thread.sleep(5000);
//等待后跳转到搜狗网址
webDriver.navigate().to("https://www.sogou.com");
//第二种,使用Actions的对象的pause方法进行等待
//创建actions对象
Actions actions = new Actions(webDriver);
//设置等待时间
actions.pause(Duration.ofSeconds(5)).perform();
//等待后跳转到指定网址
webDriver.navigate().to("https://www.soso.com");
//等待5秒
actions.pause(Duration.ofSeconds(5)).perform();
// webDriver.navigate().to("https://www.sogou.com");
webDriver.quit();
}
}
感谢阅读,祝君暴富!