首页 > 编程语言 >Java+Selenium自动化

Java+Selenium自动化

时间:2023-02-11 15:57:17浏览次数:63  
标签:webDriver Java selenium 自动化 Selenium findElement org import public

学习地址

  https://56data.cc/2150.html#4.2

  https://blog.csdn.net/weixin_45203607/article/details/125895112

  https://www.selenium.dev/zh-cn/documentation/webdriver/waits/

  https://www.shuzhiduo.com/A/xl56b4RY5r/

驱动下载:

  根据浏览器版本下载对应驱动

  http://chromedriver.storage.googleapis.com/index.html

  查看浏览器版本:chrome://version

一、概述

  WebDriver:浏览器驱动,是一个自动化API,用来驱动浏览器。

  Selenium:是web浏览器自动化的一个工具集,可以控制浏览器完成实例,模拟用户与浏览器的交互。

二、启动Chrome浏览器

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class TestCase004 {
    public WebDriver wd;
    @BeforeClass
    public void beforeTest(){
        wd=new ChromeDriver();
        wd.manage().window().maximize();
    }
    @Test
    public void testOpenChrome(){
        wd.get("https://www.baidu.com");
} @AfterClass public void afterTest(){ wd.quit(); } }

三、元素等待

  在自动化性能测试过程中,经常会出现取不到界面元素,其中之一的原因是界面元素的加载时间与我们访问页面的时机不一致。可能是界面要素过多或者网络较慢,界面一直在加载中;为解决这种问题,selenium提供了等待方法,分为显示等待隐式等待

  3.1、显示等待

    就是明确的要等待某个元素的出现或者是某个元素的可点击条件,等不到,就一直等,除非在规定的时间之内都没有找到,那么就跳出Exception。

    处理方式1:通过线程等待函数,让自动化测试做一定时间的等待,Thread.sleep(1000),毫秒单位。

    缺点:我们很难去确定等待的时间长度,时间较短不能解决上述问题,时间较长浪费时间。

    处理方式2:在设置时间内,默认每隔一段时间检测一次当前页面元素是否存在,如果超过设置时间检测不到就抛出异常,采用WebDriverWait类+ExceptedConditions接口。

    WebDriverWait类:是由WebDirver提供的等待方法。在设置时间内,默认每隔一段时间检测一次当前页面元素是否存在,如果超过设置时间检测不到就抛出异常。格式如下:

    WebDriverWait(driver,10,1)

    dirver:浏览器驱动。

    10:最长超时时间,默认以秒为单位。

    1:检测的时间间隔,默认为0.5s。

package com.hqh.test;

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.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.time.Duration;

public class TestCase004 {
    //显示等待
    public WebDriver dirver;
    @BeforeClass
    public void beforeTest(){
        dirver=new ChromeDriver();
        dirver.manage().window().maximize();
        dirver.get("https://www.baidu.com");
    }
    @Test
    public void testSetWait1() throws InterruptedException {
        //WebDriverWait写法1
        Duration x= Duration.ofSeconds(10);//必须将int格式的10转换为Duration格式下的变量,才能去调用使用,否则报无法兼容的错误
        Duration y= Duration.ofSeconds(1);//默认0.5s
        //WebDriverWait(浏览器驱动,最长超过时间,检测的间隔时间),以秒为单位
        WebDriverWait wait=new WebDriverWait(dirver,x,y);
        wait.until(new ExpectedCondition<WebElement>() {
            @Override
            public WebElement apply(WebDriver webDriver) {
                return webDriver.findElement(By.id("kw"));
            }
        }).sendKeys("selenium");//输入selenium
        dirver.findElement(By.id("su")).click();
        Thread.sleep(2000);
    }
    @Test
    public void testSetWait2(){
        //WebDriverWait写法2
        Duration x=Duration.ofSeconds(10);
        new WebDriverWait(dirver,x).until(ExpectedConditions.presenceOfElementLocated(By.id("kw")));
        dirver.findElement(By.id("kw")).sendKeys("selenium");
        dirver.findElement(By.id("su")).click();
    }
    @AfterClass
    public void afterTest(){
        dirver.quit();
    }
}

  3.2、隐式等待

    pageLoadTimeout(1,TimeUnit.SECONDS):页面加载时的超时时间。
    setScriptTimeout(1,TimeUnit.SECONDS):异步脚本的超时时间。
    implicitlyWait(10,TimeUnit.SECONDS):识别对象时的超时时间,过了这个时间如果还没找到的话就会抛出NoSuchElement异常。
