selenium进阶

一、切换

  1.window窗口切换

@Test
public void test3(){
    System.out.println(driver.getWindowHandle());
    String oldHandle = driver.getWindowHandle();
    //使用javaScript打开一个新标签页
    JavascriptExecutor oJavaScriptExecute =(JavascriptExecutor)driver;
    oJavaScriptExecute.executeScript("window.open();");
    System.out.println("there are "+driver.getWindowHandles().size()+"windows");
    for(String handle:driver.getWindowHandles()){
        System.out.println(handle);
        if (! handle.equals(oldHandle)){
            //新标签页打开http://www.testerhome.com
            driver.switchTo().window(handle);
            driver.get("http://www.testerhome.com");
            break;
        }
    }
    driver.close();
    //切换回第一个的标签页,否则handle依然停留在已关闭的标签页。针对不存在的标签操作,会报NoSuchWindowException的异常。如图2
    driver.switchTo().window(oldHandle);
}

结果:

不切换回原有标签页


  2.切换到对话框

    对话框的辨别https://blog.csdn.net/huilan_same/article/details/52298460

    alert为浏览器弹出框,一般是用来确认某些操作、输入简单的text或用户名、密码等,根据浏览器的不同,弹出框的样式也不一样。这种弹窗是无法取到元素的,即alert是不属于网页DOM树的。如从左到右,依次为alertconfirmprompt

  

  div伪装对话框,是通过网页元素伪装成对话框,这种对话框内容较多,不会随浏览器而改变,在网页中能获取到元素。如下图

  driver.switchTo().alert().accept(); //等同于点击确认或OK
  driver.switchTo().alert().dismiss(); //等同于点击取消或cancel
  driver.switchTo().alert().getText(); //对有信息显示的alert框,获取alert文本内容
  driver.switchTo().alert().sendKeys("Hello world"); //对有提交需求的文本框发送文本

   示例1:switch_to.alert  accept text

  测试链接: http://sahitest.com/demo/alertTest.htm

 

@Test

public void test4() throws InterruptedException{
    driver.get("http://sahitest.com/demo/alertTest.htm");
    driver.findElement(By.xpath("//input[@name='b1']")).click();
    Thread.sleep(2000);
    driver.switchTo().alert().accept();
    Thread.sleep(2000);
    driver.findElement(By.xpath("//input[@name='b2']")).click();
    Thread.sleep(2000);
    System.out.println(driver.switchTo().alert().getText());
    Thread.sleep(2000);
    driver.switchTo().alert().accept();
    driver.findElement(By.xpath("//input[@name='b3']")).click();
    Thread.sleep(2000);
    driver.switchTo().alert().accept();}

     示例2:Alert(driver),dismiss

    测试链接:http://sahitest.com/demo/confirmTest.htm

@Test

public void test4() throws InterruptedException{
    driver.get("http://sahitest.com/demo/confirmTest.htm");
    driver.findElement(By.xpath("//input[@name='b1']")).click();
    System.out.println(driver.switchTo().alert().getText());
    Thread.sleep(1000);
    driver.switchTo().alert().dismiss();
}

    示例3: switch_to.alert,send_keys(keysToSend) 
    测试链接:http://sahitest.com/demo/promptTest.htm
@Test
public void test4() throws InterruptedException{
    driver.get("http://sahitest.com/demo/promptTest.htm");
    driver.findElement(By.xpath("//input[@name='b1']")).click();
    driver.switchTo().alert().sendKeys("Hello world");
    Thread.sleep(1000);
    driver.switchTo().alert().accept();}
问题:汽车之家的弹窗,是什么类型

  3.切换到iFrame/Frame

   web应用中经常会遇到frame/iframe表单嵌套页面的应用,web driver只能在一个页面对元素进行识别与定位,此时需要通过switch_to.frame()方法将当前定位的主体切换为frame/iframe表单的内嵌页面中。driver.switchTo().defaultContent()跳回最外层的页面。driver.switchTo().parentFrame();返回上一级页面

 

@Test

public void frame() throws InterruptedException{
    driver.get("http://sahitest.com/demo/framesTest.htm");
    driver.switchTo().frame("top");  //根据唯一的标示,如id,name进入frame
    WebElement shadow=driver.findElement(By.xpath("//a[@href='shadowRoot.html']"));
    System.out.println(shadow.getText());
    driver.switchTo().parentFrame(); //返回上一层
    //driver.switchTo().frame("/html/frameset/frame[2]")
    WebElement show2 = driver.findElement(By.xpath("/html/frameset/frame[2]")); //先找到元素,再进入表单
    driver.switchTo().frame(show2);
    System.out.println(driver.findElement(By.xpath("//a[@href="selectTest.htm"]")).getText());
    driver.switchTo().defaultContent();} //返回最外层
 

