selenium学习

来源:互联网 发布:seo方案ppt 编辑:程序博客网 时间:2024/06/05 21:16

Selenium 是 thoughtworks公司的一个集成测试的强大工具。最近参与了一个系统移植的项目,正好用到这个工具,把一些使用心得分享给大家,希望大家能多多使用这样的强大的,免费的工具,来保证我们的质量。Selenium 的文档现存的不少,不过都太简单了。使用Selenium的时候,我更多的是直接去看API文档,好在API不错,一个一个看,就能找到所需要的 :-) 官方网站:http://www.openqa.org/selenium/好,下面进入正题!一、Selenium 的版本Selenium 现在存在2个版本,一个叫 selenium-core, 一个叫selenium-rc 。selenium-core 是使用HTML的方式来编写测试脚本,你也可以使用 Selenium-IDE来录制脚本,但是目前Selenium-IDE只有 FireFox 版本。Selenium-RC 是 selenium-remote control 缩写,是使用具体的语言来编写测试类。selenium-rc 支持的语言非常多,这里我们着重关注java的方式。这里讲的也主要是 selenium-rc,因为个人还是喜欢这种方式 :-) 二、一些准备工作1、当然是下载 selenium 了,到 http://www.openqa.org/selenium/ 下载就可以了,记得选择selenium-rc 的版本。2、学习一下 xpath 的知识。有个教程:http://www.zvon.org/xxl/XPathTutorial/General_chi/examples.html 一定要学习这个,不然你根本看不懂下面的内容!3、安装 jdk1.5 三、selenium-rc 一些使用方法在 selenium-remote-control-0.9.0\server 目录里,我们运行 java -jar selenium-server.jar之后你就会看到一些启动信息。要使用 selenium-rc ,启动这个server 是必须的。当然,启动的时候有许多参数,这些用法可以在网站里看看教程,不过不加参数也已经足够了。selenium server 启动完毕了,那么我们就可以开始编写测试类了!我们先有个概念,selenium 是模仿浏览器的行为的,当你运行测试类的时候,你就会发现selenium 会打开一个浏览器,然后浏览器执行你的操作。 好吧,首先生成我们的测试类:java 代码 public class TestPage2 extends TestCase { private Selenium selenium; protected void setUp() throws Exception { String url = “http://xxx.xxx.xxx.xxx/yyy”; selenium = new DefaultSelenium("localhost", SeleniumServer.getDefaultPort (), "*iexplore", url); selenium.start(); super.setUp(); } protected void tearDown() throws Exception { selenium.stop(); super.tearDown(); } } 代码十分简单,作用就是初始化一个 Selenium 对象。其中:url : 就是你要测试的网站localhost: 可以不是localhost,但是必须是 selenium server 启动的地址*iexplore : 可以是其它浏览器类型,可以在网站上看都支持哪些。下面我就要讲讲怎么使用selenium 这个对象来进行测试。1、测试文本输入框假设页面上有一个文本输入框,我们要测试的内容是 在其中输入一些内容,然后点击一个按钮,看看页面的是否跳转到需要的页面。 public void test1() { selenium.open("http://xxx.xxx.xxx/yyy"); selenium.type("xpath=//input[@name='userID']", "test-user"); selenium.click("xpath=//input[@type='button']"); selenium.waitForPageToLoad("2000"); assertEquals(selenium.getTitle(), "Welcome"); } 上面的代码是这个意思:1、调用 selenium.open 方法,浏览器会打开相应的页面2、使用 type 方法来给输入框输入文字3、等待页面载入4、看看新的页面标题是不是我们想要的。2、测试下拉框java 代码 public void test1() { selenium.open("http://xxx.xxx.xxx/yyy"); selenium.select("xpath=//SELECT[@name='SBBUSYO']", "index=1"); selenium.click("xpath=//input[@type='button']"); selenium.waitForPageToLoad("2000"); assertEquals(selenium.getTitle(), "Welcome"); } 可以看到,我们可以使用 select 方法来确定选择下拉框中的哪个选项。select 方法还有很多用法,具体去看看文档吧。3、测试check boxjava 代码 public void test1() { selenium.open("http://xxx.xxx.xxx/yyy"); selenium.check("xpath=//input[@name='MEICK_000']"); selenium.click("xpath=//input[@type='button']"); selenium.waitForPageToLoad("2000"); assertEquals(selenium.getTitle(), "Welcome"); } 我们可以使用 check 方法来确定选择哪个radio button4、得到文本框里的文字java 代码 assertEquals(selenium.getValue("xpath=//input[@name='WNO']"), "1"); getValue 方法就是得到文本框里的数值,可不是 getText 方法,用错了可就郁闷了。5、判断页面是否存在一个元素java 代码 assertTrue(selenium.isElementPresent("xpath=//input[@name='MEICK_000']")); 一般这个是用来测试当删除一些数据后,页面上有些东西就不会显示的情况。6、判断下拉框里选择了哪个选项java 代码 assertEquals(selenium.getSelectedIndex("xpath=//SELECT[@name='HATIMING']"), "1"); 这个可以用来判断下拉框显示的选项是否是期望的选项。7、如果有 alert 弹出对话框怎么办?这个问题弄了挺长时间,可以这样来关闭弹出的对跨框:java 代码 if(selenium.isAlertPresent()) { selenium.getAlert(); } 其实当调用 selenium.getAlert() 时,就会关闭 alert 弹出的对话框。也可以使用 System.out.println(selenium.getAlert()) 来查看对跨框显示的信息。在测试的时候,有的人会显示许多alert 来查看运行时的数据,那么我们可以用下面的方式来关闭那些 alert:java 代码 while(selenium.isAlertPresent()) { selenium.getAlert(); } 8、如何测试一些错误消息的显示?java 代码 assertTrue(selenium.getBodyText().indexOf("错误消息")>=0); 切记: getBodyText 返回的时浏览器页面上的文字,不回包含html 代码的,如果要显示html 代码,用下面这个:java 代码 System.out.println(selenium.getHtmlSource()); 以上就是最常用的几个方法了,例如 click, type, getValue 等等。还有就是一定要学习 xpath, 其实xpath 也可以有“与、或、非”的操作:java 代码 selenium.check("xpath=//input[(@name='KNYKBN')and(@value='Y')]"); 四、其他selenium 还有更多的用法,例如弹出页面等等。当面对没见过的测试要求时,我最笨的方法就是按照api文档一个一个找,好在不多,肯定能找到。


