一. 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"))); //强制等待3s Thread.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的依赖