当前位置: 首页 > news >正文

【软件测试学习day6】WebDriver常用的API

目录

1. WebDriver API

1.1 元素的定位

1.2 id 定位

1.3 name 定位

1.4 class name 定位

1.5 Xpath 定位

1.6 link text 定位

1.6.1 精确匹配

1.6.2 模糊匹配

2. 操作测试对象

2.1 点击与输入

2.2 submit 提交按钮

2.3 text 获取元素文本

2.4 clear 清除

2.5 等待

2.5.1 强制等待

2.5.2 智能等待

2.5.2.1 显式等待

2.5.2.2 隐式等待 

2.6 打印信息

2.7 浏览器操作

3. 键盘事件

4. 鼠标事件

5. 定位一组元素

6. 下拉框操作

7. alert弹窗操作

8. 上传文件操作

9. 关闭和退出浏览器

10. 窗口切换

11. 截图


1. WebDriver API

想要实现自动化测试,就需要知道所测试对象在的位置,因此可以通过元素的标签等属性来对这些对象进行定位。获取这些属性可通过 F12 右击检查


1.1 元素的定位

常用的元素定位有:idnameclass namelink textpartial link texttag namexpathcss selector

如何找到 id 或其他属性,点击搜索框右键检查或者按 F12 ,在元素里面找到对应的属性即可。

代码层面则通过 WebDriver 底下的 findElement 方法来找到元素。


1.2 id 定位

功能:通过 id 来找到该元素对应的位置。

语法:findElement(By.cssSelector("id名"))。

.sendKeys():在对应的输入框中输入文本。

public class Main {public static void main(String[] args) {test01();}private static void test01() {ChromeOptions options = new ChromeOptions();// 允许所有请求options.addArguments("---remote-allow-origins=*");WebDriver webDriver = new ChromeDriver(options);// 进入下方网站webDriver.get("https://www.baidu.com/");// idWebElement element = webDriver.findElement(By.cssSelector("#kw"));// 输入信息element.sendKeys("id测试");}
}


1.3 name 定位

语法:webDervier.findElement(By.name("name名"))


1.4 class name 定位

语法: findElement(By.cssSelector(".类名")) 


1.5 Xpath 定位

语法:.findElement(By.xpath("Xpath路径")) 。

绝对路径:

  • /html/head/title

相对路径:

  • 相对路径+索引://form/span[1]/input(查找第一个span下的 input 标签)
  • 相对路径+属性://input[@class="s_ipt"](查找类名为 s_ipt 的标签)
  • 相对路径+通配符://*[@*="s_ipt"](查找所有名为 s_ipt 的标签)
  • 相对路径+文本匹配://a[text()="文本"](查找 a 标签含有文本的标签)

直接获取 Xpath 定位方式如下:

public class Main {public static void main(String[] args) {test01();}private static void test01() {ChromeOptions options = new ChromeOptions();// 允许所有请求options.addArguments("---remote-allow-origins=*");WebDriver webDriver = new ChromeDriver(options);// 进入下方网站webDriver.get("https://www.baidu.com/");// XpathWebElement element = webDriver.findElement(By.xpath("//*[@id=\"kw\"]"));// 输入信息element.sendKeys("Xpath测试");}
}


1.6 link text 定位

link text 定位为两种基于链接文本的定位,主要有两种:精确匹配 模糊匹配


1.6.1 精确匹配

功能:通过链接的完整可见文本进行精确匹配。

语法:WebElement element = driver.findElement(By.linkText("完整链接文本"));


1.6.2 模糊匹配

功能:通过链接的部分可见文本进行模糊匹配(只要包含指定子串即可)。

语法:WebElement element = driver.findElement(By.partialLinkText("部分链接文本"));


2. 操作测试对象

webdriver 中比较常见操作对象的方法有:click(点击事件)、send_keys(在对象上模拟按键输入)、clear(清除)、submit(提交表单)、text(获取文本对象) 。


2.1 点击与输入

语法:输入:.sendKeys(),点击:.click()。 

public class Main {public static void main(String[] args) {test01();}private static void test01() {ChromeOptions options = new ChromeOptions();// 允许所有请求options.addArguments("---remote-allow-origins=*");WebDriver webDriver = new ChromeDriver(options);// 进入下方网站webDriver.get("https://www.baidu.com/");// Xpath 路径WebElement element = webDriver.findElement(By.xpath("//*[@id=\"kw\"]"));// 输入信息element.sendKeys("输入框测试");// 点击提交按钮webDriver.findElement(By.cssSelector("#su")).click();}
}


2.2 submit 提交按钮

语法:.submit()

