测试|Selenium之WebDriver常见API使用

测试|Selenium之WebDriver常见API使用

文章目录

1.定位对象(findElement)

对象的定位是UI自动化测试的核心,webdriver提供了一系列的对象定位方法,这里只说css定位和xpath定位。

打开浏览器,进入百度首页,进入百度搜索输入框,输入

css定位

以类选择器为例

java 复制代码
public class Main {
    public static void main(String[] args) {
        ChromeOptions options=new ChromeOptions();
        //允许所有请求
        options.addArguments("-remote-allow-origns=*");
        WebDriver webDriver = new ChromeDriver(options);
        //进入百度首页
        webDriver.get("https://www.baidu.com");

        //找到百度搜索输入框
		WebElement element=webDriver.findElement(By.cssSelector(".s_ipt"));//通过css选择器
        //输入软件测试
        element.sendKeys("软件测试");

    }
}

xpath定位

java 复制代码
public class Main {
    public static void main(String[] args) {
        ChromeOptions options=new ChromeOptions();
        //允许所有请求
        options.addArguments("-remote-allow-origns=*");
        WebDriver webDriver = new ChromeDriver(options);
        //进入百度首页
        webDriver.get("https://www.baidu.com");

        //找到百度搜索输入框
//        WebElement element=webDriver.findElement(By.cssSelector(".s_ipt"));//通过css选择器
        WebElement element=webDriver.findElement(By.xpath("//*[@id=\"kw\"]"));//通过xpath
        //输入软件测试
        element.sendKeys("软件测试");

    }
}

css选择器语法:

id选择器:"#id"

类选择器:".classname"

标签选择器:直接标签名 "input"

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

xpath语法:

绝对路径:/html/head/title(不常用)

相对路径(双斜杠开头):

  • 相对路径+索引:索引默认以1开头. eg.//form/span[2]/input(百度一下)
  • 相对路径+属性值:eg.//input[@class="s_ipt"],//input[@id="su"]
  • 相对路径+通配符:eg,//*[@*="su"]
  • 相对路径+文本匹配:eg,//a[text()="新闻"]

相较于xpath选择器,css选择器定位元素效率更高

校验结果

java 复制代码
    public static void test01() throws InterruptedException {
        ChromeOptions options=new ChromeOptions();
        //允许所有请求
        options.addArguments("-remote-allow-origns=*");
        WebDriver webDriver = new ChromeDriver(options);
        //进入百度首页
        webDriver.get("https://www.baidu.com/");
        //找到百度搜索输入框
        WebElement element=webDriver.findElement(By.cssSelector(".s_ipt"));//通过css选择器
//        WebElement element=webDriver.findElement(By.xpath("//*[@id=\"kw\"]"));//通过xpath
        //输入软件测试
        element.sendKeys("软件测试");
        //找到百度一下按钮
        //点击
        webDriver.findElement(By.cssSelector("#su")).click();
        sleep(3000);//强制等待3ms
        //校验
        boolean flag=true;
        //1.找到搜索结果
        List<WebElement> elements=webDriver.findElements(By.cssSelector("a em"));
        sleep(10000);
        for (int i = 0; i < elements.size(); i++) {
            System.out.println(elements.get(i).getText());
            //2.条件
            if(!elements.get(i).getText().contains("测试")){
                flag=false;
                System.out.println("测试不通过");
                break;
            }
        }
        if(flag){
            System.out.println("测试通过");
        }

    }

2.操作对象

鼠标点击对象

在对象上模拟按键输入

clear清除对象输入的文本内容

java 复制代码
public static void test02() throws InterruptedException {
    ChromeOptions options=new ChromeOptions();
    options.addArguments("-remote-allow-origns=*");
    WebDriver webDriver = new ChromeDriver(options);
    //进入百度首页
    webDriver.get("https://www.baidu.com");
    //找到搜索框
    WebElement element=webDriver.findElement(By.cssSelector(".s_ipt"));
    //输入软件测试
    element.sendKeys("软件测试");
    sleep(3000);
    //点击搜索按钮
    webDriver.findElement(By.cssSelector("#su")).click();
    //删除内容
    element.clear();
    //在输入Vue框架
    element.sendKeys("Vue框架");
    sleep(3000);
    //再次点击
    webDriver.findElement(By.cssSelector("#su")).click();

}

submit提交

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

如果点击的元素放在非form标签中,会报错,如下所示:

