ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

WebDriver API实例详解

2020-02-04 15:55:05  阅读:253  来源: 互联网

标签:WebDriver java driver WebElement Assert API findElement select 详解


一、访问网页地址:get(url)

  Java代码

String url="http://www.baidu.com";
driver.get(url);

 

二、刷新当前网页:navigate().refresh()

  java代码

String url="http://www.baidu.com";
driver.get(url);
driver.findElement(By.id("kw")).sendKeys("123123123");
Thread.sleep(2000);
//刷新浏览器当前网页
driver.navigate().refresh();

 

三、获取页面title属性:getTitle()

  java代码

String url="http://www.baidu.com";
driver.get(url);
//获取页面的title属性
String title=driver.getTitle();
System.out.println(title);
//断言页面上的title值是不是  百度一下,你就知道
Assert.assertEquals("百度一下,你就知道",title);

 

四、获取页面源代码:getPageSource()

  java代码

String url="http://www.baidu.com";
driver.get(url);
//获取页面源代码
String pagesource=driver.getPageSource();
System.out.println(pagesource);
//断言源代码中是否包含“百度一下,你就知道”
Assert.assertTrue(pagesource.contains("百度一下,你就知道"));

 

五、获取当前页面的URL地址:getCurrentUrl()

  Java代码

String url="http://www.baidu.com/";
driver.get(url);
//获取URL地址
String getUrl=driver.getCurrentUrl();
//断言
Assert.assertEquals("https://www.baidu.com/", getUrl);

 

六、清空文本框:clear()

  java代码  

WebElement baiduKw=driver.findElement(By.id("kw"));

baiduKw.sendkeys("selenium");

baiduKw.clear();

 

七、文本框输入文本:sendkeys()

  java代码  

WebElement baiduKw=driver.findElement(By.id("kw"));
baiduKw.sendKeys("selenium");

 

八、单击元素:click()

  java代码  

WebElement baiduKW=driver.findElement(By.cssSelector("#su"));
baiduKW.click();

 

九、双击元素

  HTML源码

<input id='inputBox' type="button" style="width:100px;height:50px;" ondblclick="javascript:this.style.background='red'">请双击按钮</>

  Java代码

WebElement inputB=driver.findElement(By.xpath("//input[@id='inputBox']"));
//声明Action对象
Actions ac=new Actions(driver);
//使用doubleClick方法在定位的元素中进行鼠标的双击操作
ac.doubleClick(inputB).build().perform();

 

十、获取文本:getText()

  java代码  

//定位百度首页右上角的 新闻
WebElement XW=driver.findElement(By.xpath("//*[@name='tj_trnews']"));
//获取文本
String Text1=XW.getText();
//校验文本内容
Assert.assertEquals(Text1,"新闻");

 

十一、判断元素是否展示:isDisplayed()

  java代码  

WebElement baiduSu=driver.findElement(By.xpath("//*[@id='su']"));
//获取 百度一下 按钮是否显示
boolean Su=baiduSu.isDisplayed();
//校验结果
Assert.assertTrue(Su);

 

十二、判断元素是否激活:isEnabled()

  HTML源码:

<td>Button按钮</td>

  <td class="SubButton">
      <div id='button'>

       <input name="buttonSub" type='button' class='button' value='Submit' disabled="disabled"/>

     </div>

   </td>

  Java代码:  

//定位元素,判断是否激活
boolean submit=driver.findElement(By.xpath("//*[@name='buttonhtml']")).isEnabled();
//校验结果
Assert.assertTrue(submit);

 

十三、判断选择框是否被选中:isSelected()

  HTML源码:

<td>RadioBox单选框</td>
    <td class="widgetStyle">
     <div id='radio'>
      <input type='radio' name="identity" class='a'/><label>a</label></br>
      <input type='radio' name="identity" class='b'/><label>b</label></br>
      <input type='radio' name="identity" class='c'/><label>c</label></br>
      <input type='radio' name="identity" class='d'/><label>d</label>
     </div>
  </td>

 

  java代码:  

//定位a单选框
WebElement a=driver.findElement(By.xpath("//*[@id='radio']/input[1]"));
//点击单选框
a.click();
//获取单选框是否被选中
boolean b1=a.isSelected();
//校验结果
Assert.assertTrue(b1);

 

十四、select下拉框处理

  1. selectByIndex() 根据索引来选取,从0开始

  2. selectByValue() 根据属性value的属性值来选取

  3. selectByVisibleText()根据标签之间的Text值,也就是页面显示的

  注意:导入的包要正确不然会报错。   import org.openqa.selenium.support.ui.Select;

    单选下拉列表: 

  HTML源码

<tr>
    <td>Select下拉列表</td>
          <div id='select'>
                <select id="selected">
                    <option value ="a">huawei</option>
                    <option value ="b">oppo</option>
                    <option value="c">vivo</option>
                    <option value="d">xiaomi</option>
                    <option value="e">hongmi</option>
                    <option value="f">meizu</option>
                </select>
          </div>                                
    </tr>

  Java代码