二、cookie处理

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

  1.获取cookie

    1.1获取所有的cookie

@Test
public void cookieTest() throws InterruptedException{
    driver.get("http://www.baidu.com");
    System.out.println(driver.manage().getCookies());
}
//获取的cookie为一个字典

    1.2 对cookie进行迭代

for(Cookie cookie:driver.manage().getCookies()){
    System.out.print("name:"+cookie.getName()+"	");
    System.out.print("Domain:"+cookie.getDomain()+"	");
    System.out.print("Expiry:"+cookie.getExpiry()+"	");
    System.out.print("value:"+cookie.getValue()+"	");
    System.out.println("path:"+cookie.getPath());

}

 

    1.3 根据name获取某个cookie

 @Test
 public void cookieTest() throws InterruptedException{
     driver.get("http://www.autohome.com");
     Cookie cookie = driver.manage().getCookieNamed("area");
     System.out.println(cookie);
 }


  2.添加cookie

    Cookie cookie = new Cookie("","","",null)

    driver.manage().addCookie(cookie)

@Test
 public void cookieTest() throws InterruptedException{
     driver.get("http://www.autohome.com");
     //获取异常,打印日志
   try{
         driver.switchTo().alert().dismiss();
     } catch (Exception e){
       Reporter.log("No alert displayed",true);
         }
     //添加cookie
   Cookie addcookie = new Cookie("zhangsan","lisi");
     driver.manage().addCookie(addcookie);
     for(Cookie cookie:driver.manage().getCookies()){
         System.out.print("name:"+cookie.getName()+"	");
         System.out.println("value:"+cookie.getValue()+"	");
     }
 }


  2.删除cookie

     2.1 删除单个cookie

 @Test
    public void cookieTest() throws InterruptedException{
        driver.get("http://www.autohome.com");
        Cookie cookie = driver.manage().getCookieNamed("area");
        System.out.println(cookie.getName()+"	"+cookie.getValue());
        driver.manage().deleteCookie(cookie);
      for(Cookie icookie:driver.manage().getCookies()){
            System.out.println(icookie.getName()+"	"+icookie.getValue());
        }
    //也可以直接按照name删除cookie
     driver.manage().deleteCookieNamed("ahpau");
    }

    2.2 删除全部cookie

  

 public void cookieTest() throws InterruptedException{
        driver.get("http://www.autohome.com");
        driver.manage().deleteAllCookies();
        System.out.println(driver.manage().getCookies());
    }


三、执行JavaScript

  document.getElementById("ibm-masthead").style.display='none';

  arguments[0].setAttribute('style',arguments[1]);

  arguments[0].scrollIntoView(true);

  document.documentElement.scrollTop=500

  document.getElementById(i).style.display ='block';   //获取当前页面里面id为i的标签,改变该标签的样式,使其满框显示。

  document.getElementById(i).style.display ='none';   //获取当前页面里面id为i的标签,改变该标签的样式,使其不显示。

  document.getElementById(i).style.display ='inline';   //获取当前页面里面id为i的标签,改变该标签的样式,使其显示。