package com.hqh.test;

import org.checkerframework.checker.units.qual.A;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;

public class TestCase005 {
    //隐式等待
    public WebDriver webDriver;

    @BeforeClass
    public void before(){
        webDriver=new ChromeDriver();
        webDriver.manage().window().maximize();
        //将页面加载超时时间设置为1s
        webDriver.manage().timeouts().pageLoadTimeout(1,TimeUnit.SECONDS);
        webDriver.get("https://www.baidu.com");
    }
    @Test
    public void testWait(){
        //定位对象时给定1s的时间,如果1s内定位不到则抛出异常
        webDriver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
        webDriver.findElement(By.id("kw")).sendKeys("wait");
        //异步脚本的超时时间设置成3s
        webDriver.manage().timeouts().setScriptTimeout(3,TimeUnit.SECONDS);
        webDriver.findElement(By.id("su")).click();
    }
    @AfterClass
    public void after(){
        webDriver.quit();
    }

}

 四、控制浏览器操作

  4.1、控制浏览器窗口大小

    driver.mange().window().maximize():设置浏览器最大化;

    driver.mange().window().setSize(new Dimension(宽度,高度)):设置浏览器宽高,需要调用Dimension实例。

package com.hqh.test;

import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class TestCase006 {
    //控制浏览器窗口大小
    public WebDriver webDriver;
    @BeforeClass
    public void before(){
        webDriver=new ChromeDriver();
        webDriver.get("https://www.baidu.com");
    }
    @Test
    public void setMaxSize() throws InterruptedException {
        //设置浏览器最大化
        webDriver.manage().window().maximize();
        Thread.sleep(3000);
    }
    @Test
    public void setSize() throws InterruptedException {
        //设置浏览器指定大小宽度
        webDriver.manage().window().setSize(new Dimension(480,800));
        Thread.sleep(300);
    }
    @AfterClass
    public void after(){
        webDriver.quit();
    }
}

   4.2、控制浏览器后退、前进

    在使用浏览器浏览网页时,浏览器提供了后退和前进按钮,可以方便地在浏览过的网页之间切换。WebDriver提供了back()forward()方法来模拟后退和前进按钮。

package com.hqh.test;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class TestCase007 {
    //控制浏览器前进后退
    public WebDriver webDriver;
    @BeforeClass
    public void before(){
        webDriver=new ChromeDriver();
        webDriver.manage().window().maximize();
        webDriver.get("https://www.baidu.com");
    }
    @Test
    public void testBack() throws InterruptedException {
        Thread.sleep(3000);
        webDriver.findElement(By.linkText("新闻")).click();
        Thread.sleep(3000);
        //执行浏览器后退
        webDriver.navigate().back();
        Thread.sleep(2000);
        //执行浏览器前进
        webDriver.navigate().forward();
    }
    @AfterClass
    public void afert() throws InterruptedException {
        Thread.sleep(3000);
        webDriver.quit();
    }

}

  4.2、刷新页面

    模拟手动刷新(F5)页面

    refresh()刷新页面

@Test
    public void testRefresh() throws InterruptedException {
        Thread.sleep(2000);
        webDriver.navigate().refresh();
    }

五、Selenium提供了8种定位方法

  id、name、class name、tag name、link text、partial text、xpath、css

  假如我们有一个Web页面,通过前端工具查看到一个元素的属性是这样的:

<html>
    <head>
    </head>
    <body>
        <a id="result_logo" href="/" onm ousedown="return c({'fm':'tab','tab':'logo'})">
        <form id="form" class="fm" name="f" action="/s">
            <span class="soutu-btn"></span>
            <input id="kw" class="s_ipt" name="wd" value="" maxlength="255" autocomplete="off" />
        </form>
    </body>
