【转载】Selenium WebDriver的简单操作说明

转载自:http://blog.csdn.net/xiao190128/article/details/49784121

1.打开一个测试浏览器

  对浏览器进行操作首先需要打开一个浏览器,接下来才能对浏览器进行操作。

Java代码

import java.io.File;

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxBinary;

importorg.openqa.selenium.firefox.FirefoxDriver;

importorg.openqa.selenium.ie.InternetExplorerDriver;

public class OpenBrowsers {

        

         public static void main(String[] args) {

                   //打开默认路径的firefox

                   WebDriver diver = new FirefoxDriver();

                  

                   //打开指定路径的firefox,方法1

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

                   WebDriver dr = new FirefoxDriver();

                  

                   //打开指定路径的firefox,方法2

                   File pathToFirefoxBinary = newFile("D:\\Program Files\\Mozilla Firefox\\firefox.exe"); 

                   FirefoxBinary firefoxbin = newFirefoxBinary(pathToFirefoxBinary); 

                   WebDriver driver1 = newFirefoxDriver(firefoxbin,null);

                  

                   //打开ie

                   WebDriver ie_driver = new InternetExplorerDriver();

                  

                   //打开chrome

                   System.setProperty("webdriver.chrome.driver","D:\\chromedriver.exe");

                   System.setProperty("webdriver.chrome.bin",

                                            "C:\\Documents and Settings\\gongjf\\Local Settings"

                                             +"\\ApplicationData\\Google\\Chrome\\Application\\chrome.exe");

                  

                  

         }

}

2.打开1个具体的url

打开一个浏览器后,我们需要跳转到特定的url下,看下面代码:

Java代码

 

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class OpenUrl {

         publicstatic void main(String []args){

                   Stringurl = "http://www.51.com";

                   WebDriverdriver = new FirefoxDriver();

                  

                   //用get方法

                   driver.get(url);

                  

                   //用navigate方法,然后再调用to方法

                   driver.navigate().to(url);

         }

}

3.如何关闭浏览器

测试完成后,需要关闭浏览器

Java代码

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class CloseBrowser {

         publicstatic void main(String []args){

                   Stringurl = "http://www.51.com";

                   WebDriverdriver = new FirefoxDriver();

                  

                   driver.get(url);

                  

                   //用quit方法

                   driver.quit();

                  

                   //用close方法       

                   driver.close();

                   }

}

4.如何返回当前页面的url和title

有时候我们需要返回当前页面的url或者title做一些验证性的操作等。代码如下:

Java代码

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class GetUrlAndTitle {

         publicstatic void main(String []args){

                   Stringurl = "http://www.google.com";

                   WebDriverdriver = new FirefoxDriver();

                  

                   driver.get(url);

                  

                //得到title

                   Stringtitle = driver.getTitle();

                //得到当前页面url

                   StringcurrentUrl = driver.getCurrentUrl();

                  

                //输出title和currenturl

                   System.out.println(title+"\n"+currentUrl);

                  

                   }

}

5.其他方法

getWindowHandle()    返回当前的浏览器的窗口句柄

getWindowHandles()  返回当前的浏览器的所有窗口句柄

getPageSource()        返回当前页面的源码

从上面代码可以看出操作浏览器的主要方法都来自org.openqa.selenium.WebDriver这个接口中。看了一下源代码这些方法都是在org.openqa.selenium.remote.RemoteWebDriver这个类中实现的,然后不同浏览的driver类继承RemoteWebDriver。

C  定位页面元素

selenium-webdriver提供了强大的元素定位方法,支持以下三种方法。

单个对象的定位方法

多个对象的定位方法

层级定位 

定位单个元素

在定位单个元素时,selenium-webdriver提示了如下一些方法对元素进行定位。

 By.className(className))    

 By.cssSelector(selector)       

 By.id(id)                     

 By.linkText(linkText)          

 By.name(name)             

 By.partialLinkText(linkText)

 By.tagName(name)       

 By.xpath(xpathExpression)  

注意:selenium-webdriver通过findElement()\findElements()等find方法调用"By"对象来定位 和查询元素。By类只是提供查询的方式进行分类。findElement返回一个元素对象否则抛出异常,findElements返回符合条件的元素 List,如果不存在符合条件的就返回一个空的list。

1.使用className进行定位

当所定位的元素具有class属性的时候我们可以通过classname来定位该元素。

下面的例子定位了51.com首页上class为"username"的li。

Java代码

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

import org.openqa.selenium.By;