1.1  下载selenium2.0的lib包1.1  下载selenium2.0的lib包


http://code.google.com/p/selenium/downloads/list


官方User Guide:http://seleniumhq.org/docs/


1.2  用webdriver打开一个浏览器


我们常用的浏览器有firefox和IE两种,firefox是selenium支持得比较成熟的浏览器。但是做页面的测试,速度通常很慢,严重影响持续集成的速度,这个时候建议使用HtmlUnit,不过HtmlUnitDirver运行时是看不到界面的,对调试就不方便了。使用哪种浏览器,可以做成配置项,根据需要灵活配置。


 


打开firefox浏览器:
        //Create a newinstance of the Firefox driver


        WebDriver driver = newFirefoxDriver(); 


打开IE浏览器
        //Create a newinstance of the Internet Explorer driver


        WebDriver driver = newInternetExplorerDriver ();


 打开HtmlUnit浏览器


        //Createa new instance of the Internet Explorer driver    


        WebDriverdriver = new HtmlUnitDriver(); 


1.3  打开测试页面


对页面对测试,首先要打开被测试页面的地址(如:http://www.google.com),web driver 提供的get方法可以打开一个页面:


        // And now use thedriver to visit Google


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


 


1.4  如何找到页面元素


Webdriver的findElement方法可以用来找到页面的某个元素,最常用的方法是用id和name查找。


 假设页面写成这样:


<input type="text" name="passwd"id="passwd-id" /> 


那么可以这样找到页面的元素:


通过id查找:


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


或通过name查找:


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


或通过xpath查找:


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


但页面的元素经常在找的时候因为出现得慢而找不到,建议是在查找的时候等一个时间间隔。


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


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


1.5.1 输入框(text field or textarea)


   找到输入框元素:


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


在输入框中输入内容:


element.sendKeys(“test”);


将输入框清空:


element.clear();


获取输入框的文本内容:


element.getText();


 


1.5.2下拉选择框(Select)


找到下拉选择框的元素:


Select select = new Select(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();


 


1.5.3单选项(Radio Button)


找到单选框元素:


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


选择某个单选项:


bookMode.click();


清空某个单选项:


bookMode.clear();


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


bookMode.isSelected();


1.5.4多选项(checkbox)


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


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


checkbox.click();


checkbox.clear();


checkbox.isSelected();


checkbox.isEnabled();


1.5.5按钮(button)


找到按钮元素:


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


点击按钮:


saveButton.click();


判断按钮是否enable:


 


saveButton.isEnabled ();


1.5.6左右选择框


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


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


lang.selectByVisibleText(“English”);


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


addLanguage.click();


1.5.7弹出对话框(Popup dialogs)


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


alert.accept();


alert.dismiss();


alert.getText();


1.5.8表单(Form)


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


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


approve.click();





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


1.5.9上传文件


上传文件的元素操作:


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


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


adFileUpload.sendKeys(filePath);


1.6  Windows 和 Frames之间的切换


一般来说,登录后建议是先:


driver.switchTo().defaultContent();


切换到某个frame:


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


从一个frame切换到另一个frame:


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


切换到某个window:


driver.switchTo().window("windowName");


 


1.7  调用Java Script


Web driver对Java Script的调用是通过JavascriptExecutor来实现的,例如:


JavascriptExecutor js = (JavascriptExecutor) driver;


        js.executeScript("(function(){inventoryGridMgr.setTableFieldValue('"+ inventoryId + "','" + fieldName + "','"


                + value + "');})()");


1.8  页面等待


页面的操作比较慢,通常需要等待一段时间,页面元素才出现,但webdriver没有提供现成的方法,需要自己写。


等一段时间再对页面元素进行操作:


    public void waitForPageToLoad(longtime) {


        try {


            Thread.sleep(time);


        } catch (Exceptione) {


        }


    }


在找WebElement的时候等待:


   public WebElementwaitFindElement(By by) {


        returnwaitFindElement(by, Long.parseLong(CommonConstant.GUI_FIND_ELEMENT_TIMEOUT),Long


                .parseLong(CommonConstant.GUI_FIND_ELEMENT_INTERVAL));


    }


 


    public WebElementwaitFindElement(By by, long timeout, long interval) {


        long start = System.currentTimeMillis();


        while (true) {


            try {


                return driver.findElement(by);


            } catch(NoSuchElementException nse) {


                if (System.currentTimeMillis()- start >= timeout) {


                    throw newError("Timeout reached and element[" + by + "]not found");


                } else {


                    try {


                        synchronized(this) {


                           wait(interval);


                        }


                    } catch(InterruptedException e) {


                        e.printStackTrace();


                    }


                }


            }


        }


    }


 


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


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


// You may use any WebDriver implementation. Firefox is used hereas an example


WebDriver driver = new FirefoxDriver();


 


// A "base url", used by selenium to resolve relativeURLs


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


 


// Create the Selenium implementation


Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);


 


// Perform actions with selenium


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


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


selenium.click("name=btnG");


 


// Get the underlying WebDriver implementation back. This willrefer to the


// same WebDriver instance as the "driver" variableabove.


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


 


    //Finally, close thebrowser. Call stop on the WebDriverBackedSelenium instance


    //instead of callingdriver.quit(). Otherwise, the JVM will continue running after


    //the browser has beenclosed.


    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");


}