</html>   

  通过id定位:

driver.findElement(By.id("kw"));

  通过name定位:

driver.findElement(By.name("wd"));

  通过class name定位:

driver.findElement(By.className("s_ipt"));

  通过tag name定位:

driver.findElement(By.tagName("input"));

  通过xpath定位,xpath定位有N中写法,比如

driver.findElement(By.xpath("//*[@id='kw']"));
driver.findElement(By.xpath("//*[@class='s_ipt']"));
driver.findElement(By.xpath("//input[@name='wd']"));
driver.findElement(By.xpath("//html/body/form/input"));
driver.findElement(By.xpath("//form[@id='form']/input"));
driver.findElement(By.xpath("//inout[@id='kw' and @name='wd']"));

  通过css定位,css定位有N种写法,比如

driver.findElement(By.cssSelector("#kw"));
driver.findElement(By.cssSelector("[name=wd]"));
driver.findElement(By.cssSelector(".s_ipt"));
driver.findElement(By.cssSelector("html>body>form>inoput"));
driver.findElement(By.cssSelector("form#form>span>input"));

  接下来,我们页面上有一组文本连接。

<a class="mnav" href="http://news.baidu.com" name="tj_trnews">新闻</a>
<a class="mnav" href="http://www.hao123.com" name="tj_trhao123">hao123</a>

  通过link text定位:

driver.findElement(By.linkText("新闻"));
driver.findElement(By.linkText("hao123"));

  通过partialLink text定位

driver.findElement(By.partialLinkText("新"));
driver.findElement(By.partialLinkText("hao"));

六、WebDriver常用方法

  clear()清除文本;

  sendKeys("内容或文件路径")模拟输入和文件上传;

  click()单击元素;

  submit()提交表单,类似于回车,例如在搜索框输入关键字之后的“回车”操作;

  getSize()返回元素的尺寸;

  getText()获取元素的文本;

  getAttribute(name)获取属性值;

  isDisplayed()设置该元素是否用户可见;

package com.hqh.test;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class TestCase009 {
    public WebDriver webDriver;
    @BeforeClass
    public void before(){
        webDriver=new ChromeDriver();
        webDriver.manage().window().maximize();
        webDriver.get("https://www.baidu.com");
    }
    @Test
    public void testSubmit() throws InterruptedException {
        webDriver.findElement(By.id("kw")).sendKeys("submit");
        Thread.sleep(2000);
        webDriver.findElement(By.id("kw")).click();
        webDriver.findElement(By.id("kw")).sendKeys("selenium2");
        //submit()类似于回车键的作用
        webDriver.findElement(By.id("kw")).submit();
    }
    @Test
    public void testGet(){
        //getSize()获取百度输入框的尺寸
        WebElement size = (WebElement) webDriver.findElement(By.id("kw"));
        System.out.println(size.getSize());
        //返回百度页面底部备案信息
        WebElement text=webDriver.findElement(By.id("bottom_layer"));
        System.out.println(text.getText());
        //返回元素的属性值,可以是id,name,type或元素拥有的其他任意属性
        WebElement ty= (WebElement) webDriver.findElement(By.id("kw"));
        System.out.println(ty.getAttribute("type"));
        //返回元素是否可见
        WebElement display= (WebElement) webDriver.findElement(By.id("kw"));
        System.out.println(display.isDisplayed());


    }
    @AfterClass
    public void after() throws InterruptedException {
        Thread.sleep(2000);
        webDriver.quit();
    }
}

