软件测试之自动化测试【webdriver API】

目录

一、webdriver API

1.元素的定位

2.操作测试对象

3.添加等待

3.1 sleep 强制等待

3.2 隐式等待

3.3 显式等待 

4.打印信息

5.浏览器的操作

5.1 浏览器的前进和后退

5.2 浏览器滚动条操作

5.3 浏览器最大化及设置浏览器宽、高

6.键盘按键

7. 鼠标事件

8.定位一组元素

9.多层框架/窗口定位

9.1 多层框架的定位

9.2 多窗口定位

10.下拉框处理

11.alert、confifirm、prompt 的处理

11.1 alert 弹窗操作 

12.上传文件操作

13.关闭浏览器

14.切换窗口

15.截图


🌈上节课我们已经学习了webdriver API 中元素的定位、操作测试对象,如果对自动化测试还没有了解的朋友,请看我的上一篇文章:软件测试之自动化测试_奋斗小温的博客-CSDN博客

🔥接下来的测试课我们继续讲解 webdriver API,请继续关注我,这节课是本章自动化测试的一个核心知识点+高频面试题❗❗❗


一、webdriver API

1.元素的定位

2.操作测试对象

如果这两个内容没有听懂的朋友,请看我博客测试专栏的上一篇文章:软件测试之自动化测试_奋斗小温的博客-CSDN博客

3.添加等待

3.1 sleep 强制等待

如果是等待 3 天时间,强制等待一直等待,等待的时间是 3 天

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import static java.lang.Thread.sleep;

//强制等待
public class Main5 {
    public static void main(String[] args) throws InterruptedException {
        test02();
    }

    //clear 清除对象输入的文本内容
    private static void test02() throws InterruptedException {
        ChromeOptions options = new ChromeOptions();
        //允许所有请求
        options.addArguments("--remote-allow-origins=*");
        WebDriver webDriver = new ChromeDriver(options);
        //打开百度首页
        webDriver.get("https://www.baidu.com");
        sleep(3000);
        //找到百度输入框的:id为kw,并且输入“什么是测试”
        webDriver.findElement(By.cssSelector("#kw")).sendKeys("什么是测试");
        //找到百度一下按钮:“su”,并且点击
        webDriver.findElement(By.cssSelector("#su")).click();
        sleep(300000000);
        //清除百度输入框的中的数据
        webDriver.findElement(By.cssSelector("#kw")).clear();
    }
}

2ccb6912ac5146a286bb13ef5f50165f.png

3.2 隐式等待

  • 通过添加 implicitlyWait() 方法就可以方便的实现智能等待;implicitlyWait(30) 的用法比 sleep() 更智能,后者只能选择一个固定的时间的等待,前者可以在一个时间范围内智能的等待。
WebDriver.Timeouts implicitlyWait(long var1, TimeUnit var3);
  • 隐式地等待并非一个固定的等待时间,当脚本执行到某个元素定位时,如果元素可以定位,则继续执行;如果元素定位不到,则它以轮询的方式不断的判断元素是否被定位到。直到超出设置的时长

假设等待3天时间:这里隐式等待最长等待为3天,如果3天内获取到页面上的元素,此时执行下边的代码;如果等待3天时间还是没有找到这个元素,此时报错

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.util.concurrent.TimeUnit;
import static java.lang.Thread.sleep;


//等待
public class Main5 {
    public static void main(String[] args) throws InterruptedException {
        test02();
    }

    //clear 清除对象输入的文本内容
    private static void test02() throws InterruptedException {
        ChromeOptions options = new ChromeOptions();
        //允许所有请求
        options.addArguments("--remote-allow-origins=*");
        WebDriver webDriver = new ChromeDriver(options);
        //打开百度首页
        webDriver.get("https://www.baidu.com");
        sleep(3000);
        //找到百度输入框的:id为kw,并且输入“什么是测试”
        webDriver.findElement(By.cssSelector("#kw")).sendKeys("什么是测试");
        //找到百度一下按钮:“su”,并且点击
        webDriver.findElement(By.cssSelector("#su")).click();
        //sleep(300000000);//强制等待
        webDriver.manage().timeouts().implicitlyWait(3, TimeUnit.DAYS);
        //清除百度输入框的中的数据
        webDriver.findElement(By.cssSelector("#kw")).clear();
    }
}

