• 自动化测试07Selenium01


    目录

    什么是自动化测试

    Selenium介绍

    Selenium是什么

    Selenium特点

    工作原理

    Selenium+Java环境搭建 

     Selenium常用的API使用

    定位元素findElement

    CSS选择语法

    id选择器:#id

    类选择 .class

    标签选择器 标签名

    后代选择器 父级选择器 自己选择器

    xpath

    绝对路径(不常用)

    相对路径

    相对路径+索引*​编辑

    相对路径+属性值*​编辑

    相对路径+通配符*:上面写法的简写​编辑

    相对路径+文本匹配​编辑

    操作测试对象 

    等待

    sleep强制等待

    隐式等待

    显式等待 

    打印信息

    浏览器的操作

     浏览器的前进

    浏览器的后退

    浏览器的滚动条

     键盘操作

    鼠标事件 

    特殊场景如何通过SeleniumAPI完成

    补充

    关闭浏览器

    切换窗口

    截图

    总结


    什么是自动化测试

    自动化测试就相当于将人工测试手段进行转换,让代码去执行

    自动化分类:单元测试,接口测试,UI自动化测试

    Selenium介绍

    Selenium是什么

    Selenium使用来做web自动化测试框架

    Selenium特点

    支持各种浏览器;支持各种平台(Linux,Windows,MAC……);支持各种语言(Python,Java,C#,JS,Ruby……);有丰富的API

    工作原理

    自动化脚本:通过idea 编写的代码(我学习的是Java语言)

    webdriver浏览器驱动:需要大家去下载的

    浏览器:Edge浏览器,Chrome浏览器 

    Selenium+Java环境搭建 

    我的Chrome版本是:118.0.5993.72

    1、找到对应的依赖

    1. org.seleniumhq.selenium
    2. selenium-java
    3. 3.141.59

    新建一个Java项目,在pom.xml中添加以上依赖。 

    2、新建一个main类

    1. import org.openqa.selenium.WebDriver;
    2. import org.openqa.selenium.chrome.ChromeDriver;
    3. import org.openqa.selenium.chrome.ChromeOptions;
    4. public class Main {
    5. public static void main(String[] args) {
    6. ChromeOptions options = new ChromeOptions();
    7. options.addArguments("--remote-allow-origins=*");
    8. WebDriver webDriver = new ChromeDriver(options);
    9. webDriver.get("https://www.baidu.com");
    10. }
    11. }

     运行结果:

     Selenium常用的API使用

    定位元素findElement

    CSS选择语法

    id选择器:#id

    类选择 .class

    标签选择器 标签名

     

    后代选择器 父级选择器 自己选择器

    xpath

    绝对路径(不常用)

    相对路径

    相对路径+索引*
    相对路径+属性值*
    相对路径+通配符*:上面写法的简写
    相对路径+文本匹配
    1. public class Main {
    2. public static void main(String[] args) throws InterruptedException {
    3. test01();
    4. }
    5. private static void test01() throws InterruptedException {
    6. int flag = 0;
    7. ChromeOptions options = new ChromeOptions();
    8. //允许所有请求
    9. options.addArguments("--remote-allow-origins=*");
    10. WebDriver webDriver = new ChromeDriver(options);
    11. //打开百度首页
    12. webDriver.get("https://www.baidu.com");
    13. //找到百度搜索输入框
    14. // WebElement element = webDriver.findElement(By.cssSelector(".s_ipt"));
    15. WebElement element = webDriver.findElement(By.xpath("//*[@id=\"kw\"]"));
    16. //输入软件测试
    17. element.sendKeys("软件测试");
    18. //找到百度一下按钮
    19. // 点击
    20. webDriver.findElement(By.cssSelector("#su")).click();
    21. sleep(3000);
    22. //校验
    23. //找到搜索结果
    24. List elements = webDriver.findElements(By.cssSelector("a em"));
    25. for (int i = 0; i < elements.size(); i++) {
    26. //如果返回的结果有软件测试,证明测试通过,否则测试不通过
    27. if (elements.get(i).getText().equals("测试")){
    28. flag = 1;
    29. System.out.println("测试通过");
    30. break;
    31. }
    32. }
    33. if (flag == 0) {
    34. System.out.println("测试不通过");
    35. }
    36. }
    37. }

     定位一个元素有哪几种方式(你是通过什么方式去定位元素的?)

      css选择器,xpath定位元素。

    css选择器和xpath选择器你觉得哪个更好?

      css选择器定位元素效率更高。

    操作测试对象 

    webdriver 中比较常用的操作对象的方法有下面几个:

    • click 点击对象
    • send_keys 在对象上模拟按键输入
    • clear 清除对象输入的文本内容
    • submit 提交
    • text 用于获取元素的文本信息 

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

    1. private static void test02() throws InterruptedException {
    2. ChromeOptions options = new ChromeOptions();
    3. //允许所有请求
    4. options.addArguments("--remote-allow-origins=*");
    5. WebDriver webDriver = new ChromeDriver(options);
    6. webDriver.get("https://www.baidu.com/");
    7. sleep(3000);
    8. //找到百度搜索输入框,输入”java107“
    9. webDriver.findElement(By.cssSelector("#kw")).sendKeys("腾讯云智");
    10. //点击了百度一下按钮
    11. webDriver.findElement(By.cssSelector("#su")).click();
    12. sleep(3000);
    13. //清空百度搜索输入框
    14. webDriver.findElement(By.cssSelector("#kw")).clear();
    15. }
    1. private static void test03() {
    2. ChromeOptions options = new ChromeOptions();
    3. options.addArguments("--remote-allow-origins=*");
    4. WebDriver webDriver = new ChromeDriver(options);
    5. webDriver.get("https://www.baidu.com/");
    6. webDriver.findElement(By.xpath("//a[text()=\"新闻\"]")).click();
    7. }
    1. private static void test04() {
    2. ChromeOptions options = new ChromeOptions();
    3. options.addArguments("--remote-allow-origins=*");
    4. WebDriver webDriver = new ChromeDriver(options);
    5. webDriver.get("https://www.baidu.com/");
    6. String button_value = webDriver.findElement(By.cssSelector("#su")).getAttribute("value");
    7. // System.out.println(button_value);
    8. if (button_value.equals("百度一下")) {
    9. System.out.println("测试通过");
    10. } else {
    11. System.out.println(button_value);
    12. System.out.println("测试不通过");
    13. }
    14. }

    登录自动测试,验证码没法获取,屏蔽掉单独手动测试嘛?

     自动化测试加一个白名单,设定一个账号(xxxx.123)如果登录账号是(xxxx.123),此时就不需要验证码处理。

    等待

    sleep强制等待

    隐式等待

    webDriver.manage().timeouts().implicitlyWait(3, TimeUnit.DAYS);

    假设等待3天时间

    如果等待时间3天时间,强制等待,等待时间3天,也是等待

    隐式等待,最长等待3天时间,如果在3天之内获取到页面上的元素,此时执行下面的代码

    如果等待3天时间还是没有找到这个元素,此时报错。

    显式等待 

    1. private static void test06() {
    2. //创建驱动
    3. WebDriver webDriver = new ChromeDriver();
    4. //打开百度首页
    5. webDriver.get("https://www.baidu.com/");
    6. //隐式等待的代码 3秒
    7. //判断元素是否可以被点击
    8. WebDriverWait wait = new WebDriverWait(webDriver,1);
    9. wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#bottom_layer > div > p:nth-child(8)")));
    10. wait.until(ExpectedConditions.titleIs("百度一下,你就知道"));
    11. }

    隐式等待和显示等待的区别?

    隐式等待等待的式所有的元素,不能针对某个一个确定的元素进行等待,显示等待可以。

    显示等待,等待的是一定的条件(程序员自己设定)

    打印信息

    1. private static void test05() {
    2. ChromeOptions options = new ChromeOptions();
    3. options.addArguments("--remote-allow-origins=*");
    4. WebDriver webDriver = new ChromeDriver(options);
    5. webDriver.get("https://www.baidu.com/");
    6. String url = webDriver.getCurrentUrl();
    7. String title = webDriver.getTitle();
    8. if (url.equals("https://www.baidu.com/") && title.equals("百度一下,你就知道")) {
    9. System.out.println("当前页面url=" + url + ",当前页面title:"+ title);
    10. System.out.println("测试通过");
    11. } else {
    12. System.out.println("测试不通过");
    13. }
    14. }

    浏览器的操作

     浏览器的前进

    浏览器的后退

    浏览器的滚动条

    1. private static void test07() throws InterruptedException {
    2. WebDriver webDriver = new ChromeDriver();
    3. //打开百度首页
    4. webDriver.get("https://www.baidu.com/");
    5. //搜索521
    6. webDriver.findElement(By.cssSelector("#kw")).sendKeys("521");
    7. //强制等待3s
    8. webDriver.findElement(By.cssSelector("#su")).click();
    9. sleep(3000);
    10. //浏览器后退
    11. webDriver.navigate().back();
    12. sleep(3000);
    13. //强制等待3s
    14. webDriver.navigate().refresh();
    15. //浏览器浏览器前进
    16. sleep(3000);
    17. webDriver.navigate().forward();
    18. sleep(3000);
    19. ((JavascriptExecutor)webDriver).executeScript("document.documentElement.scrollTop=10000");
    20. webDriver.manage().window().maximize();
    21. sleep(3000);
    22. //全屏
    23. webDriver.manage().window().fullscreen();
    24. //设置屏幕大小
    25. webDriver.manage().window().setSize(new Dimension(600,1000));

     键盘操作

    1. private static void test08() throws InterruptedException {
    2. WebDriver webDriver = new ChromeDriver();
    3. //打开百度首页
    4. webDriver.get("https://www.baidu.com/");
    5. //搜索521
    6. webDriver.findElement(By.cssSelector("#kw")).sendKeys("521");
    7. //control+A
    8. webDriver.findElement(By.cssSelector("#kw")).sendKeys(Keys.CONTROL,"A");
    9. sleep(3000);
    10. //control+X
    11. webDriver.findElement(By.cssSelector("#kw")).sendKeys(Keys.CONTROL,"X");
    12. sleep(3000);
    13. //xontrol+V
    14. webDriver.findElement(By.cssSelector("#kw")).sendKeys(Keys.CONTROL,"V");
    15. sleep(3000);
    16. }

    鼠标事件 

    1. private static void test09() throws InterruptedException {
    2. WebDriver webDriver = new ChromeDriver();
    3. webDriver.get("https://www.baidu.com/");
    4. webDriver.findElement(By.cssSelector("#kw")).sendKeys("520");
    5. webDriver.findElement(By.cssSelector("#su"));
    6. sleep(3000);
    7. //找到图片按钮
    8. WebElement webElement = webDriver.findElement(By.cssSelector("#s_tab > div > a.s-tab-item.s-tab-item_1CwH-.s-tab-pic_p4Uej.s-tab-pic"));
    9. //鼠标右击
    10. Actions actions = new Actions(webDriver);
    11. sleep(3000);
    12. actions.moveToElement(webElement).contextClick().perform();
    13. }

    特殊场景如何通过SeleniumAPI完成

    定位一组元素

    webdriver 可以很方便的使用findElement 方法来定位某个特定的对象,不过有时候我们却需要定位一 组对象,这时候就需要使用findElements 方法。

    定位一组对象一般用于以下场景:

    • 批量操作对象,比如将页面上所有的checkbox 都勾上
    • 先获取一组对象,再在这组对象中过滤出需要具体定位的一些对象。比如定位出页面上所有的 checkbox,然后选择最后一个
      1. #coding=utf-8
      2. from selenium import webdriver
      3. import time
      4. import os
      5. dr = webdriver.Chrome()
      6. file_path = 'file:///' + os.path.abspath('checkbox.html')
      7. dr.get(file_path)
      8. # 选择页面上所有的input,然后从中过滤出所有的checkbox 并勾选之
      9. inputs = dr.find_elements_by_tag_name('input')
      10. for input in inputs:
      11. if input.get_attribute('type') == 'checkbox':
      12. input.click()
      13. time.sleep(2)
      14. dr.quit()

      get_attribute:获得属性值

    多层框架/窗口定位

    对于一个web 应用,经常会出现框架(frame) 或窗口(window)的应用,这也就给我们的定位带来 了一定的困难。

    • 定位一个frame :switch_to.frame(name_or_id_or_frame_element)
    • 定位一个窗口window:switch_to.window(name_or_id_or_frame_element)

    多层框架的定位

    switch_to.frame(name_or_id_or_frame_element):通过frame的id或者name或者frame自带的其它 属性来定位框架,这里switch_to.frame()把当前定位的主体切换了frame里。 switch_to.default_content:从frame中嵌入的页面里跳出,跳回到最外面的默认页面中。

    多层窗口定位

    有可能嵌套的不是框架,而是窗口,还有真对窗口的方法:switch_to.window

    用法与switch_to.frame 相同: driver.switch_to.window("windowName")

    层级定位

    有时候我们需要定位的元素没有直接在页面展示,而是需要对页面的元素经过一系列操作之后才展示出 来,这个时候我们就需要一层层去定位.

    下拉框处理

    下拉框是我们最常见的一种页面元素,对于一般的元素,我们只需要一次就定位,但下拉框里的内容需要进行两次定位,先定位到下拉框对下拉框进行操作后,再定位到下拉框内里的选项。

    alert、confirm、prompt 的处理

    • text 返回alert/confirm/prompt 中的文字信息
    • accept 点击确认按钮
    • dismiss 点击取消按钮,如果有的话
    • send_keys 输入值,如果alert 没有对话框就不能用了,不然会报错

      注意:switch_to.alert()只能处理原生的alert

      1. #coding:utf-8
      2. from selenium import webdriver
      3. from selenium.webdriver.common.by import By
      4. from selenium.webdriver.common.action_chains import ActionChains
      5. from selenium.common.exceptions import
      6. NoSuchElementException,UnexpectedTagNameException
      7. from selenium.webdriver.support.ui import Select
      8. from selenium.webdriver.common.alert import Alert
      9. from time import sleep
      10. import os
      11. driver=webdriver.Chrome()
      12. driver.implicitly_wait(30)
      13. file_path = 'file:///' + os.path.abspath('send.html')
      14. driver.get(file_path)
      15. #driver.get('file:///D:/PycharmProjects/test/send.html')
      16. #点击“请点击”
      17. driver.find_element_by_xpath("html/body/input").click()
      18. #输入内容
      19. driver.switch_to.alert().send_keys('webdriver')
      20. driver.switch_to.alert().accept()
      21. sleep(5)
      22. driver.quit()

    补充

    关闭浏览器

    浏览器quit和close区别?

    1. quit关闭了整个浏览器,close只是关闭了当前页面
    2. quit情况缓存,close不会清空缓存

    切换窗口

    1. private static void test10() throws InterruptedException {
    2. WebDriver webDriver = new ChromeDriver();
    3. webDriver.get("https://www.baidu.com/");
    4. webDriver.findElement(By.cssSelector("#s-top-left > a:nth-child(1)")).click();
    5. sleep(3000);
    6. //通过getWindowHandle获取所有的窗口句柄
    7. //通过getWindowHandle获取的get打开的页面窗口句柄
    8. System.out.println(webDriver.getWindowHandle());
    9. Set handles = webDriver.getWindowHandles();
    10. String target_handle = "";
    11. for (String handle:handles) {
    12. target_handle = handle;
    13. }
    14. webDriver.switchTo().window(target_handle);
    15. sleep(3000);
    16. webDriver.findElement(By.cssSelector("#ww")).sendKeys("新闻联播");
    17. webDriver.findElement(By.cssSelector("#s_btn_wr")).click();
    18. }

    截图

    1. private static void test11() throws InterruptedException, IOException {
    2. WebDriver webDriver = new ChromeDriver();
    3. webDriver.get("https://www.baidu.com/");
    4. webDriver.findElement(By.cssSelector("#kw")).sendKeys("软件测试");
    5. webDriver.findElement(By.cssSelector("#su")).click();
    6. sleep(3000);
    7. File file = ((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);
    8. FileUtils.copyFile(file,new File("E://TestCode/src/main/resources/jietu.png"));
    9. }

    总结

    定位元素:xpath,css选择器

    操作测试对象

            点击(click,submit),键盘输入

    信息获取:

            url获取,title获取,某个属性值获取

    鼠标操作

    浏览器操作

    alert操作

    选项操作

    截图

    浏览器关闭操作

    切换(窗口切换,frame切换)

  • 相关阅读:
    云原生精品资料合集(附下载)
    Spark SQL执行多次join后越来越慢,最后出现OOM
    经典算法之折半查找法
    redis安装(单机模式和哨兵模式)
    Opencv学习笔记(十二):图片腐蚀和膨胀操作
    docker 生成镜像的几个问题
    【Day33】每日一题 [779. 第K个语法符号 ]
    【UniApp】-uni-app-项目计算功能(苹果计算器)
    【OpenCV】OpenCV 之 n 点透视问题
    详谈判断点在多边形内的七种方法
  • 原文地址:https://blog.csdn.net/m0_67247641/article/details/133937350