自动化测试-Selenium

一. Selenium介绍

selenium 是用来做web自动化测试的框架,支持各种浏览器,各种,支持各种语言 

原理:

二. 元素定位

2.1 XPath 定位

绝对路径: /html/head/title

相对路径以双斜杠开头,常见的相对路径定位有以下几种:

<1>相对路径+索引: 索引是从1开始的

<2>相对路径+属性值:

<3>相对路径+通配符

<4>相对路径+文本匹配

2.2 CSS定位

• id选择器: #id

• 类选择器: .class

• 标签选择: 标签名

• 后代选择器: 父级选择器 子级选择器

三. 操作测试对象

3.1 常见API

• click 点击对象

• send_keys 在对象上模拟按键输入

• clear 清除对象输入的文本内容

• submit 提交

• getAttribute 获取标签中value属性所对应的值

• text 由于获取元素的文本信息

public class Demo1 {public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();//允许所有请求options.addArguments("--remote-allow-origins=*");WebDriver webDriver =new ChromeDriver(options);//获取网址webDriver.get("https://www.sogou.com");//获取value标签元素文本信息String str=webDriver.findElement(By.xpath("//input[@value=\"搜狗搜索\"]")).getAttribute("value");System.out.println(str);//输入搜索内容webDriver.findElement(By.cssSelector("#query")).sendKeys("软件测试");Thread.sleep(3000);webDriver.findElement(By.xpath("//input[@value=\"搜狗搜索\"]")).click();Thread.sleep(3000);//找到并打印所有a标签下em标签中的内容List<WebElement> elements=webDriver.findElements(By.cssSelector("a em"));for (int i = 0; i < elements.size(); i++) {System.out.println(elements.get(i).getText());}Thread.sleep(3000);webDriver.close();}
}
public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("https://www.sogou.com/");Thread.sleep(3000);webDriver.findElement(By.cssSelector("#query")).sendKeys("软件测试");Thread.sleep(3000);//由于此处的搜狗搜索在form标签中,因此能够顺利提交//webDriver.findElement(By.cssSelector("#stb")).click();webDriver.findElement(By.cssSelector("#stb")).submit();Thread.sleep(3000);//此时代码是会报错的,因为a标签并不在form标签内//webDriver.findElement(By.cssSelector("#weixinch")).submit();webDriver.close();}

3.2 等待

public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("https://www.baidu.com/");webDriver.findElement(By.cssSelector("#s-top-loginbtn")).click();//隐式等待//webDriver.manage().timeouts().implicitlyWait(3, TimeUnit.DAYS);//显示等待,若加载出直接执行下面代码,若在指定时间内没有加载出来,就抛异常new WebDriverWait(webDriver,10).until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#s-top-loginbtn")));//强制等待3sThread.sleep(3000);webDriver.findElement(By.xpath("//*[@id=\"TANGRAM__PSP_11__userName\"]")).sendKeys("1111");webDriver.close();}

隐式等待等待的是整个页面的元素,而显示等待等待的是一定的条件. 

3.3 打印信息(标题/URL)

    public static void main(String[] args) {ChromeOptions options =new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("https://www.sogou.com/");String title=webDriver.getTitle();String url=webDriver.getCurrentUrl();System.out.println("当前标题:"+title+"当前url:"+url);webDriver.close();}

3.4 浏览器的操作

    public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("https://www.sogou.com");webDriver.findElement(By.cssSelector("#query")).sendKeys("软件测试");webDriver.findElement(By.cssSelector("#stb")).click();webDriver.manage().timeouts().implicitlyWait(3, TimeUnit.DAYS);//后退一步webDriver.navigate().back();Thread.sleep(3000);//前进一步webDriver.navigate().forward();Thread.sleep(3000);//使屏幕最大化webDriver.manage().window().maximize();Thread.sleep(3000);//全屏webDriver.manage().window().fullscreen();Thread.sleep(3000);//自定义窗口大小webDriver.manage().window().setSize(new Dimension(600,1000));Thread.sleep(3000);//滑动滚动条((JavascriptExecutor)webDriver).executeScript("document.documentElement.scrollTop=19999");}

3.5 键盘事件

通过sendKeys()调用按键:

• sendkeys(Keys.TAB) #TAB

• sendKeys(Keys.ENTER) #回车

• sendKeys(Keys.SPACE) #空格键

• sendKeys(Keys.ESCAPE) #回退键(Esc)

  public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("https://www.sogou.com/");Thread.sleep(3000);webDriver.findElement(By.cssSelector("#query")).sendKeys("软件测试");Thread.sleep(3000);webDriver.findElement(By.cssSelector("#query")).sendKeys(Keys.SPACE);Thread.sleep(3000);webDriver.findElement(By.cssSelector("#query")).sendKeys("软件开发");Thread.sleep(3000);webDriver.findElement(By.cssSelector("#query")).sendKeys(Keys.ENTER);}

键盘组合键用法 

sendKeys(Keys.CONTROL,"a") #全选 (Ctrl+a)

sendKeys(Keys.CONTROL,"c") #复制 (Ctrl+c)

sendKeys(Keys.CONTROL,"x") #剪切 (Ctrl+x)

sendKeys(Keys.CONTROL,"v") #粘贴 (Ctrl+v)

    public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("https://www.sogou.com/");webDriver.findElement(By.cssSelector("#query")).sendKeys("软件测试");Thread.sleep(3000);webDriver.findElement(By.cssSelector("#query")).sendKeys(Keys.CONTROL,"a");Thread.sleep(3000);webDriver.findElement(By.cssSelector("#query")).sendKeys(Keys.CONTROL,"x");Thread.sleep(3000);webDriver.findElement(By.cssSelector("#query")).sendKeys(Keys.CONTROL,"v");Thread.sleep(3000);webDriver.findElement(By.cssSelector("#query")).sendKeys(Keys.ENTER);}

3.6 鼠标事件

Actions类:

• contextClick() 右击

• doubleClick() 双击

• dragAndDrop() 拖动

• moveToElement() 移动

    public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("https://www.sogou.com/");webDriver.findElement(By.cssSelector("#query")).sendKeys("软件测试");webDriver.findElement(By.cssSelector("#query")).sendKeys(Keys.ENTER);Actions actions=new Actions(webDriver);Thread.sleep(3000);//需要现将鼠标移动到要操作的元素,然后右击,要perform()才会有效果actions.moveToElement( webDriver.findElement(By.cssSelector("#sogou_weixin"))).contextClick().perform();}

四. 特殊操作

为了方便测试的演示,测试的页面都是自制的。

4.1 定位一组元素

页面:

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><h3>checkbox</h3>
<div class="well">
<form class="form-horizontal">
<div class="control-group">
<label class="control-label" for="c1">checkbox1</label>
<div class="controls">
<input type="checkbox" id="c1" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="c2">checkbox2</label>
<div class="controls">
<input type="checkbox" id="c2" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="c3">checkbox3</label>
<div class="controls">
<input type="checkbox" id="c3" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="r">radio1</label>
<div class="controls">
<input type="radio" id="r1" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="r">radio2</label>
<div class="controls">
<input type="radio" id="r2" />
</div>
</div>
</form>
</div>
</body>
</html>

测试: 

    public static void main(String[] args) {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("http://localhost:63342/SeleniumTest/page/test1.html?_ijt=a28mk13t2kbijoe7d2clon53lj&_ij_reload=RELOAD_ON_SAVE");webDriver.manage().timeouts().implicitlyWait(3,TimeUnit.DAYS);List<WebElement> webElements=webDriver.findElements(By.xpath("//input[@type=\"checkbox\"]"));for (int i = 0; i < webElements.size(); i++) {System.out.println(webElements.get(i).getAttribute("type"));}}

4.2 多层框架/窗口定位

多框架定位

如果有内嵌网页框架,需要先转到框架才能操作框架内元素。

    public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();//允许所有请求options.addArguments("--remote-allow-origins=*");WebDriver webDriver =new ChromeDriver(options);webDriver.get("https://mail.163.com/");//需要先定位到框架,再对框架内元素进行操作webDriver.switchTo().frame(webDriver.findElement(By.xpath("//iframe")));Thread.sleep(3000);webDriver.findElement(By.xpath("//input[@name=\"email\"]")).sendKeys("12345");}

