使用selenium做自动化测试入门-基于JAVA

栏目: 编程工具 · 发布时间: 6年前

内容简介:使用selenium做自动化测试入门-基于JAVA

Posted on 2017 年 6 月 14 日

之前在使用 JAVA 做爬虫的时候,有遇到一个问题,就是有些网站,必须要浏览器运行,然后JS执行.内容才能显示出来.遇到这种站,代码直接就趴了,内容抓取不到.网上找了一下发现有一个叫selenium的,可以模拟浏览器行为,做自动化测试.感觉这个应该挺好玩的.难得今天有时间.玩了一把.确实不错

官方网站: http://www.seleniumhq.org/
 
官方代码仓库: https://github.com/SeleniumHQ/selenium

我的项目使用的依赖管理 工具 是maven,下面给出Selenium的maven地址

        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.4.0</version>
        </dependency>
<!-- 大家平时找jar包可以在这个网站:https://mvnrepository.com/ 去查询,非常好用 -->

然后写一个入门测试的程序

package org.linuxsogood.reference.chp1.selenium;
 
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
 
/**
 * Created by honway on 2017/6/14 10:44.
 * 
 */
public class Demo1 {
 
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "C:\\opt\\driver\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("http://192.168.0.227:7700/");
        WebElement username = driver.findElement(By.xpath("//*[@id=\"loginForm\"]/div/div[2]/input"));
        username.sendKeys("123456");
        WebElement passwd = driver.findElement(By.xpath("//*[@id=\"loginForm\"]/div/div[3]/input"));
        passwd.sendKeys("123456");
        driver.findElement(By.xpath("//*[@id=\"loginForm\"]/div/div[5]/button")).submit();
        driver.findElement(By.xpath("//*[@id=\"menu_li\"]/li[2]/a")).click();
        Thread.sleep(2000);
        driver.findElement(By.xpath("//*[@id=\"menu_li\"]/li[2]/ul/li[9]")).click();
    }
}

由于selenium的运行是基于浏览器的,所以这里要下载一个webdriver,把下载下来的webDriver放到一个目录里面,然后使用System工具类设置一下系统变量,指向这个webDriver

对于每一种浏览器,都会有一个webDriver, 其实这个webDriver就是一个浏览器的驱动.用它来控制我们本地安装的对应的浏览器.我例子当中使用的是chrome的驱动器.

请注意:这里只需要设置驱动器对应的环境变量,不是你的chrome浏览器程序的exe文件所在的位置.是你下载的驱动器程序的位置.

附上官方的驱动器下载地址 http://chromedriver.storage.googleapis.com/index.html

使用selenium做自动化测试入门-基于JAVA

程序中有一个线程暂停了2秒的代码,是因为点击菜单,它有一个动画效果,如果不暂时一会儿再点击,就会选择不到元素,从而抛出异常.


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Effective Engineer

The Effective Engineer

Edmond Lau / The Effective Bookshelf, Palo Alto, CA. / 2015-3-19 / USD 39.00

Introducing The Effective Engineer — the only book designed specifically for today's software engineers, based on extensive interviews with engineering leaders at top tech companies, and packed with h......一起来看看 《The Effective Engineer》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

在线进制转换器
在线进制转换器

各进制数互转换器

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试