java 复制代码
private static void test03() throws InterruptedException {
    ChromeOptions options = new ChromeOptions();
    options.addArguments("-remote-allow-origns=*");
    WebDriver webDriver = new ChromeDriver(options);
    //进入百度首页
    webDriver.get("https://www.baidu.com");
    //找到搜索框
    webDriver.findElement(By.xpath("//*[@id=\"s-top-left\"]/a[1]")).submit();//输入软件测试
}

所以推荐使用click()

text获取元素的文本信息

getText

getAttribute获取元素属性值

getText获取不了

java 复制代码
    private static void test04() {
        ChromeOptions options = new ChromeOptions();
        options.addArguments("-remote-allow-origns=*");
        WebDriver webDriver = new ChromeDriver(options);
        //进入百度首页
        webDriver.get("https://www.baidu.com");
        //获取元素属性值
//        String button_value=webDriver.findElement(By.cssSelector("#su")).getText();
//        System.out.println(button_value);	

        String button_value=webDriver.findElement(By.cssSelector("#su")).getAttribute("value");
        if(button_value.equals("百度一下")){
            System.out.println("测试通过");
        }else{
            System.out.println("测试不通过");
        }
    }

3.添加等待

1.sleep强制等待:sleep(xxx);单位为ms,1000ms=1s

2.智能等待:隐式等待(使用WebDriver对象的manage方法返回值的timeouts方法的返回值的implicitlywait方法),显示等待(使用WebDriverWait对象的until方法)

隐式等待等待所有的元素被定位到

显示等待等待一定的条件被定位到(程序员自己设定)

隐式等待:

显示等待:

java 复制代码
    private static void test07() {
        WebDriver webDriver = new ChromeDriver();
        webDriver.get("https://www.baidu.com/");
//判断能否点击
        // 显式等待设置:最长等待时间为10秒,并等待元素可见
        WebDriverWait wait = new WebDriverWait(webDriver, 10);
//        wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#su"))).click();//能定位到
        wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#s"))).click();//定位不到,就会有问题

    }

eg:driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

隐式地等待并非一个固定的等待时间当脚本执行到某个元素定位时,如果元素可以定位,则继续执行 ;如果元素定位不到,则它以轮询的方式不断的判断元素是否被定位到。直到超出设置的时长

4.打印信息

打印title和url

java 复制代码
private static void test06() {
    // 创建Chrome浏览器的WebDriver实例
    WebDriver webDriver = new ChromeDriver();

    // 导航到目标网页
    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("测试通过");
    }else {
        System.out.println(url);
        System.out.println(title);
        System.out.println("测试不通过");
    }
}

5.浏览器的操作

浏览器前进,刷新与后退

使用的navigate

java 复制代码
webDriver.navigate().back();
webDriver.navigate().refresh();
webDriver.navigate().forward();
java 复制代码
private static void test08() throws InterruptedException {
    //打开百度首页,强制等待3秒
    WebDriver webDriver = new ChromeDriver();
    webDriver.get("https://www.baidu.com/");
    sleep(3000);

    //搜索儿童节,强制等待3秒
    webDriver.findElement(By.cssSelector("#kw")).sendKeys("儿童节");//输入框的id名
    webDriver.findElement(By.cssSelector("#su")).click();
    sleep(3000);
    //浏览器后退
    webDriver.navigate().back();
    sleep(3000);
    //强制等待3秒,前进
    webDriver.navigate().refresh();
    webDriver.navigate().forward();
    sleep(3000);
}

浏览器滚动条

如果自动化不符合预期,大部分时候都是页面渲染的问题

java 复制代码
((JavascriptExecutor)webDriver).executeScript("document.documentElement.scrollTop=10000");

浏览器页面最大化最小化、全屏,设置大小

使用的manage的windows

java 复制代码
webDriver.manage().window().maximize();
sleep(3000);
webDriver.manage().window().fullscreen();
sleep(3000);
webDriver.manage().window().setSize(new Dimension(600,1000));

关闭浏览器

有两种方式:webDriver.quit();``webDriver.close();

java 复制代码
    private static void test11() 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();
    }

两者的区别:☆☆☆

  1. quit是关闭了整个浏览器,close是关闭了上一级页面
  2. quit会清空缓存(cookie),close不会清空缓存

6.键盘鼠标事件

键盘事件:使用sendKeys方法

功能键的选择:

通过send_keys()调用按键:

sendkeys(Keys.TAB) # TAB

sendkeys(Keys.ENTER) # 回车

sendkeys(Keys.SPACE) #空格键