七、模拟鼠标操作

  在WebDriver中,通过导入Actions类模拟鼠标操作,实现与Web产品的鼠标交互操作,例如鼠标右击、双击、悬停、甚至是鼠标拖动等功能,代码如下:

  Actions action=new Actions(webDriver),先导入actions类,传入驱动参数webDriver;

  WebElement webElement=webDriver.findElement(By.id("kw")),然后定位元素;

  action.contextClick(webElement).perform(),最后调用actions类中的方法,并将定位到的元素参数传入其中,perform()方法表示执行鼠标的动作。

  右键点击webElement元素:actions.contextClick(webElement).perform();

  左键点击webElement元素:actions.Click(webElement).perform();

  点击左键不松开:actions.clickAndHold();

  鼠标左键双击webElement元素:actions.doubleClick(webElement).perform();

  鼠标悬停至webElement元素上方:

    actions.moveToElement(webElement).perform();//中间

    actions.moveToElement(webElement,x,y).perform();//指定位置

  移动鼠标位置:actions.moveToElement(x,y).perform();

  拖动元素,在源元素的位置执行点击并保持,移动到目标元素的位置,然后释放鼠标:

  Actions dragAndDrop(WebElement source,WebElement target)

  Actions dragAndDropBy(WebElement source,int x,int y);//拖动到指定位置

package com.hqh.test;

import org.checkerframework.checker.units.qual.A;
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 org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import javax.swing.*;

public class TestCase008 {
    public WebDriver webDriver;
    @BeforeClass
    public void befor(){
        webDriver=new ChromeDriver();
        webDriver.manage().window().maximize();
        webDriver.get("https://www.baidu.com");
    }
    @Test
    public void testActions() throws InterruptedException {
        Thread.sleep(2000);
        //先找到要悬停的元素
        WebElement sz=webDriver.findElement(By.name("tj_briicon"));
        //导入Actions类,将浏览器驱动driver作为参数传入
        Actions action=new Actions(webDriver);
        //悬停操作
        action.clickAndHold(sz);
        WebElement fy=webDriver.findElement(By.name("tj_fanyi"));
        action.click(fy);
        action.perform();
    }
    @AfterClass
    public void after() throws InterruptedException {
        Thread.sleep(2000);
        webDriver.quit();
    }
}

八、模拟键盘操作

  keys()类提供了键盘上几乎所有按键的方法,前面了解到,SendKeys()方法可以用来模拟键盘输入外,还可以模拟键盘的组合键。

  ctrl+a:webdriver.findElement(By.id("kw")).sendKeys(Keys.CONTROL,"a");

  ctrl+x:webdriver.findElement(By.id("kw")).sendKeys(Keys.CONTROL,"x");

  ctrl+a:webdriver.findElement(By.id("kw")).sendKeys(Keys.CONTROL,"a");

  ctrl+v:webdriver.findElement(By.id("kw")).sendKeys(Keys.CONTROL,"v");

   tab键:webdriver.findElement(By.id("kw")).sendKeys(Keys.TAB);

  回车键:webdriver.findElement(By.id("kw")).sendKeys(Keys.ENTER);

  空格键:webdriver.findElement(By.id("kw")).sendKeys(Keys.SPACE);

package com.hqh.test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;



public class TestCase010 {
    //模拟键盘组合键
    public WebDriver webDriver;
    @BeforeClass
    public void before(){
        webDriver=new ChromeDriver();
        webDriver.get("https://www.baidu.com");
        webDriver.manage().window().maximize();
    }
    @Test
    public void testKes() throws InterruptedException {
        WebElement webElement=webDriver.findElement(By.id("kw"));
        //往输入框输入内容
        webElement.sendKeys("seleniumm");
        Thread.sleep(2000);
        //删除多输入的一个m
        webElement.sendKeys(Keys.BACK_SPACE);
        Thread.sleep(2000);
        //输入空格键+“教程”
        webElement.sendKeys(Keys.SPACE);
        webElement.sendKeys("教程");
        Thread.sleep(2000);
        //ctrl+a全选输入框内容
        webElement.sendKeys(Keys.CONTROL,"a");
        Thread.sleep(2000);
        //ctrl+x剪切输入框内容
        webElement.sendKeys(Keys.CONTROL,"x");
        Thread.sleep(2000);
        //ctrl+v粘贴内容到输入款
        webElement.sendKeys(Keys.CONTROL,"v");
        Thread.sleep(2000);
        //通过回车键盘来点击操作
        webElement.sendKeys(Keys.ENTER);
        Thread.sleep(2000);
    }
    @AfterClass
    public void after() throws InterruptedException {
        Thread.sleep(2000);
        webDriver.quit();
    }
}

 九、多表单切换

  在Web应用中经常会遇到frame/iframe表单嵌套页面的应用,WebDriver只能在一个页面上对元素进行识别和定位,对于frame/iframe表单内嵌页面上的元素无法直接定位。这时候就需要:

  WebElement webElement=webDriver.findElement("frame表单元素"),定位frame表单;

  webDriver.switchTo().frame(webElement),切换到指定frame表单;

  webDriver.switchTo().defaultConter(),跳出表单。