  • 如果点击的元素放在 form 标签中,此时使用 submit 实现的效果和 click 是一样的。
  • 如果点击的元素放在非 form 标签中,此时使用 submit 报错。

2.3 text 获取元素文本

语法:.getText()  .getAttribute()。

.getText()获取元素的可见文本内容(用户实际看到的文本)。String按钮文字、链接文本、段落内容、表格单元格文本等。
.getAttribute()获取元素的指定属性值(如hrefvalueclass等,或自定义属性)。String获取输入框的默认值、隐藏字段的值、动态生成的属性、自定义data-*属性等。

当我们需要获取到网页中的某个文本时可通过 .getText() 来获取。 如想要访问下图文本:

        ChromeOptions options = new ChromeOptions();// 允许所有请求options.addArguments("---remote-allow-origins=*");WebDriver webDriver = new ChromeDriver(options);// 进入下方网站webDriver.get("https://www.baidu.com/");// 通过类来获取WebElement element = webDriver.findElement(By.cssSelector(".title-content-title"));String inp = element.getText();System.out.println(inp);

如果要获取标签中的文本可采用 .getAttribute("标签名") ,如获取按钮中的文本:

   ChromeOptions options = new ChromeOptions();// 允许所有请求options.addArguments("---remote-allow-origins=*");WebDriver webDriver = new ChromeDriver(options);// 进入下方网站webDriver.get("https://www.baidu.com/");// 通过类来获取String buttonValue = webDriver.findElement(By.cssSelector("#su")).getAttribute("value");if (buttonValue.equals("百度1下")) {System.out.println("测试通过");}else {System.out.println(buttonValue);


2.4 clear 清除

功能:将字段进行清除

语法:.clear();

运行 Java 代码,自动给搜索 “测试清除”,并搜索后清空搜索栏中的 “测试清除” 字段。代码如下:

​
public class Main {public static void main(String[] args) {test01();}private static void test01() {ChromeOptions options = new ChromeOptions();// 允许所有请求options.addArguments("---remote-allow-origins=*");WebDriver webDriver = new ChromeDriver(options);webDriver.get("https://www.baidu.com/");// 找到搜索框并输入 测试清除 字段webDriver.findElement(By.cssSelector("#kw")).sendKeys("测试清除");// 点击了百度一下按钮webDriver.findElement(By.cssSelector("#su")).click();// 清空百度搜索框中的数据webDriver.findElement(By.cssSelector("#kw")).clear();}
}​


2.5 等待

2.5.1 强制等待

语法:sleep(),例:强制等待 2 sleep(2000);

功能:使程序中某一时刻强制等待。


2.5.2 智能等待

智能等待分为 显式等待隐式等待


2.5.2.1 显式等待

功能:针对特定元素或条件设置灵活的等待逻辑,支持自定义验证条件。

特点:全局生效即对所有的 WebDriver 操作生效。

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("dynamic-element")));

2.5.2.2 隐式等待 

功能:为所有的 findElement()findElements() 设置全局超时等待。

特点:对特定的元素或操作生效。

WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)); // 全局等待10秒

2.6 打印信息

打印 url 使用 .getCurrentUrl() 

打印 title 使用 .getTitle()

        ChromeOptions options = new ChromeOptions();// 允许所有请求options.addArguments("---remote-allow-origins=*");WebDriver webDriver = new ChromeDriver(options);// 进入下方网站webDriver.get("https://www.baidu.com/");// 获取当前页面的 urlString url = webDriver.getCurrentUrl();// 获取当前页面的 titleString title = webDriver.getTitle();System.out.println("当前页面的url="+url );System.out.println("当前页面的title="+title);


