测试|Selenium之WebDriver常见API使用

测试|Selenium之WebDriver常见API使用

1.定位对象(findElement)

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

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

css定位

以类选择器为例

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-v61O4oFp-1690808760925)(F:\typora插图\image-20230731140841726.png)]

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定位

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-W8pyUrlz-1690808760926)(F:\typora插图\image-20230731141138565.png)]

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()="新闻"]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cSMnndAF-1690808760927)(F:\typora插图\image-20230731142633112.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HLYsPWDn-1690808760927)(F:\typora插图\image-20230731142800411.png)]

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

校验结果

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

    }

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XKdHGhzA-1690808760928)(F:\typora插图\image-20230731203215211.png)]

2.操作对象

鼠标点击对象

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IQWaj859-1690808760929)(F:\typora插图\image-20230731150321017.png)]

在对象上模拟按键输入

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-E4wBRsew-1690808760929)(F:\typora插图\image-20230731150336385.png)]

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

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

}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cFWfGAvj-1690808760930)(F:\typora插图\image-20230731151451051.png)]

submit提交

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-whXmKlHk-1690808760930)(F:\typora插图\image-20230731151607972.png)]

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

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();//输入软件测试
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eSdU7hMh-1690808760931)(F:\typora插图\image-20230731153701092.png)]

所以推荐使用click()

text获取元素的文本信息

getText[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bSlZ9I3j-1690808760931)(F:\typora插图\image-20230731160404555.png)]

getAttribute获取元素属性值

getText获取不了

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-j0BtupZf-1690808760932)(F:\typora插图\image-20230731160117303.png)]

3.添加等待

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

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

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

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

隐式等待:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2SH1RQBD-1690808760932)(F:\typora插图\image-20230731171845814.png)]

显示等待:

    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

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7TIm4yKV-1690808760933)(F:\typora插图\image-20230731165548572.png)]

5.浏览器的操作

浏览器前进,刷新与后退

使用的navigate

webDriver.navigate().back();
webDriver.navigate().refresh();
webDriver.navigate().forward();
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);
}

浏览器滚动条

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

((JavascriptExecutor)webDriver).executeScript("document.documentElement.scrollTop=10000");

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-GLq04iy7-1690808760933)(F:\typora插图\image-20230731173929172.png)]

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

使用的manage的windows

webDriver.manage().window().maximize();
sleep(3000);
webDriver.manage().window().fullscreen();
sleep(3000);
webDriver.manage().window().setSize(new Dimension(600,1000));

关闭浏览器

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

    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”)…

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() 移动

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LOz4oOAa-1690808760934)(F:\typora插图\image-20230731181247322.png)]

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)

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jTdQPS6T-1690808760935)(F:\typora插图\image-20230731184900090.png)]

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xx7EM8c9-1690808760935)(F:\typora插图\image-20230731185828203.png)]

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

切换窗口

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

}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-guhGFdwu-1690808760935)(F:\typora插图\image-20230731195900770.png)]

什么时候不需要和需要切换窗口:
在这里插入图片描述
需要切换:在这里插入图片描述

截图

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

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:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

层级定位

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

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

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

下拉框处理(两级处理)

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

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-iJSXIyPV-1690808760937)(F:\typora插图\image-20230731190814317.png)]

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

弹窗处理(alert)

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HtZTomTP-1690808760937)(F:\typora插图\image-20230731192054709.png)]

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

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

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

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LAi7R834-1690808760937)(F:\typora插图\image-20230731192517454.png)]

总结

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-D8JEDIG1-1690808760938)(F:\typora插图\image-20230731210509252.png)]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值