转:Selenium Webdriver使用技巧(三)

上一篇 / 下一篇  2014-05-05 12:01:39 / 个人分类:Selenium

如何处理alertconfirmprompt对话框

alertconfirmprompt这样的js对话框在selenium1.X时代也是难啃的骨头,常常要用autoit来帮助处理。

试用了一下selenium webdriver中处理这些对话框十分方便简洁

 

Html代码

 

Dialogs.html  

 

<html>

 

   <head>

 

       <title>Alert</title>

 

   </head>

 

   <body>

 

       <input id = "alert" value = "alert" type ="button" nclick = "alert('欢迎!请按确认继续!');"/>

        <input id = "confirm" value= "confirm" type = "button" nclick = "confirm('确定吗?');"/>

         <inputid = "prompt" value = "prompt" type = "button"onclick = "var name = prompt('请输入你的名字:','请输入

 

你的名字'); document.write(name) "/>

        

 

   </body>

 

</html>

 

 

 以上html代码在页面上显示了三个按钮,点击他们分别弹出alertconfirmprompt对话框。如果在prompt对话框中输入文字点击确定之后,将会刷新页面,显示出这些文字。

 

selenium webdriver处理这些弹层的代码如下:

 

Java代码

 

import org.openqa.selenium.Alert;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

 

public class DialogsStudy {

 

         /**

          * @author gongjf

          */

         publicstatic void main(String[] args) {

                   //TODO Auto-generated method stub

                   System.setProperty("webdriver.firefox.bin","D:\\ProgramFiles\\Mozilla Firefox\\firefox.exe"); 

                   WebDriverdr = new FirefoxDriver();

                   Stringurl = "file:///C:/Documents and Settings/gongjf/桌面/selenium_test/Dialogs.html";//"/Your/Path/to/main.html"

                   dr.get(url);

                  

                   //点击第一个按钮,输出对话框上面的文字,然后叉掉

                   dr.findElement(By.id("alert")).click();

                   Alertalert = dr.switchTo().alert();

                   Stringtext = alert.getText();

                   System.out.println(text);

                   alert.dismiss();

                  

                   //点击第二个按钮,输出对话框上面的文字,然后点击确认

                   dr.findElement(By.id("confirm")).click();

                   Alertconfirm = dr.switchTo().alert();

                   Stringtext1 = confirm.getText();

                   System.out.println(text1);

                   confirm.accept();

                  

                   //点击第三个按钮,输入你的名字,然后点击确认,最后

                   dr.findElement(By.id("prompt")).click();

                   Alertprompt = dr.switchTo().alert();

                   Stringtext2 = prompt.getText();

                   System.out.println(text2);

                   prompt.sendKeys("jarvi");

                   prompt.accept();

                  

         }

 

}

 

 

小结:

 

从以上代码可以看出dr.switchTo().alert();这句可以得到alert\confirm\prompt对话框的对象,然后运用其方法对它进行操作。对话框操作的主要方法有:

 

getText()    得到它的文本值

accept()      相当于点击它的"确认"

dismiss()    相当于点击"取消"或者叉掉对话框

sendKeys()输入值,这个alert\confirm没有对话框就不能用了,不然会报错。

 

 

如何操作cookies

 

Web测试中我们经常会接触到Cookies,一个Cookies主要属性有所在域、namevalue、有效日期和路径",下面来讲一下怎么操作Cookies

 

Java代码

 

import java.util.Set;

 

import org.openqa.selenium.Cookie;

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

 

public class CookiesStudy {

 

         /**

          * @author gongjf

          */

         publicstatic void main(String[] args) {

                   //TODO Auto-generated method stub

                   System.setProperty("webdriver.firefox.bin","D:\\ProgramFiles\\Mozilla Firefox\\firefox.exe"); 

                   WebDriverdr = new FirefoxDriver();

                   dr.get("http://www.51.com");

                  

                   //增加一个name ="name",value="value"cookie

                   Cookiecookie = new Cookie("name", "value");

                   dr.manage().addCookie(cookie);

                  

                   //得到当前页面下所有的cookies,并且输出它们的所在域、namevalue、有效日期和路径

                   Set<Cookie>cookies = dr.manage().getCookies();

                   System.out.println(String.format("Domain-> name -> value -> expiry -> path"));

                   for(Cookiec : cookies)

                            System.out.println(String.format("%s-> %s -> %s -> %s -> %s",

                                               c.getDomain(),c.getName(), c.getValue(),c.getExpiry(),c.getPath()));

                  

                  

                   //删除cookie有三种方法

                  

                   //第一种通过cookiename

                   dr.manage().deleteCookieNamed("CookieName");

                   //第二种通过Cookie对象

                   dr.manage().deleteCookie(cookie);

                   //第三种全部删除

                   dr.manage().deleteAllCookies();

         }

 

小结:

 

上面的代码首先在页面中增加了一个cookie,然后遍历页面的所有cookies,并输出他们的主要属性。最后就是三种删除cookie的方法。

 

 

如何等待页面元素加载完成

web自动化测试中,我们经常会遇到这样一种情况:当我们的程序执行时需要页面某个元素,而此时这个元素还未加载完成,这时我们的程序就会报错。怎么办?等待。等待元素出现后再进行对这个元素的操作。

selenium-webdriver中我们用两种方式进行等待:明确的等待和隐性的等待。

 

明确的等待

 

明确的等待是指在代码进行下一步操作之前等待某一个条件的发生。最不好的情况是使用Thread.sleep()去设置一段确认的时间去等待。但为什么说最不好呢?因为一个元素的加载时间有长有短,你在设置sleep的时间之前要自己把握长短,太短容易超时,太长浪费时间。selenium webdriver提供了一些方法帮助我们等待正好需要等待的时间。利用WebDriverWait类和ExpectedCondition接口就能实现这一点。

 

 

下面的html代码实现了这样的一种效果:点击click按钮5秒钟后,页面上会出现一个红色的div块。我们需要写一段自动化脚本去捕获这个出现的div,然后高亮之。

 

 

Html代码

 

Wait.html

 

<html>