2.7 浏览器操作

浏览器操作主要有前进、后退、刷新、滚动条、浏览器最大化等,本期讲解以下几种:

  • 前进:webDriver 底下的 navigate().forward() 方法
  • 后退:webDriver 底下的 navigate().back() 方法
  • 刷新:WebDriver 底下的 navigate().refresh() 方法
  • 滚动条:WebDriver.executeScript() 方法(需将 webDriver 类型转换为 JavaScriptExecutor )
        WebDriver webDriver = new ChromeDriver();// 打开以下网站webDriver.get("https://www.baidu.com/");// 搜索框输入111webDriver.findElement(By.cssSelector("#kw")).sendKeys("111");// 提交webDriver.findElement(By.cssSelector("#su")).click();// 浏览器后退sleep(2000);// 等待2秒webDriver.navigate().back();sleep(2000);// 等待2秒// 浏览器刷新webDriver.navigate().refresh();sleep(2000); // 等待2秒// 浏览器前进webDriver.navigate().forward();sleep(2000); // 等待2秒// 滚动条((JavascriptExecutor)webDriver).executeScript("document.documentElement.scrollTop=10000");sleep(2000); // 等待2秒// 浏览器最大化webDriver.manage().window().fullscreen();sleep(2000); // 等待2秒// 设置浏览器窗口大小webDriver.manage().window().setSize(new Dimension(600,1000));sleep(2000); // 等待2秒

3. 键盘事件

当我们需要将某个事件进行全选、剪切、复制、粘贴时就会用到键盘事件,如下代码。

webDriver.findElement(By.cssSelector("#kw")).sendKeys(Keys.CONTROL,"A");

其中 A 代表全选,X 代表剪切,V 代表粘贴。


4. 鼠标事件

        // 找到图片WebElement webElement = webDriver.findElement(By.cssSelector(".cos-image-video-mask_4G07f"));// 鼠标右击Actions actions = new Actions(webDriver);sleep(2000);actions.moveToElement(webElement).contextClick().perform();

5. 定位一组元素

场景:有一组 input 标签有单选框(radio)、复选框(checkbox),是单选框就点击。

        WebDriver webDriver = new ChromeDriver();// 打开你要访问的路径webDriver.get("");// 假设你要访问的是一组 input 标签List<WebElement> webElements = webDriver.findElements(By.cssSelector("input"));// 遍历这组数据for (int i = 0; i < webElements.size(); i++) {// 判断是否为复选框是则点击if (webElements.get(i).getAttribute("type").equals("radio")) {webElements.get(i).click();}else {}}

6. 下拉框操作

        WebDriver webDriver = new ChromeDriver();webDriver.get("对应的网址");WebElement webElement = webDriver.findElement(By.cssSelector("对应的class或id"));Select select = new Select(webElement);select.selectByIndex(0);// 选择第一个select.selectByValue("对应的value值");// 该 value 对应的选择框

7. alert弹窗操作

alert 弹框取消:webDriver.switchTo().alert().dissmiss();

alert 弹框输入信息:webDriver.switchTo().alert().sendKeys();

alert 弹框确认:webDriver.switchTo().alert().accept();

        WebDriver webDriver = new ChromeDriver();webDriver.get("");// 点击按钮webDriver.findElement(By.cssSelector("button")).click();sleep(2000);// alert 弹窗取消webDriver.switchTo().alert().dismiss();// 再次点击按钮webDriver.findElement(By.cssSelector("button")).click();// alert 弹窗内输入内容webDriver.switchTo().alert().sendKeys("你好");sleep(2000);// alert 弹窗确认webDriver.switchTo().alert().accept();

8. 上传文件操作

        WebDriver webDriver = new ChromeDriver();webDriver.get("");// 想要访问的地址webDriver.findElement(By.cssSelector("input")).sendKeys("文件路径");

9. 关闭和退出浏览器

关闭:.close();