package com.hqh.test;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class TestCase011 {
    //多表单切换
    public WebDriver webDriver;
    @BeforeClass
    public void before(){
        webDriver=new ChromeDriver();
        webDriver.manage().window().maximize();
        webDriver.get("https://www.126.com/");
    }
    @Test
    public void testA() throws InterruptedException {
        Thread.sleep(3000);
        //先定位iframe标签
        WebElement webElement=webDriver.findElement(By.xpath("//*[@id=\"loginDiv\"]/iframe"));
        //然后使用switchTo().frame()方法将当前定位的主体切换为frame/iframe表单的内嵌页面
        webDriver.switchTo().frame(webElement);
        webDriver.findElement(By.name("email")).sendKeys("11111");
        webDriver.findElement(By.name("password")).sendKeys("22222");
        webDriver.findElement(By.cssSelector("#dologin")).click();
    }
    @AfterClass
    public void after() throws InterruptedException {

    }
}

十、多窗口切换

  在页面操作过程中有时候点击某个链接会弹出新的窗口,这时就需要主机切换到新打开的窗口进行操作。

  String getWindowHandle(),返回当前窗口句柄,通过将其传递给switchTo(),进行切换窗口;

  Set<String> getWindowHandles(),返回所有窗口句柄;

  webDriver.switchTo().window(handle),切换到指定句柄的窗口;

package com.hqh.test;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.util.Set;

public class TestCase012 {
    //窗口切换
    public WebDriver webDriver;
    @BeforeClass
    public void before(){
        webDriver=new ChromeDriver();
        webDriver.manage().window().maximize();
        webDriver.get("https://www.baidu.com");
    }
    @Test
    public void testHandle1() throws InterruptedException {
        //2个窗口进行切换
        //获取当前页面的句柄
        String handl1=webDriver.getWindowHandle();
        Thread.sleep(2000);
        webDriver.findElement(By.partialLinkText("hao123")).click();
        //获取所有页面的句柄
        Set<String> handls=webDriver.getWindowHandles();
        for (String handl2:handls){
            if (handl2.equals(handl1)==false) {
                //跳转到第二个窗口
                webDriver.switchTo().window(handl2);
                Thread.sleep(3000);
                //定位第二个窗口的元素
                webDriver.findElement(By.cssSelector("[monkey=\"weather\"]")).click();
                //关闭正在打开的窗口,第2个窗口
                webDriver.close();
            }
        }
    }
    @Test
    public void testHandle2() throws InterruptedException {
        //3个及以上的窗口进行切换
        //获取当前窗口句柄
        String handle1=webDriver.getWindowHandle();
        webDriver.findElement(By.partialLinkText("hao123")).click();
        Thread.sleep(2000);
        getHandle(handle1);
        webDriver.findElement(By.linkText("央视网")).click();
        getHandle(handle1);
        webDriver.getTitle();
    }
    //创建一个切换窗口的方法,方便多窗口切换
    public void getHandle(String handle1){
        Set<String> handles=webDriver.getWindowHandles();
        System.out.println("句柄长度==="+handles.size()+",窗口切换次数 "+(handles.size()-1));
        for(String handle:handles) {
            if (handle.equals(handle1) == false) {
                webDriver.switchTo().window(handle);
            }
        }
    }
    @AfterClass
    public void after() throws InterruptedException {
        Thread.sleep(2000);
        webDriver.quit();
    }
}

十一、下拉框选择

  WebDriver提供了Select类来处理下拉框。

  WelElement welElement=webDriver.findElement(By.id("select")),先定位下拉框元素;

  Select select=new Select(welElement),然后导入Select类,并传入定位到的下拉框元素值;

  最后通过Select类中方法去获取下拉框中的值:

  select.selectByIndex(1),通过索引选择;

  select.selectByValue("zhangsan"),通过value值获取;

  select.selectByVisibleText("张三"),通过文本值获取。