sendkeys(Keys.ESCAPE) #回退键(Esc)

组合键:sendKeys(Keys.xxx,"xx")...

java 复制代码
private static void test09() throws InterruptedException {
    WebDriver webDriver = new ChromeDriver();
    webDriver.get("https://www.baidu.com/");
    webDriver.findElement(By.cssSelector("#kw")).sendKeys("儿童节");//输入框的id名
    //ctrl+a
    webDriver.findElement(By.cssSelector("#kw")).sendKeys(Keys.CONTROL,"A");//输入框的id名
    sleep(3000);
    //ctr+x
    webDriver.findElement(By.cssSelector("#kw")).sendKeys(Keys.CONTROL,"X");//输入框的id名
    sleep(3000);

    //ctrl+v
    webDriver.findElement(By.cssSelector("#kw")).sendKeys(Keys.CONTROL,"V");//输入框的id名
    sleep(3000);

}

信息的输入:"xxx"(直接加内容)

鼠标事件

  • contextClick() 右击
  • doubleClick() 双击
  • dragAndDrop() 拖动
  • moveToElement() 移动
java 复制代码
private static void test10() throws InterruptedException {
    WebDriver webDriver = new ChromeDriver();
    webDriver.get("https://www.baidu.com/");
    webDriver.findElement(By.cssSelector("#kw")).sendKeys("图片");
    webDriver.findElement(By.cssSelector("#su")).click();
    sleep(3000);
    //找到图片按钮
    WebElement webElement= webDriver.findElement(By.xpath("//*[@id=\"kw\"]"));
    Actions actions=new Actions(webDriver);
    sleep(10000);
    actions.moveToElement(webElement).contextClick().perform();
    sleep(10000);

}

常见功能实现案例

一组元素的定位(findElements)

(场景类似调查问卷的多选问题)执行代码,满足条件的所有选项就都选择了

多层框架中元素的定位(switchTo().frame)

有可能嵌套的不是框架,而是窗口,还有针对窗口的方法:switchTo().window

用法与switchTo.frame 相同.

切换窗口

java 复制代码
private static void test12() 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打开的页面窗口句柄
    System.out.println(webDriver.getWindowHandle());
    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();

}

什么时候不需要和需要切换窗口:

需要切换:

截图

使用((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);这个方法,并使用FileUtils工具类的copyFile方法复制到硬盘上。

java 复制代码
private static void test13() 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("F://typora插图//20230731jietu.png"));
}

这里需要引入相关依赖common-io:

xml 复制代码
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

层级定位

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

没有直接在页面中展示:可能需要一些操作才能定位到

定位思路与多层框架/窗口定位思路一致。

下拉框处理(两级处理)

(场景:类似选择收货地址的省市县...)

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

这里除了可以通过value值进行定位,还可以通过index下标(默认从0开始),定位等等

弹窗处理(alert)

页面中有一个按钮,点击按钮会有弹窗,弹窗中有对话框,对于输入信息的处理:

上传文件的处理(sendKeys(路径))

上传文件一般要打开一个本地串口,从窗口选择本地文件添加。

在selenium webdriver中,只需要定位上传按钮,通过sendKeys添加本地文件路径即可,绝对路径和相对路径均可,关键是上传的文件存在。

总结

相关推荐
waterHBO6 小时前
python 爬虫 selenium 笔记
爬虫·python·selenium
chenjingming66614 小时前
windows使用tcpdump.exe工具进行抓包教程
网络·测试工具·tcpdump
小码哥说测试1 天前
软件测试技术之 GPU 单元测试是什么!
自动化测试·功能测试·测试工具·jmeter·单元测试·集成测试·postman
全能全知者1 天前
不废话简单易懂的Selenium 页面操作与切换
python·selenium·测试工具·网络爬虫
测试19982 天前
使用Selenium进行网页自动化
自动化测试·软件测试·python·selenium·测试工具·自动化·测试用例
做一道光2 天前
1、QAC静态测试常用操作
软件测试·测试工具·静态测试
假女吖☌2 天前
postman接口关联
测试工具·postman
测试杂货铺2 天前
selenium元素定位:元素点击交互异常解决方法
自动化测试·软件测试·python·selenium·测试工具·职场和发展·单元测试
讓丄帝愛伱2 天前
PostMan使用变量
测试工具·postman
可愛小吉3 天前
Python 课程12-Python 自动化应用
开发语言·前端·selenium·openpyxl·reportlab