退出:.quit();

        WebDriver webDriver = new ChromeDriver();webDriver.get("https://www.baidu.com/");webDriver.findElement(By.cssSelector("#s-top-left > a:nth-child(1)")).click();sleep(2000);webDriver.quit(); //退出浏览器webDriver.close(); //关闭浏览器

两者区别:

quit 退出整个浏览器,close 关闭当前页面(跳转之前的页面)。

quit 清空缓存,close 不会清空缓存。


10. 窗口切换

窗口切换会用到句柄,通过 .getWindowHandles() 就能获取到,通过句柄测试脚本就可对窗口进行打开、关闭或切换。

        WebDriver webDriver = new ChromeDriver();webDriver.get("https://www.baidu.com/");webDriver.findElement(By.cssSelector("#s-top-left > a:nth-child(1)")).click();sleep(2000);// 获取到所有窗口的句柄Set<String> handles = webDriver.getWindowHandles();String target_handle = "";for (String handle:handles) {target_handle = handle;}webDriver.switchTo().window(target_handle);sleep(2000);webDriver.findElement(By.cssSelector("#ww")).sendKeys("新闻联播");webDriver.findElement(By.cssSelector("#s_btn_wr")).click();

其中 .switchTo().window(“句柄”) 可对多窗口/页面进行切换和操作。


11. 截图

需要在 idea 中引入 common-io 依赖。

<dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.11.0</version>
</dependency>

实现:

  • Selenium WebDriver通过 TakesScreenshot接口提供截图功能
  • 通过 getScreenshotAs() 结合Robot类或AShot库(第三方工具)截取特定DOM元素,而非全屏。
  • 将 webDriver 强转为 TakesScreenshot 类型,并使用 .getScreenshotAs() 方法,再写入到本地磁盘。 
        WebDriver webDriver = new ChromeDriver();webDriver.get("https://www.baidu.com/");webDriver.findElement(By.cssSelector("#kw")).sendKeys("软件测试");webDriver.findElement(By.cssSelector("#su")).click();sleep(2000);// 截图File file = ((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);FileUtils.copyFile(file,new File("D://test.png"));

效果: 


相关文章:

  • 代码随想录算法训练营第五十八天| 图论4—卡码网110. 字符串接龙,105. 有向图的完全联通
  • CHAPTER 17 Iterators, Generators, and Classic Coroutines
  • 《饶议科学》阅读笔记
  • Qt开发经验 --- 避坑指南(5)
  • OpenCV-Python (官方)中文教程(部分一)_Day21
  • IT行业词汇科普手册
  • 对京东开展外卖业务的一些思考
  • DeepSeek全域智能革命:从量子纠缠到星际文明的认知跃迁引言:认知边界的坍缩与重构
  • 发那科机器人3(机器人编程基础)
  • Linux/AndroidOS中进程间的通信线程间的同步 - 共享内存
  • Kafka的核心组件有哪些?简要说明其作用。 (Producer、Consumer、Broker、Topic、Partition、ZooKeeper)
  • STM32开发printf函数支持
  • LabVIEW 与 NI 硬件(PXI, CompactRIO, DAQ, RF, Vision)的深度研究与未来发展趋势-分析报告
  • 【AI】模型与权重的基本概念
  • LeetCode热题100--73.矩阵置零--中等
  • JC/T 2187-2013 铝波纹芯复合铝板检测
  • 如何保证Kafka生产者的消息顺序性? (单分区内有序,需确保同一Key的消息发送到同一分区)
  • IBM BAW(原BPM升级版)使用教程Toolkit介绍
  • C语言--字符函数
  • 前端面试每日三题 - Day 27
  • 普京提议重启俄乌直接谈判后,特朗普表态了
  • 一生要出片的年轻人,买爆相机
  • 印控克什米尔地区再次传出爆炸声
  • 智利观众也喜欢上海的《好东西》
  • 花2万多在海底捞办婚礼,连锁餐企要抢酒楼的婚宴生意?
  • 人民日报钟声:平等对话是解决大国间问题的正确之道