1428b51ef7a1488a95b0476afdb000da.png

3.3 显式等待 

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.concurrent.TimeUnit;
import static java.lang.Thread.sleep;

public class Main7 {
    public static void main(String[] args) throws InterruptedException {
        test02();
    }

    private static void test02() throws InterruptedException {
        //创建驱动
        WebDriver webDriver = new ChromeDriver();
        //打开百度首页
        webDriver.get("https://www.baidu.com");
        // 判断元素是否可以被点击
        //显式等待
        WebDriverWait wait = new WebDriverWait(webDriver, 3000);
        wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#bottom_layer > div > p:nth-child(8)")));

    }
}
  •  隐式等待:等待的是所有的元素
  • 显式等待:等待的是一定的条件(程序员自己设定)

4.打印信息

1️⃣打印 title    2️⃣打印 url

测试用例:检验百度首页的 url 和 title 是否符合预期

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class Main6 {
    public static void main(String[] args) throws InterruptedException {
        test();
    }

    //clear 清除对象输入的文本内容
    private static void test() throws InterruptedException {
        ChromeOptions options = new ChromeOptions();
        //允许所有请求
        options.addArguments("--remote-allow-origins=*");
        WebDriver webDriver = new ChromeDriver(options);
        //打开百度首页
        webDriver.get("https://www.baidu.com");
        String url = webDriver.getCurrentUrl();
        String title = webDriver.getTitle();
        if (url.equals("https://www.baidu.com/") && title.equals("百度一下,你就知道")) {
            System.out.println("当前页面url:" + url + "当前页面title:" + title);
            System.out.println("测试通过");
        } else {
            System.out.println("测试不通过");
        }
    }
}

cb7aec8deef944adb796cde2df2f1d94.png

5.浏览器的操作

5.1 浏览器的前进和后退

前进:webDriver.navigate().forward();

后退:webDriver.navigate().back();

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import static java.lang.Thread.sleep;

public class Main8 {
    public static void main(String[] args) throws InterruptedException {
        test02();
    }

    private static void test02() throws InterruptedException {
        WebDriver webDriver = new ChromeDriver();
        //打开百度首页
        webDriver.get("https://www.baidu.com/");
        //搜索 521
        webDriver.findElement(By.cssSelector("#kw")).sendKeys("521");//百度输入框的:id为kw
        sleep(3000);//强制等到3秒
        webDriver.findElement(By.cssSelector("#su")).click();//百度一下按钮:“su”
        //浏览器后退
        sleep(3000);
        webDriver.navigate().back();
        //强制等待3秒
        sleep(3000);
        webDriver.navigate().refresh();//刷新
        //浏览器前进
        sleep(3000);
        webDriver.navigate().forward();
    }

}

d60c77bfef8640839ed9689fd27d8e45.png

5.2 浏览器滚动条操作

浏览器滚动条的控制需要依靠js脚本

#将浏览器滚动条滑到最顶端
document.documentElement.scrollTop=0
#将浏览器滚动条滑到最底端
document.documentElement.scrollTop=10000

例如:

.测试案例:搜索521,然后滚动条滑倒最下边

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import static java.lang.Thread.sleep;
public class Main9 {
    public static void main(String[] args) throws InterruptedException {
        test02();
    }

    private static void test02() throws InterruptedException {
        WebDriver webDriver = new ChromeDriver();
        //打开百度首页
        webDriver.get("https://www.baidu.com/");
        //搜索 521
        webDriver.findElement(By.cssSelector("#kw")).sendKeys("521");//百度输入框的:id为kw
        sleep(3000);//强制等到3秒
        webDriver.findElement(By.cssSelector("#su")).click();//百度一下按钮:“su”
        sleep(3000);
        ((JavascriptExecutor)webDriver).executeAsyncScript("document.documentElement.scrollTop=10000");
    }

}