public class ByClassName {

  

   public static void main(String[] args) {

        WebDriver driver = new FirefoxDriver();

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

        WebElement element =driver.findElement(By.className("username"));

        System.out.println(element.getTagName());

    }

}

输出结果:

Java代码

 

Li

2.使用id属性定位

51.com首页的帐号输入框的html代码如下:

Java代码

<input id="passport_51_user"type="text" value="" tabindex="1" title="用户名/彩虹号/邮箱"

name="passport_51_user">

在下面的例子中用id定位这个输入框,并输出其title,借此也可以验证代码是否工作正常。

Java代码

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class ByUserId {

         /**

          * @param args

          */

         publicstatic void main(String[] args) {

                   //TODO Auto-generated method stub

                   WebDriverdr = new FirefoxDriver();

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

                  

                   WebElementelement = dr.findElement(By.id("passport_51_user"));

                   System.out.println(element.getAttribute("title"));

         }

}

输出结果:

 Java代码

用户名/彩虹号/邮箱

3.使用name属性定位

51.com首页的帐号输入框的html代码如下:

Java代码

<input id="passport_51_user"type="text" value="" tabindex="1" title="用户名/彩虹号/邮箱"

name="passport_51_user">

使用name定位

 

Java代码

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class ByUserId {

         /**

          * @param args

          */

         publicstatic void main(String[] args) {

                   //TODO Auto-generated method stub

                   WebDriverdr = new FirefoxDriver();

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

                  

         WebElemente = dr.findElement(By.name("passport_51_user"));                                      System.out.println(element.getAttribute("title"));

         }

}

输出结果:

 Java代码

用户名/彩虹号/邮箱

4.使用css属性定位

51.com首页的帐号输入框的html代码如下:

Java代码

<input id="passport_51_user"type="text" value="" tabindex="1" title="用户名/彩虹号/邮箱"

name="passport_51_user">

使用css定位

Java代码

WebElement e1 =dr.findElement(By.cssSelector("#passport_51_user"));

5.使用 XPATH定位

51.com首页的帐号输入框的html代码如下:

Java代码

<input id="passport_51_user"type="text" value="" tabindex="1" title="用户名/彩虹号/邮箱"

name="passport_51_user">

通过xpath查找:

Java代码

WebElement element=driver.findElement(By.xpath("//input[@id=' passport_51_user ']"));

6.使用其他方式定位

在定位link元素的时候,可以使用link和link_text属性;

另外还可以使用tag_name属性定位任意元素;

7.定位多个元素

上面提到findElements()方法可以返回一个符合条件的元素List组。看下面例子。

Java代码

import java.io.File;

import java.util.List;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxBinary;

import org.openqa.selenium.firefox.FirefoxDriver;

public class FindElementsStudy {

         /**

          * @author gongjf

          */

         publicstatic void main(String[] args) {

                   WebDriver  driver = new FirefoxDriver();

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

                  

                   //定位到所有<input>标签的元素,然后输出他们的id

                   List<WebElement>element = driver.findElements(By.tagName("input"));

                   for(WebElement e : element){

                            System.out.println(e.getAttribute("id"));

                   }

                  

                   driver.quit();

         }

}

输出结果:

Java代码

 

passport_cookie_login

gourl

passport_login_from

passport_51_user

passport_51_password

passport_qq_login_2

btn_reg

passport_51_ishidden

passport_auto_login

上面的代码返回页面上所有input对象

8.层级定位

层级定位的思想是先定位父元素,然后再从父元素中精确定位出其我们需要选取的子元素。

层级定位一般的应用场景是无法直接定位到需要选取的元素,但是其父元素比较容易定位,通过定位父元素再遍历其子元素选择需要的目标元素,或者需要定位某个元素下所有的子元素。

下面的代码演示了如何使用层级定位class为"login"的div,然后再取得它下面的所有label,并打印出他们的文本

Java代码

 

import java.io.File;

importjava.util.List;

importorg.openqa.selenium.By;

importorg.openqa.selenium.WebDriver;

importorg.openqa.selenium.WebElement;

importorg.openqa.selenium.firefox.FirefoxBinary;

importorg.openqa.selenium.firefox.FirefoxDriver;

publicclass LayerLocator {

         /**

          * @author gongjf

          */

         public static void main(String[] args){

        

                   WebDriver  driver = new FirefoxDriver();

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

                  

                   //定位class为"login"的div,然后再取得它下面的所有label,并打印出他们的值

                   WebElement element =driver.findElement(By.className("login"));

                    List<WebElement> el =element.findElements(By.tagName("label"));

                    for(WebElement e : el)

                   System.out.println(e.getText());

        

         }       

}