package cn.WebDriverAPI;
//单选下拉框
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;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;


public class downList {
    public WebDriver driver;
    @Test
    public void test(){
        System.setProperty("webdriver.chrome.driver", "E://chromedriver.exe");
        driver=new ChromeDriver();
        driver.get("file:///C:/Users/Administrator.USER-20180602NR/Desktop/selenium.html");
        WebElement s=driver.findElement(By.xpath("//select[@id='selected']"));
        Select select=new Select(s);
        //isMultiple表示此下拉框列表是否允许多选,返回结果应为false
        Assert.assertFalse(select.isMultiple());
        //输出isMultiple方法返回的值
        Boolean b=select.isMultiple();
        System.out.println("b:"+b);
        //通过选项的文字进行选中
        select.selectByVisibleText("oppo");
        //获取当前被选中的下拉列表选项文本并赋给text1
        String text1=select.getFirstSelectedOption().getText();
        //断言
        Assert.assertEquals("oppo", text1);
        System.out.println("文本"+text1);
        //使用下拉列表选项的value属性值进行选中操作
        select.selectByValue("c");
        //获取当前被选中的下拉列表选项文本并赋给text2
        String text2=select.getFirstSelectedOption().getText();
        //断言
        Assert.assertEquals("vivo",text2);
        //通过索引选择,从0开始
        select.selectByIndex(3);
        String text3=select.getFirstSelectedOption().getText();
        Assert.assertEquals("xiaomi",text3);
    }
    @AfterMethod
    public void afterMethod(){
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        driver.quit();
    }

}

 

十五、多选的下拉列表:

  HTML源码

<select id="selects" multiple="multiple">
            <option value="java">java</option>
            <option value="c">c</option>
            <option value="c++">c++</option>
            <option value="VB">VB</option>
            <option value="php">php</option>
            <option value="python">python</option>
            <option value="ruby">ruby</option>
        </select>

  java代码

        WebElement mus=driver.findElement(By.id("selects"));
        Select select=new Select(mus);
        //断言下拉列表是否支持多选,支持多选isMultiple方法则返回True
        Assert.assertTrue(select.isMultiple());
        //通过索引选择
        select.selectByIndex(0);
        //获取当前被选中选项的文字
        String text=select.getFirstSelectedOption().getText();
        //断言获取到的文字是否符合实际
        Assert.assertEquals("java",text);
        //通过value值选择
        select.selectByValue("c");
        //通过选项文字选择
        select.selectByVisibleText("VB");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //取消所有选项的选中状态
        select.deselectAll();
        

 

十六、操作radio单选框

  HTML源码

<div id='radio'>
     <input type='radio' name="fruit" class='yi'/><label>yi</label></br>
     <input type='radio' name="fruit" class='er'/><label>er</label></br>
     <input type='radio' name="fruit" class='san'/><label>san</label></br>
     <input type='radio' name="fruit" class='si'/><label>si</label></br>
     <input type='radio' name="fruit" class='wu'/><label>wu</label>
</div>

 

  java代码

     //查找class属性为yi的按钮
        WebElement yi=driver.findElement(By.className("yi"));
        //判断此按钮是否为选中状态,如果不是则调用click方法进行点击
        if(!yi.isSelected())
            yi.click();
        //断言class属性值为yi的按钮处于被选中状态。此时isSelected方法返回值应为True
        Assert.assertTrue(yi.isSelected());
        //输出isSelected方法返回值
        Boolean b=yi.isSelected();
        System.out.println("b:"+b);

 

十七、操作CheckBox复选框

  HTML源码

<div id='checkboxs'>
      <input type="checkbox" name="checkbox2"/><label>liu</label></br>
      <input type="checkbox" name="checkbox3"/><label>qi</label></br>
      <input type="checkbox" name="checkbox4"/><label>ba</label></br>    
      <input type="checkbox" name="checkbox5"/><label>jiu</label></br>
      <input type="checkbox" name="checkbox6"/><label>shi</label>            
 </div>

  java代码

//查找name值为checkbox2的复选框
        WebElement liu=driver.findElement(By.xpath("//input[@name='checkbox2']"));
        //判断如果此复选框还未被选中,则调用click方法单击选中
        if(!liu.isSelected())
            liu.click();
        //断言此复选框被成功选中
        Assert.assertTrue(liu.isSelected());
        //停2秒看效果
        Thread.sleep(2000);
        //判断如果此复选框处于被选中状态则再次调用click方法进行单击取消复选框的选中状态
        if(liu.isSelected())
            liu.click();
        //断言此复选框处于非选中状态
        Assert.assertFalse(liu.isSelected());
        Thread.sleep(2000);    
        //再次选中name值为checkbox2的复选框
        liu.click();
        Thread.sleep(2000);    
        //查找所有type属性值为 checkBox的复选框,并存在list容器内
        List<WebElement> checkboxs= driver.findElements(By.xpath("//input[@type='checkbox']"));
        //遍历容器中所有元素,判断每个复选框处于非选中状态,非选中状态的则调用click方法单击
        //因为name值为checkbox2的复选框在上一步时已被选中所有在for循环中不会再被点击
        for(WebElement checkbox:checkboxs){
            System.out.println(checkbox.isSelected());
            Thread.sleep(1000);
            if(!checkbox.isSelected())
                checkbox.click();
        }

 

 