5.3 浏览器最大化及设置浏览器宽、高

浏览器最大化:

webDriver.manage().window().maximize();

设置浏览器宽、高:

webDriver.manage().window().setSize(new Dimension(width, high));

例如:

测试案例:先打开一个浏览器,继续打开百度网页,搜索521并且百度一下,进行浏览器后退、浏览器前进、滚动条滑动、浏览器最大化、浏览器悬停和设置浏览器宽、高

import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import static java.lang.Thread.sleep;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        test02();
    }

    private static void test02() throws InterruptedException {
        WebDriver webDriver = new ChromeDriver();
        //打开百度首页
        webDriver.get("https://www.baidu.com/");
        //搜索 521
        webDriver.findElement(By.cssSelector("#kw")).sendKeys("521");//百度输入框的:id为kw
        sleep(3000);//强制等到3秒
        webDriver.findElement(By.cssSelector("#su")).click();//百度一下按钮:“su”
        //浏览器后退
        sleep(3000);
        webDriver.navigate().back();
        //强制等待3秒
        sleep(3000);
        webDriver.navigate().refresh();//刷新
        // 浏览器前进
        sleep(3000);
        webDriver.navigate().forward();
        sleep(3000);
        //浏览器滚动条操作
        ((JavascriptExecutor)webDriver).executeScript("document.documentElement.scrollTop=10000");
        //浏览器最大化
        webDriver.manage().window().maximize();
        sleep(3000);
        //浏览器悬停
        webDriver.manage().window().fullscreen();
        sleep(3000);
        //设置浏览器宽、高
        webDriver.manage().window().setSize(new Dimension(600, 1000));
    }

}

6.键盘按键

要使用键盘按键,必须引入keys 包:

from selenium.webdriver.common.keys import Keys

通过 send_keys() 调用按键

sendKeys(Keys.TAB) # TAB
sendKeys(Keys.ENTER) # 回车
sendKeys(Keys.SPACE) #空格键
sendKeys(Keys.ESCAPE) #回退键(Esc)
sendKeys(Keys.CONTROL,'a') #全选(Ctrl+A)
sendKeys(Keys.CONTROL,'c') #复制(Ctrl+C)
sendKeys(Keys.CONTROL,'x') #剪贴(Ctrl+X)
sendKeys(Keys.CONTROL,'v') #粘贴(Ctrl+V)

例如:

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import static java.lang.Thread.sleep;

public class Main10 {
    public static void main(String[] args) throws InterruptedException {
        test();
    }

    private static void test() throws InterruptedException {
        WebDriver webDriver = new ChromeDriver();
        webDriver.get("https://www.baidu.com/");
        webDriver.findElement(By.cssSelector("#kw")).sendKeys("521");
        sleep(3000);
        //ctrl+A
        webDriver.findElement(By.cssSelector("#kw")).sendKeys(Keys.CONTROL, "A");
        sleep(3000);
        //ctrl+X
        webDriver.findElement(By.cssSelector("#kw")).sendKeys(Keys.CONTROL, "X");
        //ctrl+V
        sleep(3000);
        webDriver.findElement(By.cssSelector("#kw")).sendKeys(Keys.CONTROL, "V");
    }

}

7. 鼠标事件

要使用鼠标事件需要导入工具包:

import org.openqa.selenium.interactions.Actions;

语法:

#鼠标拖动事件
Actions(webDriver).moveToElement(webElement).contextClick().perform();
  • Actions(webDriver):生成用户的行为。所有的行动都存储在actionchains 对象。通过perform()存储的行为。
  • moveToElement(element):移动鼠标到一个元素中,menu 上面已经定义了他所指向的哪一个元素
  • perform():执行所有存储的行为
  • ActionChains
  1. context_click() 右击
  2. double_click() 双击
  3. drag_and_drop() 拖动
  4. move_to_element() 移动

测试案例:打开百度首页,搜索520并且百度一下,把鼠标放在图片的按钮上进行右击

🌈如何找到图片的按钮:F12进行元素选择,把鼠标放在图片上进行定位,右击进行Copy,选择 Copy selector

