Selenium Web 自动化

来源:互联网 发布:乐多捕鱼源码 编辑:程序博客网 时间:2024/06/14 12:10

1 对浏览器操作
  1.1 用webdriver打开一个浏览器
  1.2 最大化浏览器&关闭浏览器
  1.3 设置浏览器窗口大小
  1.4 打开测试页面
  1.5 处理浏览器弹出的新窗口
2 页面元素定位
3 如何对页面元素进行操作
  3.1 WebElement相关方法
  3.2 iFrame的处理
  3.3 输入框(text field or textarea)
  3.4 下拉选择框(Select)
  3.5 单选项(Radio Button)
  3.6 多选项(checkbox)
  3.7 按钮(button)
  3.8 处理Alert
  3.9 上传文件
    3.9.1 元素标签是Input时上传方式
    3.9.2 通过操作桌面浏览窗口上传
  3.10 Selenium处理HTML5
    3.10.1 处理Vedio
    3.10.2 处理Canvas 
  3.11 表单(Form)
4 其他
  4.1 等待元素加载
  4.2 执行JS脚本
  4.3 模拟键盘操作

 

1 对浏览器操作


 返回

1.1 用webdriver打开一个浏览器

复制代码
//打开firefox浏览器:WebDriver driver = new FirefoxDriver(); //打开IE浏览器WebDriver driver = new InternetExplorerDriver ();//打开HtmlUnit浏览器WebDriverdriver = new HtmlUnitDriver(); //打开chrome浏览器WebDriverdriver = new ChromeDriver();
复制代码

1.2 最大化浏览器&关闭浏览器

WebDriver driver = new FirefoxDriver();driver.manage().window().maximize();driver.close();driver.quit();

1.3 设置浏览器窗口大小

复制代码
    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);    }
复制代码

1.4 打开测试页面

打开测试页面driver.get("http://www.baidu.com/");driver.navigate().to("http://www.baidu.com/"); //navigate方法会产生1个Navigator对象,其封装了与导航相关的一些方法,比如前进后退等

1.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());    }
复制代码

2 页面元素定位


 返回

Webdriver提供下面两种方法来定位页面元素,参数是By对像,最常用是By.id和By.name查找。

  • findElement   定位某个元素,如果没有找到元素会抛出异常:NoSuchElementException
  • findElements     定位一组元素

例如需要定位如下元素: 

  <input class="input_class" type="text" name="passwd" id="passwd-id" /> 
复制代码
//By.idWebElement element = driver.findElement(By.id("passwd-id"));//By.nameWebElement element = driver.findElement(By.name("passwd"));//By.xpathWebElement element =driver.findElement(By.xpath("//input[@id='passwd-id']")); //By.classNameWebElement element = driver.findElement(By.className("input_class"));//By.cssSelectorWebElement element = driver.findElement(By.cssSelector(".input_class"));//By.linkText//通俗点就是精确查询WebDriver driver = new FirefoxDriver();driver.get("http://www.baidu.com/"); WebElement element = driver.findElement(By.linkText("百科"));//By.partialLinkText://这个方法就是模糊查询WebDriver driver = new FirefoxDriver();driver.get("http://www.baidu.com/"); WebElement element = driver.findElement(By.partialLinkText("hao"));//By.tagNameWebDriver driver = new FirefoxDriver();driver.get("http://www.baidu.com/"); String test= driver.findElement(By.tagName("form")).getAttribute("name");System.out.println(test);
复制代码

3 如何对页面元素进行操作


 返回

3.1 WebElement相关方法

Method   Summaryvoid 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.StringgetAttribute(java.lang.String   name)Get   the value of a the given attribute of the element. java.lang.StringgetCssValue(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, includingsub-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. voidsendKeys(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.

3.2 iFrame的处理

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

3.3 输入框(text field or textarea)

WebElement element = driver.findElement(By.id("passwd-id"));element.sendKeys(“test”);//在输入框中输入内容:element.clear();       //将输入框清空element.getText();     //获取输入框的文本内容:

3.4 下拉选择框(Select)

复制代码
Select select = new Select(driver.findElement(By.id("select")));  select.selectByVisibleText(“A”);select.selectByValue(“1”); select.deselectAll();select.deselectByValue(“1”);select.deselectByVisibleText(“A”);select.getAllSelectedOptions();select.getFirstSelectedOption(); 
复制代码

示例:

复制代码
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();    }}
复制代码

3.5 单选项(Radio Button)

WebElement radio=driver.findElement(By.id("BookMode"));radio.click();       //选择某个单选项radio.clear();      //清空某个单选项radio.isSelected();  //判断某个单选项是否已经被选择

3.6 多选项(checkbox)

WebElement checkbox = driver.findElement(By.id("myCheckbox."));checkbox.click();checkbox.clear();checkbox.isSelected();checkbox.isEnabled();

3.7 按钮(button)

WebElement btn= driver.findElement(By.id("save"));btn.click();      //点击按钮btn.isEnabled ();  //判断按钮是否enable

3.8 处理Alert

弹出对话框(Popup dialogs)

Alert alert = driver.switchTo().alert();alert.accept();  //确定alert.dismiss();  //取消alert.getText(); //获取文本

示例:

复制代码
    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()代码    }
复制代码

3.9 上传文件

3.9.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);    }
复制代码

3.9.2 通过操作桌面浏览窗口上传

示例2 上传文件

3.10 Selenium处理HTML5

3.10.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);    }
复制代码

3.10.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);    }
复制代码

3.11 表单(Form)

//Form中的元素的操作和其它的元素操作一样,对元素操作完成后对表单的提交可以:WebElement approve = driver.findElement(By.id("approve"));approve.click();//approve.submit();//只适合于表单的提交

4 其他


 返回

4.1 等待元素加载

超时设置

WebDriver driver = new FirefoxDriver();driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);      //识别元素时的超时时间driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);  //页面加载时的超时时间driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);  //异步脚本的超时时间
  • 硬性等待  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);        }    }
复制代码

4.2 执行JS脚本

selenium常用的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);    }
复制代码

4.3 模拟键盘操作

有时候有些元素不便点击或者做其他的操作,这个时候可以借助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);    }
复制代码
原创粉丝点击