、浏览器多窗口处理

  HTML源码

<div id='open'>
     <a href="selenium.html" class='open' target='bank'>Open new window打开新窗口</a><br>
</div>

  java代码

//定位点击元素,打开新的窗口
driver.findElement(By.className("open")).click();
//获取当前页面句柄
String handle=driver.getWindowHandle();
//获取所有页面句柄,并循环判断不是当前的句柄就做选取switchTo()
for(String handles:driver.getWindowHandles()){
    if(handles.equals(handle))
      continue;//跳过本次循环,不执行下面的命令直接进行下一次循环
      //break; //结束全部for循环
    driver.switchTo().window(handles);
}
//在新打开的页面中进行操作
driver.findElement(By.id("input")).sendKeys("新页面");
//关闭新页面
driver.close();
//选择原来的句柄,切到原来的界面
driver.switchTo().window(handle);
//在原来的界面进行操作
driver.findElement(By.id("input")).sendKeys("旧页面");

  

、alert弹窗

        HTML源码:

<input id='test' type='button' onclick="alert('这是一个alert弹框');" value='单击此按钮,弹出alert弹窗'>

  java代码:  

//定位Alert弹窗
WebElement At=driver.findElement(By.id("test"));
//点击alert按钮
At.click();
//选择alert弹窗
Alert alert=driver.switchTo().alert();
//获取alert弹窗中的文本内容
String text=alert.getText();
//校验alert弹窗中的文本
Assert.assertEquals(text,"这是一个alert弹框");
//点击alert弹窗中的确定按钮
alert.accept();

 

、Confirm弹窗

  HTML源码:

<input id='testcf' type='button' onclick="confirm('这是一个confirm弹框');" value='单击此按钮,弹出confirm弹窗'></input>

  java代码:

//定位confirm按钮
WebElement Cf=driver.findElement(By.xpath("//*[@id='testcf']"));
Cf.click();
//选取alert弹窗
Alert confirm=driver.switchTo().alert();
//点击confirm弹窗上的确定按钮
confirm.accept();
//点击confirm弹窗上面的取消按钮
//confirm.dismiss();

 

、prompt弹窗

  HTML源码

<input id='testpt' type='button' onclick="prompt('这是一个prompt弹框');" value='单击此按钮,弹出prompt弹窗'></input>

  Java代码

//定位prompt按钮
WebElement Cf=driver.findElement(By.xpath("//*[@id='testpt']"));
Cf.click();
//选取alert弹窗
Alert prompt=driver.switchTo().alert();
//在prompt弹窗的输入框中输入文字
prompt.sendKeys("在prompt弹窗中的输入框中输入123za。。。");
Thread.sleep(3000);
//点击prompt弹窗中的确定按钮
prompt.accept();
//点击Prompt弹窗中的取消按钮
//prompt.dismiss();

 

、iFrame

  HTML源码

<html>
<meta http-equiv=Content-Type content="text/html;charset=utf-8">
<meta http-equiv=X-UA-Compatible content="IE=edge,chrome=1">
<meta content=always name=referrer>
   <head>
     <title>selenium</title>
   </head>
 <body>
    <input id='test' type='button' onclick="alert('这是一个alert弹框');" value='单击此按钮,弹出alert弹窗'></input>
    <input id='testcf' type='button' onclick="confirm('这是一个confirm弹框');" value='单击此按钮,弹出confirm弹窗'></input>
    <input id='testpt' type='button' onclick="prompt('这是一个prompt弹框');" value='单击此按钮,弹出prompt弹窗'></input>
    <br>
     <td>Input输入框</td>
          <div id='ifra'><input type="text" id="input"/></div>                                        
   
 </body>
 <br>
    <td>Iframe框架</td>
        <iframe width=700 height=150 name=iFrame frameborder=0 src="selenium.html"></iframe>        
</html>

  java代码  

//用iframe标签的id或者name定位iframe,并将控制权交给iframe
driver.switchTo().frame("iFrame");
//定位iframe里面的输入框并输入123
driver.findElement(By.id("input")).sendKeys("123");
//控制权交回原来的界面
driver.switchTo().defaultContent();
//在外面的输入框中输入123
driver.findElement(By.id("input")).sendKeys("123");

 当iframe没有id和name可用时可以使用index、WebElement方法(还没弄明白index方法暂时不写出来了)

  HTML源码

  java代码

WebElement e = driver.findElement(By.xpath("//div[@id='loginDiv']/iframe[@frameborder='0']"));   
driver.switchTo().frame(e);

 

标签:WebDriver,java,driver,WebElement,Assert,API,findElement,select,详解
来源: https://www.cnblogs.com/puhongjun/p/12255911.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有