输出结果:

Java代码

帐号:

密码:

隐身

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

找到页面元素后,怎样对页面进行操作呢?我们可以根据不同的类型的元素来进行一一说明。

1. 输入框(text field or textarea)

 找到输入框元素:

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

在输入框中输入内容:

element.sendKeys(“test”);

将输入框清空:

element.clear();

获取输入框的文本内容:

element.getText();

2. 下拉选择框(Select)

找到下拉选择框的元素:

Select select = newSelect(driver.findElement(By.id("select")));

选择对应的选择项:

select.selectByVisibleText(“mediaAgencyA”);

select.selectByValue(“MA_ID_001”);

不选择对应的选择项:

select.deselectAll();

select.deselectByValue(“MA_ID_001”);

select.deselectByVisibleText(“mediaAgencyA”);

或者获取选择项的值:

select.getAllSelectedOptions();

select.getFirstSelectedOption();

对下拉框进行操作时首先要定位到这个下拉框,new 一个Selcet对象,然后对它进行操作 

3. 单选项(Radio Button)

找到单选框元素:

WebElement bookMode =driver.findElement(By.id("BookMode"));

选择某个单选项:

bookMode.click();

清空某个单选项:

bookMode.clear();

判断某个单选项是否已经被选择:

bookMode.isSelected();

4. 多选项(checkbox)

多选项的操作和单选的差不多:

WebElement checkbox=driver.findElement(By.id("myCheckbox."));

checkbox.click();

checkbox.clear();

checkbox.isSelected();

checkbox.isEnabled();

5. 按钮(button)

找到按钮元素:

WebElement saveButton =driver.findElement(By.id("save"));

点击按钮:

saveButton.click();

判断按钮是否enable:

saveButton.isEnabled ();

6. 左右选择框

也就是左边是可供选择项,选择后移动到右边的框中,反之亦然。例如:

Select lang = new Select(driver.findElement(By.id("languages")));

lang.selectByVisibleText(“English”);

WebElement addLanguage=driver.findElement(By.id("addButton"));

addLanguage.click();

7. 弹出对话框(Popup dialogs)

Alert alert = driver.switchTo().alert();

alert.accept();

alert.dismiss();

alert.getText();

后面有具体的例子解释~

8. 表单(Form)

Form中的元素的操作和其它的元素操作一样,对元素操作完成后对表单的提交可以:

WebElement approve =driver.findElement(By.id("approve"));

approve.click();

approve.submit();//只适合于表单的提交

9. 上传文件 (Upload File)

上传文件的元素操作:

WebElement adFileUpload = driver.findElement(By.id("WAP-upload"));

String filePath ="C:\test\\uploadfile\\media_ads\\test.jpg";

adFileUpload.sendKeys(filePath);

10.拖拉(Drag andDrop)

WebElement element=driver.findElement(By.name("source"));

WebElement target = driver.findElement(By.name("target"));

(new Actions(driver)).dragAndDrop(element,target).perform();

11.导航 (Navigationand History)

打开一个新的页面:

 driver.navigate().to("http://www.example.com");

通过历史导航返回原页面:

driver.navigate().forward();

driver.navigate().back();

                                                                                                                                           

E  iframe的处理

有时候我们在定位一个页面元素的时候发现一直定位不了,反复检查自己写的定位器没有任何问题,代码也没有任何问题。这时你就要看一下这个页面元素是否在一个iframe中,这可能就是找不到的原因之一。如果你在一个default content中查找一个在iframe中的元素,那肯定是找不到的。反之你在一个iframe中查找另一个iframe元素或default content中的元素,那必然也定位不到。

selenium webdriver中提供了进入一个iframe的方法:

WebDriverorg.openqa.selenium.WebDriver.TargetLocator.frame(String nameOrId)

也提供了一个返回default content的方法:

WebDriver org.openqa.selenium.WebDriver.TargetLocator.defaultContent()

这样使我们面对iframe时可以轻松应对。

以下面的html代码为例,我们看一下处现iframe。

Html代码

main.html

<html>

   <head>

       <title>FrameTest</title>

   </head>

   <body>

         <divid = "id1">this is a div!</div>

       <iframe id = "frame" frameborder="0" scrolling="no"style="left:0;position:absolute;" src ="frame.html"></iframe>

   </body>

