Selenium基础教程----基于Java(一)

来源:互联网 发布:音画制作软件 编辑:程序博客网 时间:2024/06/15 06:57

什么是Selenium

“Test Automation for Web Applications”—-来自Selenium官网

通过官网的描述,可以看出Selenium就是执行网络应用的自动化测试,目前绝大多数的应用软件都是基于web开发的应用程序,需要使用浏览器来打开应用,那么对这些应用程序的测试的需求就越来越大。Selenium就是这么一个帮助企业和组织进行web-app自动化测试的工具。
Selenium2开始使用WebDriver,相比于Selenium-RC,WebDriver更直接的使用浏览器,进而实现更强的自动化测试。


如何获取Selenium

本文基于Java语言介绍,其他语言的获取方式请查看官网Selenium官网

官网推荐使用Maven来获取Selenium,只需要在pom.xml 中配置好依赖即可,我们截取依赖部分如下:

<dependency>    <groupId>org.seleniumhq.selenium</groupId>    <artifactId>selenium-server</artifactId>    <version>3.0.1</version></dependency>

如果未使用IDEA或者Eclipse的IDE环境,还需要执行mvn命令:

mvn clean install

这样就可以在自己的项目下导入selenium进而使用。


实例Demo

package org.openqa.selenium.example;import org.openqa.selenium.By;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.firefox.FirefoxDriver;import org.openqa.selenium.support.ui.ExpectedCondition;import org.openqa.selenium.support.ui.WebDriverWait;public class Selenium2Example  {    public static void main(String[] args) {        // 创建一个火狐浏览器WebDriver的新实例        // 注意代码的剩余部分都是依赖于这个接口,而不是这个接口的实现        WebDriver driver = new FirefoxDriver();        // 然后使用刚刚创建的FirefoxWebDriver来访问百度首页        driver.get("http://www.baidu.com");        // 或者我们可以使用下面的代码完成上面相同的功能(后面我们会具体介绍navigate)        // driver.navigate().to("http://www.baidu.com");        // 通过name参数来找到文本输入框的元素位置        WebElement element = driver.findElement(By.name("wd"));        // 找到文本输入框元素后,我们输入一些信息来为搜索做准备        element.sendKeys("中国");        // 现在开始提交表单,WebDriver会通过定位到的元素为我们找到表单        element.submit();        // 检查页面的title        System.out.println("Page title is: " + driver.getTitle());        // 百度的页面会通过JavaScript动态渲染        // 等待页面加载完成,并且设置了10秒的超时检查。        (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {            public Boolean apply(WebDriver d) {                return d.getTitle().toLowerCase().startsWith("中国!");            }        });        //会打印出"中国_百度搜索"        System.out.println("Page title is: " + driver.getTitle());        //关闭浏览器        driver.quit();    }}

后面开始介绍Selenium WebDriver的API

原创粉丝点击