http://code.google.com/p/selenium/downloads/list

官方User Guide:http://seleniumhq.org/docs/

1.2  用webdriver打开一个浏览器

我们常用的浏览器有firefox和IE两种,firefox是selenium支持得比较成熟的浏览器。但是做页面的测试,速度通常很慢,严重影响持续集成的速度,这个时候建议使用HtmlUnit,不过HtmlUnitDirver运行时是看不到界面的,对调试就不方便了。使用哪种浏览器,可以做成配置项,根据需要灵活配置。

 

  1. 打开firefox浏览器:

        //Create a newinstance of the Firefox driver

        WebDriver driver = newFirefoxDriver(); 

  1. 打开IE浏览器

        //Create a newinstance of the Internet Explorer driver

        WebDriver driver = newInternetExplorerDriver ();

 打开HtmlUnit浏览器

        //Createa new instance of the Internet Explorer driver    

        WebDriverdriver = new HtmlUnitDriver(); 

1.3  打开测试页面

对页面对测试,首先要打开被测试页面的地址(如:http://www.google.com),web driver 提供的get方法可以打开一个页面:

        // And now use thedriver to visit Google

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

 

1.4  如何找到页面元素

Webdriver的findElement方法可以用来找到页面的某个元素,最常用的方法是用id和name查找。

 假设页面写成这样:

<input type="text" name="passwd"id="passwd-id" /> 

那么可以这样找到页面的元素:

通过id查找:

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

或通过name查找:

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

或通过xpath查找:

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

但页面的元素经常在找的时候因为出现得慢而找不到,建议是在查找的时候等一个时间间隔。

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

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

1.5.1 输入框(text field or textarea)

   找到输入框元素:

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

在输入框中输入内容:

element.sendKeys(“test”);

将输入框清空:

element.clear();

获取输入框的文本内容:

element.getText();

 

1.5.2下拉选择框(Select)

找到下拉选择框的元素:

Select select = new Select(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();

 

1.5.3单选项(Radio Button)

找到单选框元素:

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

选择某个单选项:

bookMode.click();

清空某个单选项:

bookMode.clear();

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

bookMode.isSelected();

1.5.4多选项(checkbox)

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

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

checkbox.click();

checkbox.clear();

checkbox.isSelected();

checkbox.isEnabled();

1.5.5按钮(button)

找到按钮元素:

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

点击按钮:

saveButton.click();

判断按钮是否enable:

 

saveButton.isEnabled ();

1.5.6左右选择框

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

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

lang.selectByVisibleText(“English”);

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

addLanguage.click();

1.5.7弹出对话框(Popup dialogs)

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

alert.accept();

alert.dismiss();

alert.getText();

1.5.8表单(Form)

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

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

approve.click();

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

1.5.9上传文件

上传文件的元素操作:

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

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

adFileUpload.sendKeys(filePath);

1.6  Windows 和 Frames之间的切换

一般来说,登录后建议是先:

driver.switchTo().defaultContent();

切换到某个frame:

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

从一个frame切换到另一个frame:

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

切换到某个window:

driver.switchTo().window("windowName");

 

1.7  调用Java Script

Web driver对Java Script的调用是通过JavascriptExecutor来实现的,例如:

JavascriptExecutor js = (JavascriptExecutor) driver;

        js.executeScript("(function(){inventoryGridMgr.setTableFieldValue('"+ inventoryId + "','" + fieldName + "','"

                + value + "');})()");

1.8  页面等待

页面的操作比较慢,通常需要等待一段时间,页面元素才出现,但webdriver没有提供现成的方法,需要自己写。

等一段时间再对页面元素进行操作:

    public void waitForPageToLoad(longtime) {

        try {

            Thread.sleep(time);

        } catch (Exceptione) {

        }

    }

在找WebElement的时候等待:

   public WebElementwaitFindElement(By by) {

        returnwaitFindElement(by, Long.parseLong(CommonConstant.GUI_FIND_ELEMENT_TIMEOUT),Long

                .parseLong(CommonConstant.GUI_FIND_ELEMENT_INTERVAL));

    }

 

    public WebElementwaitFindElement(By by, long timeout, long interval) {

        long start = System.currentTimeMillis();

        while (true) {

            try {

                return driver.findElement(by);

            } catch(NoSuchElementException nse) {

                if (System.currentTimeMillis()- start >= timeout) {

                    throw newError("Timeout reached and element[" + by + "]not found");

                } else {

                    try {

                        synchronized(this) {

                           wait(interval);

                        }

                    } catch(InterruptedException e) {

                        e.printStackTrace();

                    }

                }

            }

        }

    }

 

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

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

// You may use any WebDriver implementation. Firefox is used hereas an example

WebDriver driver = new FirefoxDriver();

 

// A "base url", used by selenium to resolve relativeURLs

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

 

// Create the Selenium implementation

Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);

 

// Perform actions with selenium

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

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

selenium.click("name=btnG");

 

// Get the underlying WebDriver implementation back. This willrefer to the

// same WebDriver instance as the "driver" variableabove.

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

 

    //Finally, close thebrowser. Call stop on the WebDriverBackedSelenium instance

    //instead of callingdriver.quit(). Otherwise, the JVM will continue running after

    //the browser has beenclosed.

    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");

}


0 0