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

news2024/10/6 18:29:50

目录

一、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();
    }
}

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();
    }
}

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("测试不通过");
        }
    }
}

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();
    }

}

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

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();
    }

}

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>

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

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 {
                // 否则什么也不操作
                ;
            }
        }

    }
}

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):通过frameid或者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>

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

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

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();
    }
}

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>

 代码实现

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);)

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

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>

 测试案例:代码编写一个 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();
    }
}

 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>

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

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");
    }
}

13.关闭浏览器

关闭操作分为两种:

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

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

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();//只是关闭原始页面(从哪里跳转来的页面)

    }
}

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();
    }
}

15.截图

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

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

 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"));
    }
}


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

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

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

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

相关文章

chatgpt赋能python:Python找零-让你的生活更轻松

Python 找零 - 让你的生活更轻松 在我们日常生活中&#xff0c;找零是一个很常见的问题。无论是在超市买东西、给朋友拿钱、或者是做商业交易&#xff0c;都需要进行找零操作。而使用 Python 编程语言&#xff0c;可以让这个问题更加简单易懂&#xff0c;让我们来一起学习 Pyt…

Python中的布尔类型以及布尔值介绍

什么是布尔类型&#xff1f; 布尔类型是一种逻辑类型&#xff0c;它只有两个取值&#xff1a;True&#xff08;真&#xff09;和False&#xff08;假&#xff09;。在Python中&#xff0c;True和False是内置的布尔类型常量&#xff0c;用于表示真和假的状态。 布尔运算符 在P…

一场九年前的“出发”:奠基多模态,逐鹿大模型

原创&#xff1a;谭婧 全球AI大模型的技术路线&#xff0c;没有多少秘密&#xff0c;就那几条路线&#xff0c;一只手都数得过来。 而举世闻名的GPT-4浑身上下都是秘密。 这两件事并不矛盾。为什么呢&#xff1f; 这就好比&#xff0c;回答“如何制造一台光刻机&#xff1f;”。…

Yolov5/Yolov7涨点技巧:MobileViT移动端轻量通用视觉transformer,MobileViTAttention助力小目标检测,涨点显著

1. MobileViT介绍 论文:https://arxiv.org/abs/2110.02178 现有博客都是将MobileViT作为backbone引入Yolov5,因此存在的问题点是训练显存要求巨大,本文引入自注意力的Vision Transformer(ViTs):MobileViTAttention MobileViT是一种基于Transformers的轻量级模型,它可以用于…

chatgpt赋能python:Python操作手机:SEO指南

Python 操作手机&#xff1a;SEO 指南 在移动设备占据互联网用户市场大头的今天&#xff0c;应用程序的互动变得越来越受欢迎。这就需要我们在开发和优化网站时将手机端无缝集成到我们的计划中。使用 Python 语言可以有效地实现此目标&#xff0c;本文将探讨如何使用 Python 操…

【一篇文章带你掌握HTML中ul、ol和dl列表的使用 - 超详细】

【一篇文章带你掌握HTML中ul、ol和dl列表的使用 - 超详细】_dl标签_China_YF的博客-CSDN博客 前提 在项目开发过程中&#xff0c;列表是非常常见的&#xff0c;因此列表标签也是我们使用相对频繁的标签&#xff0c;但是当我们遇到列表的时候有没有停顿思考一下&#xff0c;我在…

提醒!手机卡注销前,一定要做的四件事!

现在更换手机卡的情况对小伙伴们来说都是家常便饭的事情了&#xff0c;但是很多小伙伴在手机换号的时候&#xff0c;经常忘记解绑以前手机号绑定的一些业务&#xff0c;为此产生了很多不必要的麻烦&#xff0c;今天的这篇文章就是要告诫大家换号之前一定要做的几件事&#xff0…

基于yolov5的双目鱼体长度检测

前言 在水产养殖行业中&#xff0c;鱼体长度是衡量鱼类品质和成熟度的重要指标。然而&#xff0c;传统的鱼体长度测量方法需要手动测量&#xff0c;不仅耗时耗力还容易出现误差。正好最近做了一个基于双目视觉的鱼体检测项目&#xff0c;在这里和大家分享以下思路。 步骤 第一…

跨境电商环境搭建和买家账号培养的关键考虑因素

作为跨境电商环境搭建和买家账号培养的专业技术开发人员&#xff0c;我深知在亚马逊、速卖通、阿里国际、速卖通、美客多、shopee、Lazada、ebay、Temu等平台上运营的卖家面临的挑战 其中&#xff0c;补单是一项关键的工作&#xff0c;它能帮助卖家增加商品列表和评价数量&…