窗口的切换

在浏览器中每个窗口都有一个句柄来标识

    public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("Https://www.baidu.com");//获取当前句柄String handle= webDriver.getWindowHandle();System.out.println(handle);Thread.sleep(3000);webDriver.findElement(By.cssSelector("#s-top-left > a:nth-child(1)")).click();Set<String> hanles=webDriver.getWindowHandles();for (String h:hanles) {handle=h;}webDriver.switchTo().window(handle);Thread.sleep(3000);webDriver.findElement(By.cssSelector("#ww")).sendKeys("新闻联播");Thread.sleep(3000);webDriver.findElement(By.cssSelector("#s_btn_wr")).click();}

4.3 下拉框操作

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>下拉框</title>
</head>
<body>
<select id="ShippingMethod"onchange="updateShipping(options[selectedIndex]);" name="ShippingMethod"><option value="12.51">UPS Next Day Air ==> $12.51</option><option value="11.61">UPS Next Day Air Saver ==> $11.61</option><option value="10.69">UPS 3 Day Select ==> $10.69</option><option value="9.03">UPS 2nd Day Air ==> $9.03</option><option value="8.34">UPS Ground ==> $8.34</option><option value="9.25">USPS Priority Mail Insured ==> $9.25</option><option value="7.45">USPS Priority Mail ==> $7.45</option><option value="3.20" selected="">USPS First Class ==> $3.20</option>
</select>
</body>
</html>
    public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("http://localhost:63342/SeleniumTest/page/test3.html?_ijt=dcl94qtill9arl6odicib469be&_ij_reload=RELOAD_ON_SAVE");WebElement webElement=webDriver.findElement(By.cssSelector("#ShippingMethod"));Select select=new Select(webElement);Thread.sleep(3000);//通过标签 value选择 select.selectByValue("9.03");Thread.sleep(3000);//通过下标选择,下标从零开始select.selectByIndex(2);}

4.4 弹窗操作

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<button onclick="Click()">这是一个弹窗</button>
</body>
<script type="text/javascript">function Click() {let name = prompt("请输入姓名:");let parent = document.querySelector("body");let child = document.createElement("div");child.innerHTML = name;parent.appendChild(child)}
</script>
</html>
    public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("http://localhost:63342/SeleniumTest/page/test4.html?_ijt=e7mju27ab5d214o41bhvcqjf4r&_ij_reload=RELOAD_ON_SAVE");webDriver.findElement(By.xpath("//*[text()=\"这是一个弹窗\"]")).click();Thread.sleep(3000);//alert弹窗取消webDriver.switchTo().alert().dismiss();Thread.sleep(3000);webDriver.findElement(By.xpath("//*[text()=\"这是一个弹窗\"]")).click();Thread.sleep(3000);webDriver.switchTo().alert().sendKeys("软件测试");Thread.sleep(3000);webDriver.switchTo().alert().accept();}

4.5 文件操作

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<input type="file">
</body>
</html>
    public static void main(String[] args) {ChromeOptions options =new ChromeOptions();options.addArguments("--remote-allow-origins");WebDriver webDriver=new ChromeDriver(options);webDriver.get("http://localhost:63342/SeleniumTest/page/test5.html?_ijt=klnnrj3i4pn2rhg6cl7a63qibe&_ij_reload=RELOAD_ON_SAVE");webDriver.findElement(By.cssSelector("input")).sendKeys("E:\\test");}

4.6 quit和close