</html>

frame.html

<html>

   <head>

       <title>this is a frame!</title>

   </head>

   <body>

         <divid = "div1">this is a div,too!</div>

         <label>input:</label>

         <inputid = "input1"></input>

   </body>

</html>

Java代码

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class FameStudy {

        

         publicstatic void main(String[] args) {

                   WebDriverdr = new FirefoxDriver();

                   Stringurl = "\\Your\\Path\\to\\main.html";

                   dr.get(url);

                   //在defaultcontent定位id="id1"的div

                   dr.findElement(By.id("id1"));

                  

                   //此时,没有进入到id="frame"的frame中时,以下两句会报错

                   dr.findElement(By.id("div1"));//报错

                   dr.findElement(By.id("input1"));//报错

                  

                   //进入id="frame"的frame中,定位id="div1"的div和id="input1"的输入框。

                   dr.switchTo().frame("frame");        

                   dr.findElement(By.id("div1"));

                   dr.findElement(By.id("input1"));

                  

                   //此时,没有跳出frame,如果定位defaultcontent中的元素也会报错。

                   dr.findElement(By.id("id1"));//报错

                  

                   //跳出frame,进入defaultcontent;重新定位id="id1"的div

                   dr.switchTo().defaultContent();

                   dr.findElement(By.id("id1"));

         }

}

小结:

switch_to方法会new1个TargetLocator对象,使用该对象的frame方法可以将当前识别的”主体”移动到需要定位的frame上去。 

F 如何得到弹出窗口

在selenium 1.X里面得到弹出窗口是一件比较麻烦的事,特别是新开窗口没有id、name的时候。在selenium webdriver中得到新开窗口相对简单的多,它无关新开窗口的id、name等属性。以下面的html为例:

Html代码

<span style="white-space: normal;">test.html</span>

<html>

   <head><title>Test Popup Window</title></head>

   <body>

       <a id = "51" href = "http://www.51.com/" target ="_blank">Let's go!</a>

   </body>

</html>

下面的代码演示了如何去得到弹出的新窗口

Java代码

 

import java.util.Iterator;

import java.util.Set;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

importorg.openqa.selenium.firefox.FirefoxDriver;

public class PopupWindowTest {

         /**

          * @author gongjf

          */

         publicstatic void main(String[] args) {

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

                   WebDriverdr = new FirefoxDriver();

                   Stringurl ="\\Your\\Path\\to\\main.html";

                   dr.get(url);       

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

                   //得到当前窗口的句柄

                   StringcurrentWindow = dr.getWindowHandle();

                   //得到所有窗口的句柄

                   Set<String>handles = dr.getWindowHandles();

                   Iterator<String>it = handles.iterator();

                   while(it.hasNext()){

                            if(currentWindow== it.next())  continue;

                            dr.switchTo().window(it.next());

                           

                   }

         }

}

输出结果:

title,url = 51.com 真人配对玩游戏,http://www.51.com/

小结:

捕获或者说定位弹出窗口的关键在于获得弹出窗口的句柄。(

在上面的代码里,使用windowhandle方法来获取当前浏览器窗口的句柄,使用了windowhandles方法获取所有弹出的浏览器窗口的句柄,然后通过排除当前句柄的方法来得到新开窗口的句柄。

在获取新弹出窗口的句柄后,使用switchto.window(newwindow_handle)方法,将新窗口的句柄作为参数传入既可捕获到新窗口了。

如果想回到以前的窗口定位元素,那么再调用1次switchto.window方法,传入之前窗口的句柄既可达到目的。

G  如何处理alert、confirm、prompt对话框

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

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

Html代码

Dialogs.html  

<html>

   <head>

       <title>Alert</title>

   </head>

   <body>

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

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

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

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

        

   </body>

</html>

 以上html代码在页面上显示了三个按钮,点击他们分别弹出alert、confirm、prompt对话框。如果在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没有对话框就不能用了,不然会报错。

H  如何操作cookies

Web 测试中我们经常会接触到Cookies,一个Cookies主要属性有”所在域、name、value、有效日期和路径",下面来讲一下怎么操作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,并且输出它们的所在域、name、value、有效日期和路径

                   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有三种方法

                  

                   //第一种通过cookie的name

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

                   //第二种通过Cookie对象

                   dr.manage().deleteCookie(cookie);

                   //第三种全部删除

                   dr.manage().deleteAllCookies();

         }