fcba07339f094aecabe0c9cd7d61edd2.png

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.interactions.Actions;
import static java.lang.Thread.sleep;
//鼠标事件

public class Main11 {
    public static void main(String[] args) throws InterruptedException {
        test();
    }

    private static void test() throws InterruptedException {
        WebDriver webDriver = new ChromeDriver();
        webDriver.get("https://www.baidu.com/");
        webDriver.findElement(By.cssSelector("#kw")).sendKeys("520");
        sleep(3000);
        webDriver.findElement(By.cssSelector("#su")).click();
        sleep(3000);
        //找到图片按钮
        WebElement webElement = webDriver.findElement(By.cssSelector("#s_tab > div > a.s-tab-item.s-tab-item_1CwH-.s-tab-pic_p4Uej.s-tab-pic"));
        //鼠标右击
        Actions actions = new Actions(webDriver);
        sleep(3000);
        actions.moveToElement(webElement).contextClick().perform();
    }

}

407f2f1870984ceb986fa13232c442ab.png

8.定位一组元素

webdriver 可以很方便的使用findElement 方法来定位某个特定的对象

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

  • 批量操作对象,比如将页面上所有的checkbox 都勾上
  • 先获取一组对象,再在这组对象中过滤出需要具体定位的一些对象。比如定位出页面上所有的checkbox,然后选择最后一个

HTML 示例测试:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Checkbox</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">radio</label>
      <div class="controls">
        <input type="radio" id="r1" />
      </div>
    </div>
    <div class="control-group">
      <label class="control-label" for="r">radio</label>
      <div class="controls">
        <input type="radio" id="r2" />
      </div>
    </div>
  </form>
</div>
</body>
</html>

5299d3a9847043ceaeb90573e87a8358.png

 用浏览器打开这个页面我们看到三个复选框和两个单选框,下面我们就来定位这三个复选框

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        test();
    }

    private static void test() throws InterruptedException {
        WebDriver webDriver = new ChromeDriver();
        webDriver.get("file:///D:/Self_learning/tesk/test/Test/checkbox.html");
        //隐式等待
        webDriver.manage().timeouts().implicitlyWait(3, TimeUnit.DAYS);
        List<WebElement> webElements = webDriver.findElements(By.cssSelector("input"));
        for(int i = 0; i < webElements.size(); i++) {
            // 如果每个元素type值等于checkbox进行点击
            // getAttribute获取页面上的元素属性值,里面的type是当前元素属性
            if(webElements.get(i).getAttribute("type").equals("checkbox")){
                webElements.get(i).click();
            } else {
                // 否则什么也不操作
                ;
            }
        }

    }
}

6107a21d817f4c49b2ca920e60419a80.png

9.多层框架/窗口定位

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

  • 定位一个frame :switchTo.frame(name or id or frameElement)
  • 定位一个窗口window:switchTo.window(name or id or frameElement)

9.1 多层框架的定位

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

HTML 示例测试(frame.html、inner.html):设计一个多框架页面的定位

 frame.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>frame</title>
    <!--  <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" />-->
    <script type="text/javascript">$(document).ready(function(){
    });
    </script>
</head>
<body>
    <div class="row-fluid">
        <div class="span10 well">
            <h3>frame</h3>
            <iframe id="f1" src="inner.html" width="800", height="600"></iframe>
        </div>
    </div>
</body>
<!--<script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>-->
</html>

inner.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>inner</title>
</head>
<body>
    <div class="row-fluid">
        <div class="span6 well">
            <h3>inner</h3>
            <iframe id="f2" src="https://www.baidu.com/"
                width="700"height="500"></iframe>
            <a href="javascript:alert('watir-webdriver better than selenium webdriver;')">click</a>
        </div>
    </div>
</body>
</html>

195d22b7654c4b3fae5a952f1d4ff793.png

下面通过switchTo.frame() 方法来获取 frame 中的属性进行定位:

不可以直接用 webDriver.findElement(By.cssSelector(" ")).click();,因为 frame 里边的元素是获取不到

c1d47e8d6bbf41d78794f4cbe6083e45.png

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
//多框架定位