这个 冒泡排序详解过程 我能吹一辈子!!!

文章目录 冒泡排序概念冒泡排序算法思路冒泡排序代码实现冒泡排序优化 冒泡排序概念 冒泡排序是比较基础的排序算法之一&#xff0c;其思想是相邻的元素两两比较&#xff0c;较大的数下沉&#xff0c;较小的数冒起来&#xff0c;这样一趟比较下来&#xff0c;最大(小)值就会排列…

ES2020新语法:可选链操作符

目录 一、前言 二、案例 三、方法一&#xff1a;AND运算符 四、方法二&#xff1a;可选链操作符( ?. ) 1. 语法 2. 可选链与函数调用 3. 处理可选的回调函数或事件处理器 4.可选链和表达式 5.可选链访问数组元素 6.使用空值合并操作符 一、前言 今天看一个实习生写的…

Linux高级---configmap和secret

文章目录 一、ConfigMap1、介绍2、创建configmap3、使用configmap4、引入环境变量的另一种方式 二、Secret1、介绍2、创建secret3、使用secret4、引入环境变量的另一种方式 一、ConfigMap 1、介绍 ConfigMap 是一种 API 对象&#xff0c;用来将非机密性的数据保存到键值对中。使…

chatgpt赋能python:Python指定日期处理方法,从入门到实践

Python指定日期处理方法&#xff0c;从入门到实践 Python是一种高级编程语言&#xff0c;因其简单易学和功能强大而深受开发者喜爱。在日常工作中&#xff0c;我们经常需要对日期进行处理和计算。Python提供了丰富的日期和时间处理库&#xff0c;因此我们可以轻松地进行日期处…

el-table分页保留勾选的数据

1、目标效果 代码全部写在下方App.vue中&#xff0c;复制粘贴即可运行 目前选中了5条数据 点击下方切换分页&#xff0c;选中的数据消失了 2、原理 &#xff08;1&#xff09;el-table复选框&#xff0c;用一个变量数组selectedRow:[ ] 监听选择了哪些数据 <el-table-colu…

【Python】Requests库基本使用

知识目录 一、写在前面✨二、Requests库三、接口调用四、总结撒花&#x1f60a; 一、写在前面✨ 大家好&#xff01;我是初心&#xff0c;希望我们一路走来能坚守初心&#xff01; 今天跟大家分享的文章是 Python中Requests库在爬虫和自动化中的使用 &#xff0c;希望能帮助到…

这10种神级性能优化手段

引言&#xff1a;取与舍 软件设计开发某种意义上是“取”与“舍”的艺术。 关于性能方面&#xff0c;就像建筑设计成抗震9度需要额外的成本一样&#xff0c;高性能软件系统也意味着更高的实现成本&#xff0c;有时候与其他质量属性甚至会冲突&#xff0c;比如安全性、可扩展性…

Scikit-LLM:将大语言模型整合进Sklearn的工作流

我们以前介绍过Pandas和ChaGPT整合&#xff0c;这样可以不了解Pandas的情况下对DataFrame进行操作。现在又有人开源了Scikit-LLM&#xff0c;它结合了强大的语言模型&#xff0c;如ChatGPT和scikit-learn。但这个并不是让我们自动化scikit-learn&#xff0c;而是将scikit-learn…

数据库系统的结构

数据库模式基本概念 1.型与值 型&#xff1a;对某一类数据的结构和属性的说明。值&#xff1a;型的具体赋值。 2.模式和实例 模式&#xff1a; 数据库中全体数据的逻辑结构和特征的描述。简单来说就是数据的定义和描述。模式是元数据&#xff0c;数据是变化的&#xff0c;模…

chatgpt赋能python:用Python扫码——提高SEO的新方法

用Python扫码——提高SEO的新方法 作为一种快捷方便的支付方式&#xff0c;扫码支付已经得到广泛的应用。而越来越多的企业也开始将其应用于营销推广中。但除了付款和兑换优惠券之外&#xff0c;扫码还有一个很实用的用途——SEO。 什么是扫码SEO&#xff1f; 扫码SEO是一种…

全面理解链表数据结构:各种节点操作、做题技巧,易错点分析与题目清单(C++代码示例,不断更新)

什么是链表 链表是一种线性数据结构&#xff0c;它包含的元素并不是物理上连续的&#xff0c;而是通过指针进行连接。链表中的每个元素通常由一个节点表示&#xff0c;每个节点包含一个数据元素和一个或多个链接&#xff08;指针&#xff09;。 链表的主要类型包括&#xff1a;…