quit 关闭了整个浏览器,同时会清空浏览器的cookie,close关闭的是get时获取的页面.

    public static void main(String[] args) throws InterruptedException {ChromeOptions options=new ChromeOptions();options.addArguments("--remote-allow-origins=*");WebDriver webDriver=new ChromeDriver(options);webDriver.get("https://www.baidu.com");webDriver.findElement(By.cssSelector("#s-top-left > a:nth-child(1)")).click();Thread.sleep(3000);//webDriver.close();webDriver.quit();}

 4.7 截图

    public static void main(String[] args) throws InterruptedException, IOException {WebDriver webDriver=new ChromeDriver();webDriver.get("Https://www.baidu.com");webDriver.findElement(By.cssSelector("#kw")).sendKeys("软件测试");webDriver.findElement(By.cssSelector("#su")).click();Thread.sleep(3000);File file=((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);FileUtils.copyFile(file,new File("E:\\Code\\SeleniumTest\\picture.png"));}

注:截图操作需要另外引入一个common-io的依赖

Maven Repository: commons-io » commons-io » 2.11.0 (mvnrepository.com)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/173568.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

语音识别学习笔记

目录 开源的语音识别项目 端到端的多说话人语音识别序列化训练方法简介 新一代 Kaldi: Two-pass 实时语音识别 开源的语音识别项目 有哪些语音识别的开源项目&#xff1f; - 知乎 端到端的多说话人语音识别序列化训练方法简介 端到端的多说话人语音识别序列化训练方法简介 …

探索深度学习:从理论到实践的全面指南

探索深度学习&#xff1a;从理论到实践的全面指南 摘要&#xff1a; 本文旨在提供一个关于深度学习的全面指南&#xff0c;带领读者从理论基础到实践应用全方位了解这一技术。我们将介绍深度学习的历史、基本原理、常用算法和应用场景&#xff0c;并通过Python代码示例和Tens…

STM32使用多路PWM注意事项

这是使用CubeMX自动产生的代码&#xff0c;使用TIM2产生了PA0,PA1,PA2,PA3这4路PWM&#xff0c;可以看到里面Pulse是共同使用了一个sConfigOC,如果是需要动态调整Pulse&#xff0c;就需要特别注意。 如果是用来产生呼吸灯&#xff0c;就会把这4个PWM都打乱&#xff0c;我觉得&a…

Go查询Elasticsearch

在 Go 中需要在 Elasticsearch 中执行带有过滤条件的查询时&#xff0c;你可以使用 github.com/olivere/elastic 库的过滤器&#xff08;Filter&#xff09;功能。以下是一个示例代码&#xff0c;展示了如何在 Go 中使用 Elasticsearch 进行带有过滤条件的分页查询&#xff1a;…

【nlp】4.4 Transformer库的使用(管道模式pipline、自动模式auto,具体模型BertModel)

Transformer库的使用 1 了解Transformers库2 Transformers库三层应用结构3 管道方式完成多种NLP任务3.1 文本分类任务3.2 特征提取任务3.3 完型填空任务3.4 阅读理解任务3.5 文本摘要任务3.6 NER任务4 自动模型方式完成多种NLP任务4.1 文本分类任务4.2 特征提取任务4.3 完型填空…

讯飞星火知识库文档问答Web API的使用(二)

上一篇提到过星火spark大模型&#xff0c;现在有更新到3.0&#xff1a; 给ChuanhuChatGPT 配上讯飞星火spark大模型V2.0&#xff08;一&#xff09; 同时又看到有知识库问答的web api&#xff0c;于是就测试了一下。 下一篇是在ChuanhuChatGPT 中单独写一个基于星火知识库的内容…

【Android Jetpack】Navigation的使用

引入 单个Activity嵌套多个Fragment的UI架构模式&#xff0c;非常非常普遍。但是&#xff0c;对Fragment的管理一直是一件比较麻烦的事情。工程师需要通过FragmentManager和FragmentTransaction来管理Fragment之间的切换。页面的切换通常还包括对应用程序App bar的管理、Fragme…

vue3使用element plus树形选择器懒加载回显失败问题。

vue3使用element plus树形选择器懒加载回显时树形数据还未加载完成&#xff0c;回显时显示的的绑定值&#xff0c;不是要显示的名称。 解决1&#xff1a;不使用懒加载&#xff0c;一次性将数据返回完成 解决2&#xff1a;编辑回显时&#xff0c;拿到要显示的中文强制修改显示…

[个人笔记] Zabbix实现Webhook推送markdown文本

系统工程 - 运维篇 第四章 Zabbix实现Webhook推送markdown文本 系统工程 - 运维篇系列文章回顾Zabbix实现Webhook推送markdown文本前言实施步骤 Zabbix新增报警媒介类型Zabbix给用户新增报警媒介Zabbix修改动作的执行操作和恢复操作验证&测试 参考来源 系列文章回顾 第一章…

Linux系统分区和挂载超过2T的硬盘

报错信息&#xff1a;DOS partition table format cannot be used on drives for volumes larger than 2199023255040 bytes for 512-byte sectors. Use GUID partition table format (GPT). 转载&#xff1a;Ubuntu(Linux)系统安装扩展硬盘并完成格式化及挂载 - 知乎

微星主板开启VT

微星主板模拟器使用 开启VT 进入BIOS高级-》OC-》CPU特征-》intel 虚拟化技术-》允许

探索RockPlus SECS/GEM平台 - 赋能半导体行业设备互联

SECS/GEM协议&#xff0c;全称为半导体设备通讯标准/通用设备模型&#xff08;SECS/Generic Equipment Model&#xff09;&#xff0c;是一种广泛应用于半导体制造行业的通信协议。它定义了半导体设备与工厂主控系统&#xff08;如MES&#xff09;之间的通信方式&#xff0c;使…

PGP 遇上比特币

重复使用 PGP 密钥作为比特币密钥 介绍 在数字安全领域&#xff0c;密码学在确保数据的完整性和真实性方面发挥着至关重要的作用。 一种广泛使用的加密技术是使用 Pretty Good Privacy (PGP1)。 PGP 为安全通信&#xff08;例如电子邮件、文件传输和数据存储&#xff09;提供加…

解密Spring Cloud微服务调用:如何轻松获取请求目标方的IP和端口

公众号「架构成长指南」&#xff0c;专注于生产实践、云原生、分布式系统、大数据技术分享。 目的 Spring Cloud 线上微服务实例都是2个起步&#xff0c;如果出问题后&#xff0c;在没有ELK等日志分析平台&#xff0c;如何确定调用到了目标服务的那个实例&#xff0c;以此来排…

文章解读与仿真程序复现思路——电力自动化设备EI\CSCD\北大核心《考虑氢储一体化协同的综合能源系统低碳优化》

这个标题涉及到考虑了多个方面的能源系统优化&#xff0c;其中关键的关键词包括"氢储一体化"、"协同"、"综合能源系统"和"低碳优化"。以下是对这些关键词的解读&#xff1a; 氢储一体化&#xff1a; 氢储存&#xff1a; 指的是氢气的存…

计算机组成原理-Cache替换算法

文章目录 总览随机算法&#xff08;RAND&#xff09;先进先出算法&#xff08;FIFO&#xff09;近期最少使用算法&#xff08;LRU&#xff09;最不经常使用算法&#xff08;LFU&#xff09;总结 总览 随机算法&#xff08;RAND&#xff09; 没有选择性地考虑替换哪一块Cache&a…

c# EF框架的增删改查操作

查询 /// <summary>/// 查询/// </summary>private void SQLLoad(){//linq查询&#xff0c;方法一//var UserInfoList from u in db.UserInfo//给个变量u&#xff0c;用来接收查询结果对象//select u;//查询结果对象 //db.UserInfo.Find(1);//依据主键查询,方法二…

功率整流器的作用是什么?SURS8340T3G车规级功率整流器的介绍

汽车级功率整流器是一种用于汽车电子系统的功率电子器件&#xff0c;用于将交流电转换为直流电以供电子设备使用。汽车级功率整流器需要具有高效率、高可靠性、高稳定性和高温度工作能力等特点。其中&#xff0c;SURS8340T3G 是一种常见的汽车级功率整流器。 SURS8340T3G 是一…

基于单片机寻迹巡线避障智能小车系统设计

**单片机设计介绍&#xff0c; 基于单片机寻迹巡线避障智能小车系统设计 文章目录 一 概要二、功能设计设计思路 三、 软件设计原理图 五、 程序六、 文章目录 一 概要 基于单片机的寻迹巡线避障智能小车系统是一种能够自动跟随线路并避开障碍物的智能小车。下面是一个简要的系…

【Android Jetpack】LiveData-观察数据的容器

文章目录 LiveDataLiveData与ViewModel创建LiveData对象观察LiveData中的数据更新LiveData对象observeForever()源码Room和LiveData配合使用继承LiveData扩展功能转换LiveData合并多个LiveData中的数据 LiveData ViewModel的主要作用是存放页面所需要的各种数据。我们在示例代…