@Test
public void testJS(){
    driver.get("http://www.baidu.com");
    WebElement img = driver.findElement(By.xpath("//*[@id="cp
    JavascriptExecutor js = (JavascriptExecutor)driver;
    js.executeScript("arguments[0].scrollIntoView(true);",img);}

  返回返回值  

  return arguments[0].getText();

  return documents.readyState;

  return window.innerWidth

  return document.documentElement.scrollTop

@Test
public void testJS(){
    driver.get("http://www.baidu.com");
    JavascriptExecutor js = (JavascriptExecutor)driver;
    Object top=js.executeScript("return document.documentElement.scrollTop") ;
    System.out.println((long)top);
}


执行JavaScript脚本http://lijingshou.iteye.com/blog/2018929

  1.初始化

    JavascriptExecutor js = (JavascriptExecutor)driver;

  2.直接传入Javascript代码

    js.executeScript("window.document.getElementById('su').click()";

  3.传入WebElement执行js脚本

   //百度首页点击百度一下

   WebElement element = driver.findElement(By.id("su"));  

   js.executeScript("arguments[0].click();", element);  

   //

   js.executeScript("arguments[0].onclick=function(){alert('This is my alert!');}", element)

   //指定的DIV就新增(修改)了 style {height: 1000px}的属性

   WebElement div = driver.findElemnt(By.id("myDiv"));  

   jse.executeScript("arguments[0].setAttribute('style', arguments[1])", div, "height: 1000px");  

四、actions

@Test
public void cookieTest() throws InterruptedException{
    driver.get("http://www.baidu.com");
    Actions action = new Actions(driver);
    action.doubleClick(driver.findElement(By.xpath("//a[@name='tj_trmap']")));
}

五、网页截图

  需要jar包http://commons.apache.org/proper/commons-io/download_io.cgi

  下载Binaries文件

  如果下载commons-io-*.tar.gz,需要先解压tar -zxvf commons-io-*.tar.gz

  导入jar包

  file-project structure-添加-JARs and directories,添加解压后的目录

@Test
 public void screenshotTest() throws IOException {
     driver.get("http://www.baidu.com");
     String screenpath = System.getProperty("user.dir")+"/src/screenshot/";
     System.out.println(screenpath);
     SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmmss");
     String time = dateFormat.format(Calendar.getInstance().getTime());
     File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
     FileUtils.copyFile(srcFile,new File(screenpath,time+".png"));
     //FileUtils.copyFile(srcFile,new File(screenpath,time+".png"));
     
 }

  结果:

  

六、上传下载

  没讲

https://seleniumhq.github.io/selenium/docs/api/java/overview-summary.html

七、显式等待、隐式等待

  等待的方式有三种:显示等待、隐私等待、线程休眠

  1. 显示等待 针对于某个元素的明确等待

  WebDriverWait wait = new WebDriverWait(driver,15);

  wait.unitl(ExpectedConditions.visibilityOfElementLocated(By.id("kw")));

@Test
   public void waitfor(){
       driver.get("http://www.baidu.com");
       driver.findElement(By.id("kw")).sendKeys("selenium");
       driver.findElement(By.id("su")).click();
       //显式等待,每500毫秒检查元素是否存在;超过30秒没有发现,就报异常
       By result = By.cssSelector("span.nums_text"); 
       WebDriverWait wait = new WebDriverWait(driver,30);
       wait.until(ExpectedConditions.visibilityOfElementLocated(result));
       String actureResult = driver.findElement(result).getText();
       String expectResult="百度为您找到相关结果";
       Assert.assertTrue(actureResult.contains(expectResult));       
   }

  2. 隐式等待 通过 一定的时长等待页面上某元素加载完成,默认设置为0。可设置为全局等待

   webDriver driver; 

   driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);

  3. 线程休眠

    Thread.sleep(5000)

八、数据驱动

  1. 根据二维数组输入内容

package testcase;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.*;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;

public class dataProvider {
    @DataProvider
    public static Object[][] getTestData(){
        Object[][] o = new Object[2][1];
        o[0][0] = "selenium";
        o[1][0] = "appium";
        return o;
    }
    @Test(dataProvider = "getTestData")
    public void seartchTest(String searchKey) throws IOException {
        String chromePath = System.getProperty("user.dir") + "/src/main/java/drivers/chromedriver";
        String screenpath = System.getProperty("user.dir")+ "/src/screenshot/";
        WebDriver driver ;
        System.setProperty("webdriver.chrome.driver", chromePath);
        driver=new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
        driver.get("http://www.baidu.com");

        driver.findElement(By.id("kw")).sendKeys(searchKey);
        driver.findElement(By.id("su")).click();
        By result = By.cssSelector("span.nums_text");
        Assert.assertTrue(driver.findElement(result).isDisplayed());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String time = dateFormat.format(Calendar.getInstance().getTime());
        File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(srcFile,new File(screenpath,time+".png"));
        driver.close();
    }
}

  2. 从excel文件中导入数组

//需要把脚本转化为excel驱动的模式
import java.io.File;
import java.io.FileInputStream;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
public class SeleniumWork1 {
    public static void main(String[] args){
        try{
            File src = new File("/Users/chenshanju/Desktop/testerhome/java.xlsx");
            FileInputStream fis = new FileInputStream(src);
            @SuppressWarnings("resource")
            XSSFWorkbook wb = new XSSFWorkbook(fis);
            XSSFSheet sh1 = wb.getSheetAt(0);
            System.out.println(sh1.getRow(0).getCell(0).getStringCellValue());
            System.out.println(sh1.getRow(3).getCell(1).getStringCellValue());
            int rowInExcel = sh1.getPhysicalNumberOfRows();
            int columnInExcel = sh1.getRow(0).getPhysicalNumberOfCells();
            System.out.println(rowInExcel+"	"+columnInExcel);
            String[][] obj = new String[rowInExcel][columnInExcel];
            for(int row=0;row <rowInExcel;row++){
                for(int col=0;col<columnInExcel;col++){
                    obj[row][col]=sh1.getRow(row).getCell(col).getStringCellValue();
                    System.out.println(obj[row][col]);
                }
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
}







原文地址:https://www.cnblogs.com/csj2018/p/9217299.html