package com.hqh.test;

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.ExpectedCondition;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.Sleeper;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.time.Duration;
import java.util.List;
import java.util.Set;

public class TestCase013 {
    public WebDriver webDriver;
    @BeforeClass
    public void before(){
        webDriver=new ChromeDriver();
        webDriver.manage().window().maximize();
        webDriver.navigate().to("https://www.baidu.com");
    }
    @Test
    public void test() throws InterruptedException {
        String hanlde1=webDriver.getWindowHandle();
        System.out.println("当前句柄==="+hanlde1);
        webDriver.findElement(By.linkText("hao123")).click();
        Thread.sleep(2000);
        Set<String> handles=webDriver.getWindowHandles();
        for(String handle:handles){
            if (handle.equals(hanlde1)==false){
                webDriver.switchTo().window(handle);
            }
        }
        webDriver.findElement(By.cssSelector("[monkey=\"weather\"]")).click();
        //省
        WebElement province=webDriver.findElement(By.name("province"));
        Select select1=new Select(province);
        select1.selectByValue("16");//值
        //市
        Thread.sleep(2000);
        WebElement city=webDriver.findElement(By.name("city"));
        Select select2=new Select(city);
        select2.selectByIndex(2);//序号
        //县
        Thread.sleep(2000);
        WebElement dist=webDriver.findElement(By.name("dist"));
        Select select3=new Select(dist);
        select3.selectByVisibleText("Z 资兴");//文本
        Thread.sleep(2000);
        webDriver.findElement(By.cssSelector("[class=\"select-btn\"]>div"));
    }
    @AfterClass
    public void after() throws InterruptedException {
        Thread.sleep(2000);
        webDriver.quit();
    }
}

十二、单选框和复选框

  在WebDriver中要模拟勾选单选或复选框,只需通过定位单选按钮元素并执行点击操作即可。webDriver.findElement(By.id("radio")).click()。

十三、弹出框、警告框处理

  在WebDriver中处理JavaScript所生成的alert、confirm以及prompt十分简单,具体做法是使用switch_to_alert()方法定位到alert、confirm、prompt,然后使用text、accept、dismiss、sendKeys等方法进行操作。

  getText():返回alert、confirm、prompt中的文字信息;

  accept():接受现有警告框;

  dismiss():解散现有警告框;

  sendKeys(keysToSend):发送文本至警告框;

  keysToSend:将文本发送至警告框。

package com.hqh.test;

import com.beust.ah.A;
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 org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class TestCase014 {
    public WebDriver webDriver;

    @BeforeClass
    public void before(){
        webDriver=new ChromeDriver();
        webDriver.manage().window().maximize();
        webDriver.get("https://www.baidu.com");
    }
    @Test
    public void test() throws InterruptedException {
        Thread.sleep(3000);
        WebElement sz=webDriver.findElement(By.id("s-usersetting-top"));
        Actions actions=new Actions(webDriver);
        actions.clickAndHold(sz).perform();
        WebElement ss=webDriver.findElement(By.linkText("搜索设置"));
        actions.click(ss).perform();
        Thread.sleep(2000);
        webDriver.findElement(By.id("s1_2")).click();
        webDriver.findElement(By.id("sh_1")).click();
        webDriver.findElement(By.linkText("保存设置")).click();
        //接收所有弹窗
        webDriver.switchTo().alert().accept();
    }
    @AfterClass
    public void after() throws InterruptedException {
        Thread.sleep(3000);
        webDriver.quit();
    }
}

十四、文件上传

  对于通过input标签实现的上传功能,可以将其看作是一个输入框,即通过指定路径实现上传功能。

  webDriver.findElement(By.name("file").sendKeys("D:\\1.txt"));

十五、浏览器cookie操作

  有时候我们需要验证浏览器中cookie是否正确,因为基于真实cookie的测试是无法通过白盒测试和集成测试进行的。webdriver提供了操作cookie的相关方法可以读取,添加和删除cookie信息。

