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

什么是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

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值