   <head>

       <title>Set Timeout</title>

       <style>

           .red_box {background-color: red; width = 20%; height: 100px; border:none;}

       </style>

       <script>

           function show_div(){

               setTimeout("create_div()", 5000);

           }

 

           function create_div(){

                d =document.createElement('div');

                d.className ="red_box";

                document.body.appendChild(d);

           }

       </script>

   </head>

   <body>

       <button id = "b" nclick ="show_div()">click</button>

   </body>

</html>

 

 

下面的代码实现了高亮动态生成的div块的功能:

 

Java代码

 

import org.openqa.selenium.By;

importorg.openqa.selenium.JavascriptExecutor;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxDriver;

importorg.openqa.selenium.support.ui.ExpectedCondition;

importorg.openqa.selenium.support.ui.WebDriverWait;

 

 

public class WaitForSomthing {

 

         /**

          * @author gongjf

          */

         publicstatic void main(String[] args) {

                   //TODO Auto-generated method stub

                   System.setProperty("webdriver.firefox.bin","D:\\ProgramFiles\\Mozilla Firefox\\firefox.exe"); 

                   WebDriverdr = new FirefoxDriver();

                   Stringurl = "file:///C:/Documents and Settings/gongjf/桌面/selenium_test/Wait.html";//"/Your/Path/to/Wait.html"

                   dr.get(url);

                   WebDriverWaitwait = new WebDriverWait(dr,10);

                   wait.until(newExpectedCondition<WebElement>(){

                            @Override

                            publicWebElement apply(WebDriver d) {

                                     returnd.findElement(By.id("b"));

                            }}).click();

                  

                   WebElementelement = dr.findElement(By.cssSelector(".red_box"));

                   ((JavascriptExecutor)dr).executeScript("arguments[0].style.border= \"5px solid yellow\"",element); 

                  

         }

}

 

 

上面的代码WebDriverWait类的构造方法接受了一个WebDriver对象和一个等待最长时间(10秒)。然后调用until方法,其中重写了ExpectedCondition接口中的apply方法,让其返回一个WebElement,即加载完成的元素,然后点击。默认情况下,WebDriverWait500毫秒调用一次ExpectedCondition,直到有成功的返回,当然如果超过设定的值还没有成功的返回,将抛出异常。

 

 

隐性等待

 

隐性等待是指当要查找元素,而这个元素没有马上出现时,告诉WebDriver查询Dom一定时间。默认值是0,但是设置之后,这个时间将在WebDriver对象实例整个生命周期都起作用。上面的代码就变成了这样:

 

 

Java代码

 

 

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;

importorg.openqa.selenium.JavascriptExecutor;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxDriver;

importorg.openqa.selenium.support.ui.ExpectedCondition;

importorg.openqa.selenium.support.ui.WebDriverWait;

 

 

public class WaitForSomthing {

 

         /**

          * @author gongjf

          */

         publicstatic void main(String[] args) {

                   //TODO Auto-generated method stub

                   System.setProperty("webdriver.firefox.bin","D:\\ProgramFiles\\Mozilla Firefox\\firefox.exe"); 

                   WebDriverdr = new FirefoxDriver();

                  

                   //设置10

                   dr.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

                  

                   Stringurl = "file:///C:/Documents and Settings/gongjf/桌面/selenium_test/Wait.html";//"/Your/Path/to/Wait.html"

                   dr.get(url);

                 //注释掉原来的

                   /*WebDriverWaitwait = new WebDriverWait(dr,10);

                   wait.until(newExpectedCondition<WebElement>(){

                            @Override

                            publicWebElement apply(WebDriver d) {

                                     returnd.findElement(By.id("b"));

                            }}).click();*/

                   dr.findElement(By.id("b")).click();

                   WebElementelement = dr.findElement(By.cssSelector(".red_box"));

                   ((JavascriptExecutor)dr).executeScript("arguments[0].style.border= \"5px solid yellow\"",element); 

                  

         }

}

 

 

小结:

 

两种方法任选其一

 

 

如何利用selenium-webdriver截图

 

在自动化测试中常常会用到截图功能。可以截取页面全图,不管页面有多长。

 

下面的代码演示了如何使用webdriver进行截图:

 

 

Java代码

 

 

import java.io.File;

import java.io.IOException;

 

import org.apache.commons.io.FileUtils;

import org.openqa.selenium.OutputType;

import org.openqa.selenium.TakesScreenshot;

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class ShotScreen {

 

         /**

          * @author gongjf

          * @throws IOException

          * @throws InterruptedException

          */

         publicstatic void main(String[] args) throws IOException, InterruptedException {

                  

                   System.setProperty("webdriver.firefox.bin","D:\\ProgramFiles\\Mozilla Firefox\\firefox.exe"); 

                   WebDriverdr = new FirefoxDriver();

                   dr.get("http://www.51.com");

                                    

                   //这里等待页面加载完成

                   Thread.sleep(5000);

                   //下面代码是得到截图并保存在D盘下

                   FilescreenShotFile = ((TakesScreenshot)dr).getScreenshotAs(OutputType.FILE);

                   FileUtils.copyFile(screenShotFile,new File("D:/test.png"));

}

}

 

 



TAG:

 

评分:0

我来说两句

Open Toolbar