package com.hqh.test;

import org.checkerframework.checker.units.qual.C;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.util.Set;

public class TestCase015 {
    //cookie获取
    public WebDriver webDriver;
    @BeforeClass
    public void before(){
        webDriver=new ChromeDriver();
        webDriver.manage().window().maximize();
        webDriver.get("https://www.baidu.com");
    }
    @Test
    public void test(){
        Cookie cookie1=new Cookie("name","key");
        webDriver.manage().addCookie(cookie1);
        Set<Cookie> coo=webDriver.manage().getCookies();
        System.out.println("获取的cookie"+coo);
        //删除所有cookie
        webDriver.manage().deleteAllCookies();
    }
    @AfterClass
    public void after() throws InterruptedException {
        Thread.sleep(2000);
        webDriver.quit();
    }
}

十六、调用JavaScript代码

  某些时候,我们可能通过getText()的方法获取标签的文本值并不会生效,但是我们可以通过写js语句来解决大部分问题。

  假设我们需要获取某个标签的文本值,需要executeScript(String script,Object..args)方法,其中script代表js语句,args表示传给js语句的值:

  WebElement bq=webDriver.findElementById("bq"),我们先定位到该标签;

  ((JavascriptExecutor)webDriver).executeScript("return arguments[0].innerText;",bq),然后通过executScript方法获取文本值。

  同理,窗口的滚动条同样需要调用js语句。  

  ((JavascriptExecutor)webDriver).executeScript("window.scrollTo(100, 450);");

package com.hqh.test;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import java.util.Set;

public class TestCase016 {
    public WebDriver webDriver;
    @BeforeClass
    public void before(){
        webDriver=new ChromeDriver();
        webDriver.manage().window().maximize();
        webDriver.get("https://www.baidu.com");
    }
    @Test
    public void test() throws InterruptedException {
        //进行百度搜索
        webDriver.findElement(By.id("kw")).sendKeys("webdriver api");
        webDriver.findElement(By.id("su")).click();
        Thread.sleep(2000);
        //通过调用executeScript方法来执行JavaScript代码
        ((JavascriptExecutor)webDriver).executeScript("window.scrollTo(100, 450);");
        Thread.sleep(2000);
    }
    @AfterClass
    public void after() throws InterruptedException {
        Thread.sleep(2000);
        webDriver.quit();
    }
}

 十七、获取窗口截图

  WebDriver提供了截图函数getScreenshotAs()来截图函数。

package com.hqh.test;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.apache.commons.io.FileUtils;


import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class TestCase017 {
    public WebDriver webDriver;
    @BeforeClass
    public void before(){
        webDriver=new ChromeDriver();
        webDriver.manage().window().maximize();
        webDriver.get("http://www.baidu.com");
    }
    @Test
    public void testTakeScreen1() throws IOException, InterruptedException {
        //taskscreenshot只能截取自动化运行的浏览器窗口内,不会截取到浏览器的操作按钮和系统的任务栏区域
        webDriver.findElement(By.id("kw")).sendKeys("截图");
        webDriver.findElement(By.id("su")).click();
        File screenshot=((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);
        Thread.sleep(4000);
        FileUtils.copyFile(screenshot,new File("F:\\screenshort\\通过takesScreenshot截图.png"));
    }
    @Test
    public void testRobt() throws InterruptedException {
        //
        webDriver.findElement(By.id("kw")).sendKeys("截图");
        webDriver.findElement(By.id("su")).click();
        Thread.sleep(5000);
        BufferedImage image=null;
        try {
            image=new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
            ImageIO.write(image,"jpg",new File("F:\\screenshort\\通过Root截图.png"));
        } catch (AWTException | IOException e) {
            throw new RuntimeException(e);
        }
    }
    @AfterClass
    public void after() throws InterruptedException {
        Thread.sleep(2000);
        webDriver.quit();
    }
}

 

标签:webDriver,Java,selenium,自动化,Selenium,findElement,org,import,public
From: https://www.cnblogs.com/hqh2021/p/17097924.html

相关文章