码迷,mamicode.com
首页 > Windows程序 > 详细

Selenium Web 自动化 - Selenium常用API

时间:2016-08-02 21:07:58      阅读:877      评论:0      收藏:0      [点我收藏+]

标签:

Selenium Web 自动化 - Selenium常用API

2016-08-01

1 WebElement相关方法
2 iFrame的处理
3 操作下拉选择框
4 处理Alert
5 处理浏览器弹出的新窗口
6 执行JS脚本
7 等待元素加载
8 模拟键盘操作
9 设置浏览器窗口大小
10 上传文件
11 Selenium处理HTML5

1 WebElement相关方法

Method   Summary
void clear() If   this element is a text entry element, this will clear the value.
void click() Click   this element.
WebElement findElement(By by) Find   the first WebElement  using the given method.
 java.util.List<WebElement> findElement(By   by) Find   all elements within the current context using the given mechanism.
 java.lang.String getAttribute(java.lang.String   name) Get   the value of a the given attribute of the element.
 java.lang.String getCssValue(java.lang.String.propertyName) Get   the value of a given CSS property.
Point GetLocation() Where   on the page is the top left-hand corner of the rendered element?
 Dimension getSize() What   is the width and height of the rendered element?
 java.lang.String getTagName()  Get   the tag name of this element.
 java.lang.String getText()  Get   the visible (i.e. not hidden by CSS) innerText of this element, including
sub-elements, without any leading or trailing whitespace.
 boolean isDisplayed() Is   this element displayed or not? This method avoids the problem of having to   parse an element‘s "style" attribute.
 boolean isEnabled() Is the element currently enabled or not? This will generally return true for everything but disabled input elements.
 boolean isSelected() Determine   whether or not this element is selected or not.
 void sendKeys(java.lang.CharSequence...   keysToSend) Use   this method to simulate typing into an element, which may set its value.
 void submit() If   this current element is a form, or an element within a form, then this will   be submitted to the remote server.

2 iFrame的处理

driver.switchTo().frame(“city_set_ifr”); //传入的是iframe的ID
dr.switchTo().defaultContent(); //如果要返回到以前的默认content

3 操作下拉选择框

技术分享
package seleniumAPIDemo;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class SelectDemo {

    public static void main(String[] args) throws InterruptedException {
        WebDriver driver = new FirefoxDriver();
        iframeAndSelectTest(driver);
        driver.quit();
    }

    private static void iframeAndSelectTest(WebDriver driver)
            throws InterruptedException {
        driver.get("http://www.2345.com/");
        
        //浏览器最大化
        driver.manage().window().maximize();
        //点击切换按钮
        driver.findElement(By.id("J_city_switch")).click();
        //进入天气城市选择iframe
        driver.switchTo().frame("city_set_ifr");        
        Thread.sleep(2000);
        
        //然后在进行选择城市
        //定位 省下拉框                                                                          
        Select province = new Select(driver.findElement(By.id("province")));
        province.selectByValue("20");
        Thread.sleep(2000);
    
        //定位 城市下拉框
        Select city = new Select(driver.findElement(By.id("chengs")));
        city.selectByIndex(0);
        Thread.sleep(2000);
        
        //定位区
        Select region = new Select(driver.findElement(By.id("cityqx")));
        region.selectByVisibleText("X 新密");
        Thread.sleep(2000);
        
        //点击定制按钮
        driver.findElement(By.id("buttonsdm")).click();
        Thread.sleep(2000);
        //返回默认的content
        driver.switchTo().defaultContent();
    }
}
View Code

4 处理Alert

技术分享
    private static void alertTest(WebDriver driver) throws InterruptedException {
        
        driver.get("http://www.w3school.com.cn/tiy/t.asp?f=hdom_alert");
        //浏览器最大化
        driver.manage().window().maximize();
        //进入frame
        driver.switchTo().frame("i");
        //找到按钮并点击按钮
        driver.findElement(By.xpath("//*[@value=‘显示消息框‘]")).click();
        Thread.sleep(2000);
        //获取Alert
        Alert a = driver.switchTo().alert();
        //打印出文本内容
        System.out.println(a.getText());
        //点击确定
        Thread.sleep(2000);
        
        a.accept();
         // 如果alert上有取消按钮,可以使用a.dismiss()代码
    }
