郑大钱呀】【】【】【】,我们一起交流,一起学习。

文章目录

  • 声明
  • 自动化开发环境搭建
    • 环境准备
    • 浏览器驱动下载
    • IDEA 创建Maven项目
  • selenium初探
  • Selenium元素定位
    • By.id定位
    • By.name定位
    • By.className定位
    • By.tagName定位
    • By.linkText定位
    • By.partialLinkText定位
    • By.xpath定位
    • By.cssSelector定位
  • 特殊场景元素定位
    • iframe 表单页面定位
    • 多窗口切换
    • 警告框处理
    • 选择框处理
    • 上传文件
  • 元素等待
  • 浏览器常用API
  • 常用事件
  • 获取页面元素信息常用方法
  • 获取页面的信息
  • 浏览器cookie操作
  • 调用JavaScript代码
  • 获取窗口截图

声明

自动化测试请在允许授权的测试环境下进行,不可有任何危害网络安全的操作,如有违规操作,与本文无关。本文有不少内容,参考了CSDN的博主[Penny 要努力呀],大家也可以直接去访问,写的很详细,很赞。

自动化开发环境搭建

环境准备

  1. JDK安装并配置完成
  2. 已经安装好浏览器,这里我们使用谷歌浏览器
  3. IDEA已经安装,直接官网下就可以,社区版免费

浏览器驱动下载

使用selenium需要下载一个WebDriver,要注意WebDriver的版本要与浏览器的版本类型一致,否则可能会出异常,我们使用的浏览器版本如下:


所以我们这里要去下载谷歌浏览器对应版本的WebDriver,地址如下:

https://www.selenium.dev/documentation/webdriver/getting_started/install_drivers/


选择和自己浏览器相符合的版本即可,这里我们选择mac这个版本,如果是其他系统就选择对应的版本:

如果你的操作系统是mac的话,需要在终端,将目录切换至driver所在的目录,执行如下命令:

xattr -d com.apple.quarantine chromedriver

否则会报如下的错误:MacOS无法打开“chromedriver”,因为无法验证开发者

IDEA 创建Maven项目

这里我们选择使用java语言来进行开发,selenium框架也有对应的python版本,在jar管理上,我们使用maven来管理,简单且方便。

我们使用IDEA创建一个maven项目吗,菜单路径:File->New->Project

输入项目名和项目路径,点击Finish即可:


完成后截图如下:

我们打开pom.xml文件导入selenium和testNG的依赖包,完整的pom文件信息如下,主要关注依赖的坐标就可以了,添加完依赖包的坐标后,记得刷新一下,把包引进来,没有的,需要等待它下载完成,否则会报红:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>SeleniumStudy</artifactId><version>1.0-SNAPSHOT</version><dependencies><dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-java</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.testng</groupId><artifactId>testng</artifactId><version>7.5</version></dependency></dependencies>
</project>

这里我们引入了两个依赖包,selenium包和testNG测试框架,引入testNG是方便我们测试。

selenium初探

我们先感受一下selenium的使用,这里我们使用的网站是我们自己开发在本地的项目,我们以最经典的登录为例,登录界面如下:

示例代码如下:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;public class SeleniumTest {@Testpublic void login(){// 设置驱动System.setProperty("webdriver.chrome.driver", "/Users/yangchen/MyProject/SeleniumStudy/driver/chromedriver");// 创建一个WebDriver对象WebDriver driver = new ChromeDriver();// 打开Web页面driver.get("http://localhost:8080/#/");// 通过ID定位到账户输入框driver.findElement(By.id("account")).sendKeys("123456@qq.com");driver.findElement(By.id("password")).sendKeys("123456");driver.findElement(By.id("login_btn")).click();try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}driver.close();}
}

执行结果如下:

我们在上面实现了一个简单的登录功能,在这个程序中我们可以了解到:

  1. @Test是一个TestNG测试框架中的注解,当方法被该注解标识,就可以单独运行,这样就不用写主方法了,后面我们单独开一期,系统的学习一下TestNG的框架
  2. Web UI自动化的创建思路,一般都是创建一个WebDriver对象,就相当于你拥有了一个浏览器,然后通过get()方法进入你要进行测试的网页,然后再通过元素定位去操作每个元素,这也就是我们通常说的找对象,当操作完成后,最后我们关闭浏览器,释放资源。
  3. 基本上所有的UI自动化测试,很大的一部分工作内容就是在元素的定位。

Selenium元素定位

By.id定位

该方法即使通过Web元素的id属性来定义,一般情况下如果元素有id,我们就使用id定义,因为id一般都是不重复的,定位准确,我们上面的示例中的元素定义就采用的id定位。

前端页面代码

<input id="password" placeholder="请输入密码" class="el-input__inner">

java定位代码

driver.findElement(By.id("password"));

By.name定位

该方法与By.id方法类似,只不是通过name属性来定位的,有的时候,前端元素,它没有id,但是它有name,这个时候我们就可以使用name来定位。

前端页面代码

<input name="email" placeholder="请输入邮箱" class="el-input__inner">

java定位代码

driver.findElement(By.name("email"))

By.className定位

有的时候,他们既没有id也没有name,但是它有className,这个class不是编程中的类,它和id一样,也是前端元素的一种属性,与id不一样的是,id是唯一的,但是className是不唯一的。
前端页面代码

<input name="email" placeholder="请输入邮箱" class="el-input__inner">
<input name="password" placeholder="请输入密码" class="el-input__inner">

java定位代码

// 定位邮箱输入框
driver.findElement(By.className("el-input__inner")).sendKeys("123456@qq.com");
driver.findElement(By.id("password")).sendKeys("123456");
driver.findElement(By.id("login_btn")).click();

在我们的页面,有两个元素,邮箱输入框和密码输入框,他们的className都是一样的,但是为什么还是能准确定位到邮箱输入框,这是因为我们在找元素的时候,使用的是findElement方法,使用find_element()查找元素,但有多个元素满足条件时,他只取所有满足条件的元素列表的第1个元素,因为邮箱在第一个位置,所以就不会报错,但是如果用这个方法定位密码的输入框就会有问题。

此时就需要使用到find_element()方法了,该方法会返回一个List<E>,也就是一个数组集合,此时我们可以通过使用List<E>get(int index)方法,来取到第二个元素完成元素定位,关键代码如下:

driver.findElement(By.className("el-input__inner")).sendKeys("123456@qq.com");
driver.findElements(By.className("el-input__inner")).get(1).sendKeys("123456");

By.tagName定位

该方法就是通过元素的标签定位,在html页面中有很多标签元素,如:inputdivspanbutton等等,因此我们也可以使用标签来定位,关键代码如下:
前端页面代码

<input name="email" placeholder="请输入邮箱" class="el-input__inner">
<input name="password" placeholder="请输入密码" class="el-input__inner">

java定位代码

driver.findElement(By.tagName("input")).sendKeys("123456@qq.com");
driver.findElements(By.tagName("input")).get(1).sendKeys("123456");

By.linkText定位

该方法就是专门用来定位超链接文本的,比如我们平台的数据解读说明超链接文本,页面如下:

,前端代码如下:

<a class="el-link el-link--primary is-underline"><span class="el-link--inner">数据解读说明</span>
</a>

这里的登录按钮,我们就可以使用linkText定位到,关键代码如下:

driver.findElement(By.linkText("数据解读说明")).click();

By.partialLinkText定位

我们上面定位链接文字的时候,是精确匹配的,我们也可以使用模糊匹配,上面的数据解读说明,我们只需输入数据解读,也可以正常匹配到,关键代码如下:

driver.findElement(By.partialLinkText("数据解读")).click();

By.xpath定位

该定位方法也是用的比价多的,xpath全称为XML Path的简称,他可以通过xpath的语法,定位到页面的每个元素,具体的语法我们就不铺开了,我们讲下使用,现在的浏览器开发者工具很方便,我们可以获取到xpath路径,如下图:

相对路径写法
//*[@id="password"]
绝对路径写法
/html/body/div/div/div/div[2]/form/div[2]/div/div/input

我们推荐使用相对路径写法

java核心代码如下

driver.findElement(By.xpath("//*[@id=\"password\"]")).sendKeys("123456");

By.cssSelector定位

在说css样式选择器之前,我们这里先简单的说一下css,如果我们把元素的前端标签当成毛坯房的话,那么css就相当于给毛坯房装修的,我们这里以输入框做个简单的示例,前端代码如下:

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>测试</title>
</head>
<body><div><input placeholder="这是原始的输入框"></input></div><br/><div><input  id ='input' placeholder="这使用css渲染的输入框"></input></div>
</body>
</html>
<style>#input{border:  1px solid #cac6c6;padding: 5px;min-width: 200px;border-radius: 3px;}
</style>

前端页面效果如下:


使用了css样式,渲染出来的页面要更好看一些,在css中一般有如下几种方式定位:

  1. # :通过id
  2. . : 通过标签的类名
  3. 通过标签名定位
  4. 标签+属性:即 标签名[属性名=属性值]
  5. 层级定位:父标签[父标签属性名=父标签属性值]>(或者空格)子标签
  6. 索引定位:父标签[父标签属性名=父标签属性值]>子标签:nth-child(索引序号)
  7. 逻辑定位标签名[标签名1= 属性值1][标签名2=属性值2]

核心代码

// 通过id定位
driver.findElement(By.cssSelector("#account")).sendKeys("123456@qq.com");// 通过标签类名定位
driver.findElement(By.cssSelector(".el-input__inner")).sendKeys("123456@qq.com");// 通过`标签+属性`定位
driver.findElement(By.cssSelector("input[placeholder='请输入邮箱']")).sendKeys("123456@qq.com");// 通过层级来定位
driver.findElement(By.cssSelector("div[class='el-input']>input")).sendKeys("123456@qq.com");// 通过索引来定位,索引从1开始
driver.findElement(By.cssSelector("div[class='el-input']>input:nth-child(2)")).sendKeys("123456@qq.com");// 逻辑定位
driver.findElement(By.cssSelector("input[placeholder='请输入邮箱'][autocomplete='off']")).sendKeys("123456@qq.com");

特殊场景元素定位

我们上面说的定位方式,都是正常的场景,但是有一些场景比价特殊,比如在一个页面中嵌入了一个iframe页面、弹出一个新的选择页面、打开一个新的页面等等,这个时候我们直接使用上面的八大定位可能就不好使了,所以就需要一些特殊的方法。

iframe 表单页面定位

我们有时候会遇到像如下图中这种页面

在一个页面中又嵌套了一个页面即内联框架,但是这个时候我们想登录,直接去定位登录的元素,是行不通,我们需要通过switchTo().frame()方法,切换到iframe中,如果我们想再切换回默认页面,可以使用switchTo().defaultContent();方法切换回来。

前端代码如下

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>测试</title>
</head>
<body><h1>这里是iframe外</h1><iframe id="login_iframe" src="http://localhost:8080/#/" style="width: 100%;height: 600px"></iframe>
</body>
</html>
<style>#input{border:  1px solid #cac6c6;padding: 5px;min-width: 200px;border-radius: 3px;}
</style>

示例代码如下

import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;public class SeleniumTest {@Testpublic void login() throws InterruptedException {// 设置驱动System.setProperty("webdriver.chrome.driver", "/Users/yangchen/MyProject/SeleniumStudy/driver/chromedriver");// 创建一个WebDriver对象WebDriver driver = new ChromeDriver();// 打开Web页面driver.get("http://localhost:63343/invest-project-ui/public/Test.html?_ijt=g0len3inipqu9bfu2vej06nd81&_ij_reload=RELOAD_ON_SAVE");driver.get("http://localhost:63343/invest-project-ui/public/Test.html?_ijt=s0qnsv131v37q4o773bh8tk7rn");// 先定位到iframeWebElement iframe=driver.findElement(By.id("login_iframe"));// 再切换至iframe中Thread.sleep(1000);driver.switchTo().frame(iframe);// 通过ID定位到账户输入框Thread.sleep(1000);WebElement account=driver.findElement(By.id("account"));Thread.sleep(1000);account.sendKeys("123456@qq.com");Thread.sleep(1000);driver.findElement(By.id("password")).sendKeys("123456");// 点击按钮driver.findElement(By.id("login_btn")).click();// 再切换回默认页面driver.switchTo().defaultContent();Thread.sleep(1000);driver.close();}
}

多窗口切换

我们有一个页面,我们点击了一下一个按钮或者超链接,它打开了一个新的页面,我们需要到新的页面操作,此时我们需要先获取的局面的句柄,然后再通过switchTo().window()方法切换至新打开的页面进行操作,前端代码如下:

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>测试</title>
</head>
<body><h1>自动化测试</h1><a id="login" href="http://localhost:8080/#/" target="_blank">登录页面</a>
</body>
</html>
<style>#input{border:  1px solid #cac6c6;padding: 5px;min-width: 200px;border-radius: 3px;}
</style>

JAVA代码

import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;import java.util.Set;public class SeleniumTest {@Testpublic void login() throws InterruptedException {// 设置驱动System.setProperty("webdriver.chrome.driver", "/Users/yangchen/MyProject/SeleniumStudy/driver/chromedriver");// 创建一个WebDriver对象WebDriver driver = new ChromeDriver();// 打开Web页面driver.get("http://localhost:63343/invest-project-ui/public/Test.html?_ijt=s0qnsv131v37q4o773bh8tk7rn");WebElement login=driver.findElement(By.id("login"));Thread.sleep(1000);login.click();// 获取当前窗口句柄String search_handle = driver.getWindowHandle();//获得所有窗口句柄Set<String> handles = driver.getWindowHandles();for(String handle : handles){if(handle.equals(search_handle)==false){//切换到登录页面driver.switchTo().window(handle);// 通过ID定位到账户输入框Thread.sleep(1000);WebElement account=driver.findElement(By.id("account"));Thread.sleep(1000);account.sendKeys("123456@qq.com");Thread.sleep(1000);driver.findElement(By.id("password")).sendKeys("123456");// 点击按钮driver.findElement(By.id("login_btn")).click();}}Thread.sleep(1000);// 切换至之前的页面driver.switchTo().window(search_handle);Thread.sleep(1000);driver.quit();}
}

执行效果如下:

警告框处理

在前端页面中我们会遇到如下这种弹框:

这是就需要,通过switch_to_alert()方法定位到弹框中,然后再执行操作,弹框常用的方法如下:

  1. getText(): 返回弹框中的文字信息。
  2. accept(): 接受现有警告框。
  3. dismiss(): 解散现有警告框。
  4. sendKeys(keysToSend): 发送文本至警告框。
  5. keysToSend: 将文本发送至警告框。

示例的前端代码

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>测试</title><script type="text/javascript">function disp_alert(){confirm("自动化测试!","")}</script>
</head>
<body><h1>自动化测试</h1><button id="alert" οnclick="disp_alert()">弹框</button>
</body>
</html>

JAVA代码

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;import java.util.Set;public class SeleniumTest {@Testpublic void login() throws InterruptedException {// 设置驱动System.setProperty("webdriver.chrome.driver", "/Users/yangchen/MyProject/SeleniumStudy/driver/chromedriver");// 创建一个WebDriver对象WebDriver driver = new ChromeDriver();// 打开Web页面driver.get("http://localhost:63343/invest-project-ui/public/Test.html?_ijt=s0qnsv131v37q4o773bh8tk7rn");WebElement alert=driver.findElement(By.id("alert"));Thread.sleep(1000);alert.click();// 跳转alertAlert alertFrame = driver.switchTo().alert();// 向弹框输入框中输入文本Thread.sleep(2000);alertFrame.sendKeys("自动化测试");Thread.sleep(2000);System.out.println("弹框中的文字信息:"+alertFrame.getText());// 确认弹框alertFrame.accept();Thread.sleep(2000);driver.quit();}
}

选择框处理

选择框主要支持如下几种方式定位:

  1. selectByVisibleText(): 通过文本选择选项
  2. selectByIndex(): 通过索引选择选项
  3. selectByValue(): 通过值选择选项
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>测试</title>
</head>
<body>
<h1>自动化测试</h1>
<div><h3>城市</h3><select id="city" name="city" style="width: 200px;height: 40px;"><option value="shanghai" selected>上海</option><option value="suzhou" selected>苏州</option><option value="nanjing" selected>南京</option><option value="hangzhou" selected>杭州</option></select>
</div>
</body>
</html>

JAVA代码如下

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;import java.util.Set;public class SeleniumTest {@Testpublic void login() throws InterruptedException {// 设置驱动System.setProperty("webdriver.chrome.driver", "/Users/yangchen/MyProject/SeleniumStudy/driver/chromedriver");// 创建一个WebDriver对象WebDriver driver = new ChromeDriver();// 打开Web页面driver.get("http://localhost:63343/invest-project-ui/public/Test.html?_ijt=s0qnsv131v37q4o773bh8tk7rn");WebElement select_el=driver.findElement(By.id("city"));Select sel = new Select(select_el);Thread.sleep(1000);sel.selectByVisibleText("上海");Thread.sleep(2000);sel.selectByIndex(1);Thread.sleep(2000);sel.selectByValue("nanjing");Thread.sleep(2000);driver.quit();}
}

执行结果如下:

上传文件

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;public class SeleniumTest {@Testpublic void login() throws InterruptedException {// 设置驱动System.setProperty("webdriver.chrome.driver", "/Users/yangchen/MyProject/SeleniumStudy/driver/chromedriver");// 创建一个WebDriver对象WebDriver driver = new ChromeDriver();// 打开Web页面driver.get("http://localhost:63343/invest-project-ui/public/Test.html?_ijt=s0qnsv131v37q4o773bh8tk7rn");WebElement upload_file=driver.findElement(By.id("upload_file"));Thread.sleep(2000);upload_file.sendKeys("/Users/yangchen/Pictures/123.png");Thread.sleep(2000);driver.quit();}
}

执行结果如下

元素等待

在做UI自动化的过程中,会因为种种原因,比如网络、页面加载快慢,导致元素并不能及时的获取到,这个时候,就需要我们使用元素等待,等待找到指定的元素,再进行下一步,一般等待分为三种:

  1. 强制等待:强制等待,就是假如我在找某个元素之前,强制等待10s,但是,不管元素有没有加载好,都要等待10s才能继续,这样看起来不太智能,如果2s就加载好了,再继续等就会浪费时间,效率不高。
  2. 显式等待:显示等待要比强制等待,要智能的多,它可以针对于某个特定的元素设置的等待时间,它有两个参数:检测时间最大等待时间,如果我们把检测时间设置为1s最大等待时间设置为10s,也就意味着,每0.5s就会查找一下元素,只要一找到就立刻继续,不会继续等待,如果一直没找到,超过了最大的等待的时间,就会报错。
  3. 隐式等待:隐式等待和显示等待类似,但是不同的时候,隐式等待针对的是页面所有元素,是全局,而显示等待是针对某个元素。

java示例代码

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;import java.util.concurrent.TimeUnit;public class SeleniumTest {@Testpublic void login(){// 设置驱动System.setProperty("webdriver.chrome.driver", "/Users/yangchen/MyProject/SeleniumStudy/driver/chromedriver");// 创建一个WebDriver对象WebDriver driver = new ChromeDriver();/*** 隐式等待,全局等待* 1. implicitlyWait 识别对象时的超时时间* 2. setScriptTimeout 异步脚本的超时时间* 3. pageLoadTimeout 页面加载时的超时时间* *///页面加载超时时间设置为 5sdriver.manage().timeouts().pageLoadTimeout(5, TimeUnit.SECONDS);//定位对象时给 5 的时间, 如果 10s 内还定位不到则抛出异常driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);//异步脚本的超时时间设置成 5sdriver.manage().timeouts().setScriptTimeout(5, TimeUnit.SECONDS);// 打开Web页面driver.get("http://localhost:8080/#/");// 通过ID定位到账户输入框try {//强制等待1sThread.sleep(1000);driver.findElement(By.cssSelector("input[placeholder='请输入邮箱']")).sendKeys("123456@qq.com");//隐式等待//显式等待方式一, 针对某个元素等待WebDriverWait wait = new WebDriverWait(driver,10, 1);wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"password\"]"))).sendKeys("123456");//显式等待方式二wait.until(new ExpectedCondition<WebElement>(){@Overridepublic WebElement apply(WebDriver text) {return driver.findElement(By.xpath("//*[@id=\"password\"]"));}}).sendKeys("123456");driver.findElement(By.id("login_btn")).click();} catch (InterruptedException e) {e.printStackTrace();}finally {driver.close();}}
}

浏览器常用API

  1. maximize():浏览器窗口最大化
  2. minimize():浏览器窗口最小化
  3. fullscreen():浏览器全屏
  4. setSize():设置浏览器宽高
  5. back():模拟浏览器后退按钮
  6. forward():模拟浏览器前进按钮
  7. refresh():刷新流量器
  8. driver.close():关闭当前页面
  9. driver.quit():退出浏览器

示例代码如下:

import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;public class SeleniumTest {@Testpublic void login() throws InterruptedException {// 设置驱动System.setProperty("webdriver.chrome.driver", "/Users/yangchen/MyProject/SeleniumStudy/driver/chromedriver");// 创建一个WebDriver对象WebDriver driver = new ChromeDriver();// 打开Web页面driver.get("http://localhost:8080/#/");Thread.sleep(2000);// 窗口最小化driver.manage().window().minimize();Thread.sleep(2000);// 窗口最大化driver.manage().window().maximize();// 设置窗口指定大小Thread.sleep(2000);driver.manage().window().setSize(new Dimension(1000,600));Thread.sleep(2000);// 窗口全屏driver.manage().window().fullscreen();// 通过ID定位到账户输入框Thread.sleep(2000);driver.findElement(By.id("account")).sendKeys("123456@qq.com");Thread.sleep(2000);driver.findElement(By.id("password")).sendKeys("123456");driver.findElement(By.id("login_btn")).click();Thread.sleep(2000);// 刷新页面driver.navigate().refresh();// 浏览器后退driver.navigate().back();// 浏览器前进driver.navigate().forward();Thread.sleep(3000);driver.close();}
}

执行结果如下:

常用事件

我们在使用浏览器的时候,一般都会做一些操作,比如输入、点击、这些我们已经在登录的示例中,操作过了,除此之外,还有一些其他的事件方法,下面我们看一下常用的事件方法:

  1. sendKeys(*value):该方法为输入方法,主要作用是模拟按键操作,比如输入文本、操作键盘上的某个按键、上传指定的文件。
  2. click():该方法为点击事件,可以点击按钮、超链接、图片、选择框等元素。
  3. clear():用于清空文本输入框中的内容
  4. submit():主要用于表单的提交
    示例代码如下:
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;public class SeleniumTest {@Testpublic void login() throws InterruptedException {// 设置驱动System.setProperty("webdriver.chrome.driver", "/Users/yangchen/MyProject/SeleniumStudy/driver/chromedriver");// 创建一个WebDriver对象WebDriver driver = new ChromeDriver();// 打开Web页面driver.get("http://localhost:8080/#/");// 通过ID定位到账户输入框Thread.sleep(1000);WebElement account=driver.findElement(By.id("account"));Thread.sleep(1000);account.sendKeys("123456sdfdsfsf@qq.com");Thread.sleep(1000);// 清空文本框account.clear();account.sendKeys("123456@qq.com");Thread.sleep(1000);driver.findElement(By.id("password")).sendKeys("123456");// 点击按钮driver.findElement(By.id("login_btn")).click();Thread.sleep(1000);driver.close();}
}

获取页面元素信息常用方法

  1. getSize(): 返回元素的尺寸。
  2. getText(): 获取元素的文本。
  3. getAttribute(name): 获得属性值。
  4. isDisplayed(): 返回该元素是否用户可见。
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;public class SeleniumTest {@Testpublic void login() throws InterruptedException {// 设置驱动System.setProperty("webdriver.chrome.driver", "/Users/yangchen/MyProject/SeleniumStudy/driver/chromedriver");// 创建一个WebDriver对象WebDriver driver = new ChromeDriver();// 打开Web页面driver.get("http://localhost:8080/#/");// 通过ID定位到账户输入框Thread.sleep(1000);WebElement account=driver.findElement(By.id("account"));Thread.sleep(1000);account.sendKeys("123456@qq.com");// 获取id属性的值System.out.println("id属性的值:"+account.getAttribute("id"));// 获取元素的尺寸System.out.println("元素的尺寸:"+account.getSize());// 获取元素的位置坐标System.out.println("元素的位置坐标:"+account.getLocation());// 获取该元素是否可见System.out.println("元素是否可见:"+account.isDisplayed());Thread.sleep(1000);driver.findElement(By.id("password")).sendKeys("123456");// 点击按钮driver.findElement(By.id("login_btn")).click();Thread.sleep(1000);driver.close();}
}

执行结果如下:

id属性的值:account
元素的尺寸:(360, 40)
元素的位置坐标:(570, 319)
元素是否可见:true

获取页面的信息

  1. getTitle():用于获得当前页面的title。
  2. getCurrentUrl() : 用户获得当前页面的URL。
  3. getPageSource(): 获取页面代码
  4. getWindowHandle():获取当前页面句柄
  5. getWindowHandles():获取浏览器所有的句柄,返回的是一个集合
    示例代码如下:
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;public class SeleniumTest {@Testpublic void login() throws InterruptedException {// 设置驱动System.setProperty("webdriver.chrome.driver", "/Users/yangchen/MyProject/SeleniumStudy/driver/chromedriver");// 创建一个WebDriver对象WebDriver driver = new ChromeDriver();// 打开Web页面driver.get("http://localhost:8080/#/");System.out.println("当前URL:"+driver.getCurrentUrl());System.out.println("当前网站标题:"+driver.getTitle());System.out.println("当前前端代码:"+driver.getPageSource());System.out.println("当前页面句柄:"+driver.getWindowHandle());System.out.println("当前所有句柄:"+driver.getWindowHandles());Thread.sleep(1000);driver.close();}
}

执行结果如下:

信息: Found CDP implementation for version 98 of 97
当前URL:http://localhost:8080/#/
当前网站标题:invest-project
当前前端代码:<html lang="">中间省略<html>
当前页面句柄:CDwindow-431B77CAF29AD1E24466BDA6E83DB971
当前所有句柄:[CDwindow-431B77CAF29AD1E24466BDA6E83DB971]

浏览器cookie操作

  1. getCookies():获得所有cookie信息。
  2. getCookieNamed(String name): 返回字典的key为name的Cookie信息。
  3. addCookie(cookie dict):添加Cookie。“cookie_dict”指字典对象,必须有 name和value值。
  4. deleteCookieNamed(String name):删除Cookie信息。 “name”是要删除的cookie的名称; “optionsString” 是该Cookie的选项,目前支持的选项包括“路径” , “域” 。
  5. deleteAllCookies():删除所有cookie信息。

示例代码如下:

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;import java.util.Set;public class SeleniumTest {@Testpublic void login() throws InterruptedException {// 设置驱动System.setProperty("webdriver.chrome.driver", "/Users/yangchen/MyProject/SeleniumStudy/driver/chromedriver");// 创建一个WebDriver对象WebDriver driver = new ChromeDriver();driver.get("http://localhost:8080/#/");// 设置CookiesCookie c1 = new Cookie("name", "tester");Cookie c2 = new Cookie("sex", "male");driver.manage().addCookie(c1);driver.manage().addCookie(c2);// 获取CookiesSet<Cookie> cookies = driver.manage().getCookies();System.out.println(cookies);driver.quit();}
}

调用JavaScript代码

WebDriver提供了executeScript()方法来执行JavaScript代码

前端代码

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>测试</title>
</head>
<body>
<h1>自动化测试</h1><div id="scroll" style="width: 100%;height: 800px;"><h4>内容1</h4><h4>内容2</h4><h4>内容3</h4><h4>内容4</h4><h4>内容5</h4><h4>内容6</h4>
</div></body></html>

JAVA代码

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;public class SeleniumTest {@Testpublic void login() throws InterruptedException {// 设置驱动System.setProperty("webdriver.chrome.driver", "/Users/yangchen/MyProject/SeleniumStudy/driver/chromedriver");// 创建一个WebDriver对象WebDriver driver = new ChromeDriver();// 打开Web页面driver.get("http://localhost:63343/invest-project-ui/public/Test.html?_ijt=g0len3inipqu9bfu2vej06nd81&_ij_reload=RELOAD_ON_SAVE");Thread.sleep(2000);((JavascriptExecutor)driver).executeScript("window.scrollTo(100,450);");Thread.sleep(2000);driver.quit();}
}

执行结果

获取窗口截图

值得注意的是,这里FileUtils需要添加maven坐标,导入进来,坐标地址如下:

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

JAVA代码如下

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import java.util.Set;public class SeleniumTest {@Testpublic void login() throws InterruptedException {// 设置驱动System.setProperty("webdriver.chrome.driver", "/Users/yangchen/MyProject/SeleniumStudy/driver/chromedriver");// 创建一个WebDriver对象WebDriver driver = new ChromeDriver();driver.get("http://localhost:8080/#/");File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);try {FileUtils.copyFile(srcFile,new File("./screenshot.png"));} catch (IOException e) {e.printStackTrace();}driver.quit();}
}

截图如下:

Web UI自动化(selenium+java)相关推荐

  1. Web UI自动化录制工具-Selenium IDE

    Web UI自动化录制工具-Selenium IDE 简介 安装 使用 实例 关于Run for pytest... 简介 Selenium IDE可以对网页行为进行录制.回放自动执行测试步骤,最新版 ...

  2. Web UI自动化框架搭建

    本篇博文只从项目架构角度,提供一些建议供参考.不涉及具体代码编写.目前市场上主流的免费开源工具就是Selenium.大家可以根据自己项目技术栈,选择合适的语言+外加Unit Test框架,来构建自己的 ...

  3. Web UI自动化之Excel用例读取

    基于Selenium的Web UI自动化实现(java) 本文讲解了如何从 Excel 表格中读取测试用例并在 TestNG 中执行.使用的例子是打开百度首页,输入用户名和密码,完成登录. Excel ...

  4. LuckyFrameWeb测试平台(一款支持接口自动化、WEB UI自动化、APP自动化,并且支持分布式测试的全纬度免费开源测试平台)

    官网:luckyframe.cn 源码地址:https://gitee.com/seagull1985/LuckyFrameWeb 分布式测试:使用Web-Client的方式,Web端负责基本信息管理 ...

  5. Web UI自动化测试之Selenium工具篇

    本文大纲截图: 一.自动化测试介绍 1.基本介绍 1.1 自动化 概念: 由机器设备代替人工自动完成指定目标的过程 优点: 1)减少人工劳动力 2)提高工作效率 3)产品规格统一标准 4)规模化(批量 ...

  6. python运维脚本部署jdk_基于Java/Python搭建Web UI自动化环境

    Java搭建UI自动化测试环境 下载JDK8 https://www.cnblogs.com/thloveyl/p/12378124.html 配置Java环境 1.解压Jdk压缩包 2.配置环境变量 ...

  7. Web UI自动化框架大比拼

    引子 对于测试从业者来说,手工测试是一个绕不过去的坎.当年我校招毕业以测试工程师岗位进了一家互联网公司.入职第一天就被师父"拉去干活",至今印象深刻,是一个投顾管理平台(投资顾问管 ...

  8. Web UI自动化测试之元素定位

    目前,在自动化测试的实际应用中,接口自动化测试被广泛使用,但UI自动化测试也并不会被替代.让我们看看二者的对比: 接口自动化测试是跳过前端界面直接对服务端的测试,执行效率和覆盖率更高,维护成本更低,整 ...

  9. 手把手教你从0到1搭建web ui自动化框架(python3+selenium3+pytest)

    -前期准备 -环境 -实战: 从0开始 前期准备 为更好的学习自动化框架搭建,你需要提前了解以下知识: python基础知识 pytest单元测试框架 PO模式 selenium使用 环境 本次我们自 ...

最新文章

  1. 如何给英特尔致命一击——高通公布10纳米ARM服务器芯片
  2. c语言指针实验报告总结,c语言指针实验报告
  3. windows查看java进程详细信息的几种方法
  4. macbook配置java环境变量_Mac系统配置JDK环境变量
  5. MongoDB 复制集的选举原理
  6. 从零开始实现RPC框架 - RPC原理及实现
  7. JavaScript中的 in 操作符
  8. C# 回调函数的实现和应用场景
  9. Vue项目--仿大麦网移动端
  10. 有点甜用计算机怎么谈,有点甜造句
  11. 将手机流氓软件彻底赶出去
  12. 设置名字的第一个字为默认头像
  13. 涂抹oracle扩库,涂抹oracle
  14. Python 之 如何一行输入多个整数
  15. linux怎么读(中文读音发音)
  16. 香港科大EMBA校友黄立伟冠名两位商学院教授
  17. 找出一个二维数组中的鞍点
  18. 二、Servlet生命周期
  19. python键盘记录255是哪个按键_Keylogger: Python写的键盘敲击记录器
  20. 2023最新SSM计算机毕业设计选题大全(附源码+LW)之java体育运动兴趣社区系统8bisy

热门文章

  1. c#--示例选号器--随机N组选择号码
  2. Python生成随机的4位验证码(由大小写英文字母以及数字构成的随机验证码)
  3. mysql executed_mysql-----gtid_executed详解 原创
  4. 转:MM--公司委托加工流程
  5. 报道证计算机水平怎么填,毕业生档案
  6. 【跟我学oracle18c】第二十九天:Multitenant :19 Monitoring CDBs and PDBs
  7. 那根胡萝卜---走出软件作坊:三五个人十来条枪 如何成为开发正规军(十五)
  8. 35岁只是普通程序员,还有救吗?答案扎心了,老铁!
  9. 关于如何戒除青春期过度奖励的坏习惯的四点思考
  10. JavaScript-简易ATM取款机案例