public class Main {
    public static void main(String[] args) throws InterruptedException {
        test();
    }

    private static void test() throws InterruptedException {
        WebDriver webDriver = new ChromeDriver();
        //打开html写的多框架页面
        webDriver.get("file:///D:/Self_learning/tesk/test/Test/frame.html");
        //获取 frame 中的属性
        webDriver.switchTo().frame("f1");
        //选择click按钮,点击
        webDriver.findElement(By.cssSelector("body > div > div > a")).click();
    }
}

4cf7fc576c3840ea8892cbc2af7244b5.png

9.2 多窗口定位

有可能嵌套的不是框架,而是窗口,还有真对窗口的方法:switchTo.window(用法与 switchTo.frame 相同)

10.下拉框处理

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

HTML示例说明:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>select</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>

c9dfcbdbfa84414eb47cf003677e5612.png

 代码实现

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.Select;
//下拉框处理

public class Main {
    public static void main(String[] args) throws InterruptedException {
        test();
    }

    private static void test() throws InterruptedException {
        WebDriver webDriver = new ChromeDriver();
        //打开html写的多框架页面
        webDriver.get("file:///D:/Self_learning/tesk/test/Test/select.html");
        //选择下拉框按钮
        WebElement webElement = webDriver.findElement(By.cssSelector("#ShippingMethod"));
        //使用 select 完成下拉框操作
        Select select = new Select(webElement);
        //下标定位——从0开始
        select.selectByIndex(3);
        //值定位——源码属性的值
        select.selectByValue("12.51");

    }
}

下标定位——从0开始(select.selectByIndex(3);)

38bb148e9fa6456787b802772bdfc165.png

 值定位——源码属性的值(select.selectByValue("12.51");)

7a22195e68bd4071a59b08ed5de25d13.png

c173e132fe4c45348cf606631ccf6f23.png

11.alertconfifirmprompt 的处理

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

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

11.1 alert 弹窗操作 

HTML示例说明:弹窗操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <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>

75a34e57ba92456c8ab898f9cfc2bb09.png

 测试案例:代码编写一个 alert 弹窗,在弹窗中输入奋斗小温,随后 alert 弹窗确认

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import static java.lang.Thread.sleep;

//针对 alert 操作

public class Main15 {
    public static void main(String[] args) throws InterruptedException {
        test();
    }

    private static void test() throws InterruptedException {
        WebDriver webDriver = new ChromeDriver();
        //打开html写的多框架页面
        webDriver.get("file:///D:/Self_learning/tesk/test/Test/title1.html");
        //找到弹窗按钮并点击
        webDriver.findElement(By.cssSelector("button")).click();
        sleep(3000);
        // alert 弹窗取消
        webDriver.switchTo().alert().dismiss();
        sleep(3000);
        // 点击按钮
        webDriver.findElement(By.cssSelector("button")).click();
        //在 alert 弹窗中输入奋斗小温
        webDriver.switchTo().alert().sendKeys("奋斗小温");
        sleep(3000);
        // alert 弹窗确认
        webDriver.switchTo().alert().accept();
    }
}

13bf186b0b7943429294ec8bf9428048.png

 confirm、prompt 操作与 alert相同

12.上传文件操作

🌈只要定位上传按钮,通过 sendKeys 添加本地文件路径就可以了。绝对路径和相对路径都可以,关键是上传的文件存在。

HTML代码示例:上传文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>upload_file上传文件</title>
</head>
<body>
    <input type="file">
</body>
</html>

9da0f955b0d140ed82857ab5cdc84ee3.png

 测试案例:实现一个上传文件需求

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
// 上传文件操作

public class Main16 {
    public static void main(String[] args) throws InterruptedException {
        test();
    }

    private static void test() throws InterruptedException {
        WebDriver webDriver = new ChromeDriver();
        //打开html写的多框架页面
        webDriver.get("file:///D:/Self_learning/tesk/test/Test/upload_file.html");
        //实现文件上传
        webDriver.findElement(By.cssSelector("input")).sendKeys("D:\\图片\\Saved Pictures");
    }
}