小结:

 

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

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

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 { 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" onclick ="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,即加载完成的元素,然后点击。默认情况下,WebDriverWait每500毫秒调用一次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); 

                  

         }

}

小结:

 

两种方法任选其一

J  如何利用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"));

}

}

K  封装与重用

WebDriver对页面的操作,需要找到一个WebElement,然后再对其进行操作,比较繁琐:

 // Find the text inputelement by itsname

WebElement element =driver.findElement(By.name("q"));

// Enter something to search for

element.sendKeys("Cheese!");

我们可以考虑对这些基本的操作进行一个封装,简化操作。比如,封装代码:

    protected voidsendKeys(Byby, String value){

       driver.findElement(by).sendKeys(value);

    }

那么,在测试用例可以这样简化调用:

sendKeys(By.name("q"),”Cheese!”);

看,这就简洁多了。

类似的封装还有:

package com.drutt.mm.end2end.actions;

import java.util.List;

import java.util.NoSuchElementException;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;

import org.openqa.selenium.WebElement;

importorg.openqa.selenium.remote.RemoteWebDriver;

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

importcom.drutt.mm.end2end.data.TestConstant;

public class WebDriverAction {

   //protected WebDriverdriver;

   protectedRemoteWebDriverdriver;

   protectedWebDriverWaitdriverWait;

    protected booleanisWebElementExist(Byselector) {

       try {

           driver.findElement(selector);

           return true;

       } catch(NoSuchElementException e) {

           return false;

       }

    }

   

    protectedStringgetWebText(By by) {

       try {

       return driver.findElement(by).getText();

       } catch (NoSuchElementException e) {

           return "Textnot existed!";

       }

    }

   

    protectedvoidclickElementContainingText(By by, String text){

       List<WebElement>elementList = driver.findElements(by);

       for(WebElement e:elementList){

           if(e.getText().contains(text)){

               e.click();

               break;

           }

       }    

    }

   

    protectedStringgetLinkUrlContainingText(By by, String text){

       List<WebElement>subscribeButton = driver.findElements(by);

       String url = null;

       for(WebElement e:subscribeButton){

           if(e.getText().contains(text)){

               url =e.getAttribute("href");

               break;

           }

       }

       return url;

    }

   

    protected voidclick(Byby){

       driver.findElement(by).click();

       driver.manage().timeouts().implicitlyWait(TestConstant.WAIT_ELEMENT_TO_LOAD,TimeUnit.SECONDS);

    }

    protectedStringgetLinkUrl(By by){

       return driver.findElement(by).getAttribute("href");

    }

   

    protected voidsendKeys(Byby, String value){

       driver.findElement(by).sendKeys(value);

    }

小结:

 

按照上面的例子你可以对各个方法进行封装,使自己的代码更加简洁!

L  在selenium2.0中使用selenium1.0的API

Selenium2.0中使用WeDriver API对页面进行操作,它最大的优点是不需要安装一个selenium server就可以运行,但是对页面进行操作不如selenium1.0的Selenium RC API那么方便。Selenium2.0提供了使用Selenium RC API的方法:

// 我用火狐浏览器作为例子

WebDriver driver = newFirefoxDriver(); 

 String baseUrl="http://www.google.com"; 

Selenium selenium = newWebDriverBackedSelenium(driver, baseUrl);

// 执行selenium命令

selenium.open("http://www.google.com");

selenium.type("name=q","cheese");

selenium.click("name=btnG");

WebDriver driverInstance = ((WebDriverBackedSelenium)selenium).getUnderlyingWebDriver();

selenium.stop();

我分别使用WebDriver API和SeleniumRC API写了一个Login的脚本,很明显,后者的操作更加简单明了。

WebDriver API写的Login脚本:

    public void login() {

       driver.switchTo().defaultContent();

       driver.switchTo().frame("mainFrame");

       WebElement eUsername= waitFindElement(By.id("username"));

       eUsername.sendKeys(manager@ericsson.com);

       WebElement ePassword= waitFindElement(By.id("password"));

       ePassword.sendKeys(manager);

       WebElementeLoginButton = waitFindElement(By.id("loginButton"));

       eLoginButton.click();

    }

   

SeleniumRC API写的Login脚本:

    public void login() {

       selenium.selectFrame("relative=top");

       selenium.selectFrame("mainFrame");

       selenium.type("username","manager@ericsson.com");

       selenium.type("password","manager");

       selenium.click("loginButton");

}

原文地址:https://www.cnblogs.com/yxfeng/p/7681389.html