View Code

5 处理浏览器弹出的新窗口

技术分享
    private static void MutiWindowTest(WebDriver driver)
            throws InterruptedException {
        WebDriver newWindow = null ;
        driver.get("http://www.hao123.com/");
        //浏览器最大化
        driver.manage().window().maximize();
        //获取当前页面句柄
        String current_handles = driver.getWindowHandle();
        //点击 百度链接
        driver.findElement(By.xpath("//*[@data-title=‘百度‘]")).click();
        //接下来会有新的窗口打开,获取所有窗口句柄
        Set<String> all_handles = driver.getWindowHandles();
        //循环判断,把当前句柄从所有句柄中移除,剩下的就是你想要的新窗口
        Iterator<String> it = all_handles.iterator();
        while(it.hasNext()){
        if(current_handles == it.next()) continue;
        //跳入新窗口,并获得新窗口的driver - newWindow
         newWindow = driver.switchTo().window(it.next());
        }
        //接下来在新页面进行操作,也就是百度首页,我们输入一个java关键字进行搜索
        Thread.sleep(5000);
        WebElement baidu_keyowrd = newWindow.findElement(By.id("kw"));
        baidu_keyowrd.sendKeys("java");
        Thread.sleep(1000);
        //关闭当前窗口,主要使用close而不是quite,
        newWindow.close();
        driver.switchTo().window(current_handles);
        System.out.println(driver.getCurrentUrl());
    }
View Code

6 执行JS脚本

有时候我们需要JS脚本来辅助我们进行测试,比如我们用JS赋值或者用js执行点击操作等。执行JS脚本比较适用某些元素不易点击的情况下使用,比如网页内容太长,当前窗口太长,想要点击那些不在当前窗口可以看到元素可以用此方法。 

技术分享
    private static void runJSTest1(WebDriver driver) throws InterruptedException {
        String js ="alert(\"hello,this is a alert!\")";
        ((org.openqa.selenium.JavascriptExecutor) driver).executeScript(js);
        Thread.sleep(2000);
    }
    
    private static void runJSTest2(WebDriver driver)
            throws InterruptedException {
        driver.get("https://www.baidu.com/");
        String js ="arguments[0].click();";
        driver.findElement(By.id("kw")).sendKeys("JAVA");
        WebElement searchButton = driver.findElement(By.id("su"));
        ((org.openqa.selenium.JavascriptExecutor) driver).executeScript(js,searchButton);
        Thread.sleep(2000);
    }
View Code

7 等待元素加载

  • 硬性等待  Thread.sleep(int sleeptime);
  • 智能等待
  • 设置等待页面加载完毕
技术分享
    private static void waitElementTest(WebDriver driver) {
        //设置等待页面完全加载的时间是10秒,如果在10秒内加载完毕,剩余时间不在等待
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        driver.get("https://www.baidu.com/");
        By inputBox = By.id("kw");
        By searchButton = By.id("su");
        //智能等待元素加载出来
        intelligentWait(driver, 10, inputBox);
        //智能等待元素加载出来
        intelligentWait(driver, 10, searchButton);
        //输入内容
        driver.findElement(inputBox).sendKeys("JAVA");
        //点击查询
        driver.findElement(searchButton).click();
    }
    
    
    public static void intelligentWait(WebDriver driver,int timeOut, final By by){        
        try {
            (new WebDriverWait(driver, timeOut)).until(new ExpectedCondition<Boolean>() {

                public Boolean apply(WebDriver driver) {
                    WebElement element = driver.findElement(by);
                    return element.isDisplayed();
                }
            });
        } catch (TimeoutException e) {
            Assert.fail("超时!! " + timeOut + " 秒之后还没找到元素 [" + by + "]",e);
        }
    }
View Code

8 模拟键盘操作

有时候有些元素不便点击或者做其他的操作,这个时候可以借助selenium提供的Actions类,它可以模拟鼠标和键盘的一些操作,比如点击鼠标右键,左键,移动鼠标等操作。对于这些操作,使用perform()方法进行执行。