9c34b42e3b7c4a5d9d67b0e60fcca6ae.png

13.关闭浏览器

关闭操作分为两种:

  1. quit() :关闭整个浏览器(并且清空缓存)
  2. close() :只是关闭原始页面(从哪里跳转来的页面)(并且不会清空缓存)

测试案例:打开百度首页,点击新闻按钮,通过 quit 和 click 方法关闭浏览器

47c43a6d6f954987b696c2911681a7bc.png

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import static java.lang.Thread.sleep;
//关闭浏览器
public class Main17 {
    public static void main(String[] args) throws InterruptedException {
        test();
    }

    private static void test() throws InterruptedException {
        WebDriver webDriver = new ChromeDriver();
        webDriver.get("https://www.baidu.com/");
        //找到新闻按钮并点击
        webDriver.findElement(By.cssSelector("#s-top-left > a:nth-child(1)")).click();
        sleep(4000);
        //webDriver.quit();//关闭整个浏览器页面
        webDriver.close();//只是关闭原始页面(从哪里跳转来的页面)

    }
}

52725c0514954b15872c8c504ba1faa4.png

14.切换窗口

测试案例:打开百度首页,点击新闻按钮,在百度新闻框输入“新闻联播”并且点击百度一下

  • getWindowHandles 获取所有的窗口句柄
  • getWindowHandle 获取 get 打开的页面窗口句柄
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Set;
import static java.lang.Thread.sleep;
//切换窗口

public class Main18 {
    public static void main(String[] args) throws InterruptedException {
        test();
    }

    private static void test() throws InterruptedException {
        WebDriver webDriver = new ChromeDriver();
        webDriver.get("https://www.baidu.com/");
        //新闻选择器
        webDriver.findElement(By.cssSelector("#s-top-left > a:nth-child(1)")).click();
        sleep(3000);
        // 通过 getWindowHandles 获取所有的窗口句柄
        // 通过 getWindowHandle 获取 get 打开的页面窗口句柄
        //获取当前页面元素
        Set<String> handles = webDriver.getWindowHandles();
        String target_handle = "";
        for (String handle : handles) {
            target_handle = handle;
        }
        webDriver.switchTo().window(target_handle);
        sleep(3000);
        //找到新闻页面下的输入框
        webDriver.findElement(By.cssSelector("#ww")).sendKeys("新闻联播");
        //找到新闻页面下的百度一下
        webDriver.findElement(By.cssSelector("#s_btn_wr")).click();
    }
}

3c651a82bd464e799b703d3daba3fea7.png

15.截图

截图需要导入 common-io 依赖:Maven Repository: Search/Browse/Explore (mvnrepository.com)

搜索 common-io,复制依赖到 pom.xml 中

70eef7dc51d14682a9196542995d33ec.png

 pom.xml 中的代码(引入依赖):

<?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>Test2</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.141.59</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>
    </dependencies>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
</project>

测试案例:打开百度首页,输入“软件测试”,对测试页面进行截图 

截图:((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE); 

复制到硬盘:FileUtils.copyFile(File srcFile, File destFile);

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
import java.io.IOException;
import static java.lang.Thread.sleep;

//截图

public class Main19 {
    public static void main(String[] args) throws InterruptedException, IOException {
        test();
    }

    private static void test() 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();
        sleep(3000);
        //截图
        File file = ((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);
        //复制到硬盘
        FileUtils.copyFile(file, new File("D://20230526jietu.png"));
    }
}

d1889805b3654087b9d3355594e3513e.png


 此时我们就已经学完了 webdriver API

  1. 定位元素:xpath、css 选择器
  2. 操作测试对象:点击(click、submit)、键盘输入
  3. 信息获取:url 获取、title 获取、某个属性值获取
  4. 鼠标操作
  5. 浏览器操作
  6. alert 操作
  7. 选项操作
  8. 截图操作
  9. 浏览器关闭操作
  10. 切换 frame
  11. 切换窗口

 

  • 108
    点赞
  • 100
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 95
    评论
评论 95
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奋斗小温

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值