`

selenium2.0 入门

 
阅读更多

1.1  下载selenium2.0lib

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

官方User Guidehttp://seleniumhq.org/docs/

1.2  webdriver打开一个浏览器

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

 

<!--[if !supportLists]-->1.     <!--[endif]-->打开firefox浏览器:

        //Create a newinstance of the Firefox driver

        WebDriver driver = newFirefoxDriver(); 

<!--[if !supportLists]-->2.     <!--[endif]-->打开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  如何找到页面元素

WebdriverfindElement方法可以用来找到页面的某个元素,最常用的方法是用idname查找。

 假设页面写成这样:

<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 driverJava 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.0API

Selenium2.0中使用WeDriver API对页面进行操作,它最大的优点是不需要安装一个selenium server就可以运行,但是对页面进行操作不如selenium1.0Selenium 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 APISeleniumRC 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");

}

1.8  超时设置 

WebDriver driver = new FirefoxDriver();

<!--[if !supportLists]-->·         <!--[endif]-->driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);      //识别元素时的超时时间

<!--[if !supportLists]-->·         <!--[endif]-->driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);  //页面加载时的超时时间

<!--[if !supportLists]-->·         <!--[endif]-->driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS);  //异步脚本的超时时间

 

 

 

项目实例:

package com.vcredit.jdev.p2p.account.it;

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;

import org.junit.*;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class RegisterAndLoginIT {
  private WebDriver driver;
  private String baseUrl;
  private boolean acceptNextAlert = true;
  private StringBuffer verificationErrors = new StringBuffer();

  @Before
  public void setUp() throws Exception {
	 // driver = new ChromeDriver();
	  driver = new FirefoxDriver();
	   String hostname = System.getProperty("runtime.websvr.hostname");
	    String port = System.getProperty("runtime.websvr.port");
	    baseUrl = "http://"+hostname+":"+ port;
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  }

  @Test
  public void testLogin() throws Exception {
//	    driver.get(baseUrl + "/#/");
//	    driver.findElement(By.linkText("注册")).click();
//	    driver.findElement(By.name("username")).clear();
//	    driver.findElement(By.name("username")).sendKeys("admindk027");
//	    driver.findElement(By.name("password")).clear();
//	    driver.findElement(By.name("password")).sendKeys("123456");
//	    driver.findElement(By.name("password_confirm")).clear();
//	    driver.findElement(By.name("password_confirm")).sendKeys("123456");
//	    driver.findElement(By.name("_captcha")).clear();
//	    driver.findElement(By.name("_captcha")).sendKeys("12312");
//	    driver.findElement(By.id("mobile")).clear();
//	    driver.findElement(By.id("mobile")).sendKeys("13946858222");
//	    driver.findElement(By.name("mobileVerificationCode")).clear();
//	    driver.findElement(By.name("mobileVerificationCode")).sendKeys("123123");
//	    driver.findElement(By.xpath("//input[@type='checkbox']")).click();
//	    driver.findElement(By.xpath("//button[@type='submit']")).click();
//    driver.findElement(By.linkText("安全退出")).click();
	    driver.get(baseUrl + "/#/");
	    driver.findElement(By.linkText("登录")).click();
	    driver.findElement(By.name("username")).clear();
	    driver.findElement(By.name("username")).sendKeys("admindk027");
	    driver.findElement(By.name("password")).clear();
	    driver.findElement(By.name("password")).sendKeys("123456");
	    driver.findElement(By.name("_captcha")).clear();
	    driver.findElement(By.name("_captcha")).sendKeys("12312");
	    driver.findElement(By.cssSelector("button.btn.f18")).click();
	    driver.findElement(By.xpath("//dl[2]/dd")).click();
  }

  @After
  public void tearDown() throws Exception {
    driver.quit();
    String verificationErrorString = verificationErrors.toString();
    if (!"".equals(verificationErrorString)) {
      fail(verificationErrorString);
    }
  }

  private boolean isElementPresent(By by) {
    try {
      driver.findElement(by);
      return true;
    } catch (NoSuchElementException e) {
      return false;
    }
  }

  private boolean isAlertPresent() {
    try {
      driver.switchTo().alert();
      return true;
    } catch (NoAlertPresentException e) {
      return false;
    }
  }

  private String closeAlertAndGetItsText() {
    try {
      Alert alert = driver.switchTo().alert();
      String alertText = alert.getText();
      if (acceptNextAlert) {
        alert.accept();
      } else {
        alert.dismiss();
      }
      return alertText;
    } finally {
      acceptNextAlert = true;
    }
  }
}

 

分享到:
评论

相关推荐

    selenium2.0入门

    描述selenium2.0的入门知识,环境搭建等

    Selenium 基本介绍文档

    Selenium 1.0 初学者指南.pdf Selenium私房菜(新手入门教程).pdf [零成本实现Web自动化测试-基于Selenium和Bromine].温素剑.pdf Selenium 中文文档 .pdf selenium2.0_中文帮助文档.doc 具体见附件

    selenium_2_testing_tools

    英文版的电子书,从入门开始介绍selenium2.0, 也就是webdriver. 学习selenium webdriver的必备神器!

    selenium 学习资料

    selenium学习资料:Selenium测试实践_基于电子商务平台.pdf,selenium_webdriver-java.pdf,selenium2.0_中文帮助文档.pdf,Selenium定位大全01.pdf,基于Selenium 2的自动化测试 从入门到精通PDF电子书下载 带书签...

    gui 自动化selenium学习资料

    文档中包含gui自动化框架 selenium1.0 资料:selenium私房菜,selenium2.0 资料:selenium2 中文api,中文开发指南及webdriver使用总结文档,适用GUI于自动化开发入门及深入学习的资料

    selenium_tests

    selenium_tests “Selenium 2.0:入门级”课程的作业项目 Php4dvd 应用程序测试项目中有两个测试套件: 严格 - 简写,严格来说是任务中所说的。 扩展 - 扩展,有更多测试并由您自行决定进行,包括负面测试。

    咖啡馆

    它使用WebDriverJS,它是Selenium 2.0 / webdriver的nodejs绑定实现。 量角器默认使用Jasmine作为框架。 入门 要安装testcafe,请运行以下命令: npm install testcafe --save-dev 要安装allure report : npm ...

    s2-php-webdriver:Selenium-Saucelabs (S2) PHP Webdriver

    入门 将s2-php-webdriver的内容复制到您的服务器。 如有必要,修改Test/Base.php的配置设置。 验证您的是否正在运行,然后执行: $ phpunit Test 执照 Selenium-Saucelabs (S2) PHP WebDriver Copyright 2015 ...

    java专题,教学资元 共159g

    包含:socket网络编程及实战,系统学习docker,看的见的算法 7个经典应用诠释算法精髓,一站式学习Redis 从入门到高可用分布式实践,Spring Boot 2.0深度实践之核心技术篇,Scala 学习 进击大数据Spark生态圈,剑指Java面试...

    taurus:通过自动化友好的框架进行连续测试

    Taurus依靠JMeter,Gatling,Locust.io,Grinder和Selenium WebDriver作为其基础工具。 在Apache 2.0许可下免费和开源。 安装或升级 只需使用PyPi安装它: pip install bzt 有关Linux,Mac OS和Windows的更多详细...

    Example-Airflow-DAG:使用Airflow插件中的钩子和运算符的DAG示例

    入门在此找到的示例DAG可以分为三个主要类别:ETL 这些DAG专注于从各种系统中提取数据并将其放入Amazon Redshift,并以S3作为临时存储。 这些代表“ ETL”工作流程的最简单实现,可以“开箱即用”使用,也可以扩展以...

Global site tag (gtag.js) - Google Analytics