技术分享
    private static void actionsTest(WebDriver driver)
            throws InterruptedException {
        // 设置等待页面完全加载的时间是10秒,如果在10秒内加载完毕,剩余时间不在等待
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        driver.get("https://www.baidu.com/");
        By inputBox = By.id("kw");
        By searchButton = By.id("su");
        // 智能等待元素加载出来
        intelligentWait(driver, 10, inputBox);
        // 智能等待元素加载出来
        intelligentWait(driver, 10, searchButton);
        // 实例化action对象
        Actions action = new Actions(driver);
        // 通过action模拟键盘输入java关键字到 输入框,只有使用了perform方法才会输入进去
        action.sendKeys(driver.findElement(searchButton), "java").perform();
        // 鼠标模拟移动到搜索按钮
        action.moveToElement(driver.findElement(searchButton)).perform();
        // 模拟点击操作
        action.click().perform();
        Thread.sleep(2000);
    }
View Code

 9 设置浏览器窗口大小

技术分享
    private static void SetWindowTest(WebDriver driver)
            throws InterruptedException {
        // 设置窗口的 宽度为:800,高度为600
        Dimension d = new Dimension(800, 600);
        driver.manage().window().setSize(d);
        Thread.sleep(2000);

        // 设置窗口最大化
        driver.manage().window().maximize();
        Thread.sleep(2000);

        // 设置窗口出现在屏幕上的坐标
        Point p = new Point(500, 300);
        // 执行设置
        driver.manage().window().setPosition(p);
        Thread.sleep(2000);
    }
View Code

10 上传文件

10.1 元素标签是Input时上传方式

Upload.html文件内容如下:

<body>
<input type="file" id="fileControl" value="选择文件"/>
</body>

代码如下:

技术分享
    private static void uploadTest1(WebDriver driver) throws InterruptedException {
        //打开上传的网页 - get中输入upload的地址
        driver.get("D:\\DownLoad\\UploadTest\\upload.html");
        WebElement e1 = driver.findElement(By.id("fileControl"));
        Thread.sleep(2000);
        //输入要上传文件的地址
        e1.sendKeys("D:\\DownLoad\\UploadTest\\被上传的文件.txt");
        Thread.sleep(2000);
    }
View Code

11 Selenium处理HTML5

11.1 处理Vedio

这就需要了解html5中vedio的相关方法了,可以参考http://www.w3school.com.cn/tags/html_ref_audio_video_dom.asp

技术分享
    private static void html5VedioTest(WebDriver driver)
            throws InterruptedException {
        driver.get("http://videojs.com/");
        Thread.sleep(2000);
        //找到vedio元素
        WebElement vedio = driver.findElement(By.id("preview-player_html5_api"));
        //声明js执行器
        JavascriptExecutor js = (JavascriptExecutor) driver;
        //对vedio这个元素执行播放操作 
        js.executeScript("arguments[0].play()", vedio);
        //为了观察效果暂停5秒
        Thread.sleep(5000);
        //对vedio这个元素执行暂停操作
        js.executeScript("arguments[0].pause()", vedio);
        //为了观察效果暂停2秒
        Thread.sleep(2000);
        //对vedio这个元素执行播放操作 
        js.executeScript("arguments[0].play()", vedio);
        //为了观察效果暂停2秒
        Thread.sleep(2000);
        //对vedio这个元素执行重新加载视频的操作
        js.executeScript("arguments[0].load()", vedio);
        //为了观察效果暂停2秒
        Thread.sleep(2000);
    }
View Code

11.2 处理Canvas 

技术分享
    private static void Html5CanvasTest(WebDriver driver)
            throws InterruptedException {
        driver.get("http://literallycanvas.com/");
        Thread.sleep(2000);
        //找到canvas元素
        WebElement canvas = driver.findElement(By.xpath("//*[@id=‘literally-canvas‘]//canvas[1]"));
        //声明一个操作类
        Actions drawPen = new Actions(driver);
        //点击并保持不放鼠标 ,按照给定的坐标点移动
        drawPen.clickAndHold(canvas).moveByOffset(20, 100).moveByOffset(100, 20).moveByOffset(-20, -100).moveByOffset(-100, -20).release().perform();
        Thread.sleep(2000);
    }
View Code

 

Selenium Web 自动化 - Selenium常用API

标签:

原文地址:http://www.cnblogs.com/Ming8006/p/5727542.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!