java用selenium库控制chrome

一.简介

selenium是浏览器自动化工具,可以通过程序来控制浏览器行为,这就是selenium!你可以用它做任何你想做的事情.很多时候人们用它测试web应用,但selenium的用途绝不仅限于此.selenium拥有大多数浏览器厂商的支持,它可以驱动大多数浏览器.selenium的原理很简单,浏览器本身就提供了自动化接口,selenium只是把这些接口封装了一下,以统一的形式来编程,不必每个浏览器编一套程序.

selenium-RemoteControl已经被slenium-WebDriver所替代,selenium-RC已经不鼓励使用了.selenium IDE是一个firefox插件,可以方便地录制用户操作,是一个可视化插件.

要想使用selenium控制浏览器,可能需要浏览器提供的相应的驱动程序,如chrome就需要chrome-driver.在selenium官网上提供了与selenium有关的第三方工具.http://docs.seleniumhq.org/download/

selenium对于firefox支持得最好,有一个firefox插件selenium IDE,这个插件只能在firefox下使用.

selenium的主要用途是测试软件,当然也可以干别的事.比如爬取需要手动输入验证码的网站.

selenium是用java语言编写的,但是提供java,C#,python,nodeJS等语言的调用接口,也有第三方实现的selenium接口.

selenium可以通过命令行方式交互式执行,也可以通过编写程序执行.

htmlUnit是一个用java语言编写的模拟浏览器,但是它不是真正的浏览器,它连个界面都没有,只是一个模拟的浏览器.它对于js和css支持的不够完善,功能上肯定比不上真正的浏览器,但是它速度快,有时候是非常有用的.关键是它是基于java的浏览器.在使用selenium时,浏览器就可以使用htmlUnit作为浏览器,它的优点就是速度快.

二.下载

1.下载chrome-webdriver

在selenium官网上的download页面中提供了chrome-webdriver的下载链接.

https://sites.google.com/a/chromium.org/chromedriver/downloads

如果这个链接失效了,请百度"selenium chrome"

如果不下载chrome-webdriver,而直接写chrome.exe的路径,会报错

[1020:6356:1004/173348:ERROR:cache_util_win.cc(20)] Unable to move the cache: 0
[1020:6356:1004/173348:ERROR:cache_util.cc(134)] Unable to move cache folder C:UsersweidiaoAppDataLocalGoogleChromeUser DataShaderCacheGPUCache to C:UsersweidiaoAppDataLocalGoogleChromeUser DataShaderCacheold_GPUCache_000
[1020:6356:1004/173348:ERROR:cache_creator.cc(134)] Unable to create cache
[1020:6356:1004/173348:ERROR:shader_disk_cache.cc(589)] Shader Cache Creation failed: -2

2.下载jar包

可以使用maven,selenium-server这个jar包依赖selenium-java这个jar包,selenium-java又依赖大量的其他库.使用maven可以省去许多时间.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>MySel20Proj</groupId>
        <artifactId>MySel20Proj</artifactId>
        <version>1.0</version>
        <dependencies>
            <dependency>
                <groupId>org.seleniumhq.selenium</groupId>
                <artifactId>selenium-server</artifactId>
                <version>3.0.0-beta4</version>
            </dependency>
        </dependencies>
</project>

因为selenium-java依赖的库特别多,所以需要导入很多jar包.从官网上下载selenium-java,把解压后文件夹中的全部jar包导入即可开始编写java代码了.

三.第一个selenium程序

    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver",
                "C:\Users\weidiao\Desktop\chromedriver_win32\chromedriver.exe");
        WebDriver webDriver = new ChromeDriver();
        webDriver.manage().window().maximize();
        webDriver.get("http://www.baidu.com");
        WebElement kw = webDriver.findElement(By.id("kw"));
        kw.sendKeys("暗算");
        WebElement su = webDriver.findElement(By.id("su"));
        su.click();
        //webDriver.close();
        System.out.println("Hello World!");
    }

运行这个程序,就会打开百度,输入"暗算",点击搜索按钮.

四.API简介

要看selenium api,不要看博客,直接去官网上的documents页面查看api.

1.等待某个条件完成

有时需要等待浏览器运行js结束之后,再分析html页面.new出来一个WebDriverWait对象,调用它的until(ExpectedCondition<>condition)函数.

        // Google's search is rendered dynamically with JavaScript.
        // Wait for the page to load, timeout after 10 seconds
        (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                return d.getTitle().toLowerCase().startsWith("cheese!");
            }
        });

2.获取元素

//通过id
WebElement element = driver.findElement(By.id("coolestWidgetEvah"));
//通过className
List<WebElement> cheeses = driver.findElements(By.className("cheese"));
//通过tagName
WebElement frame = driver.findElement(By.tagName("iframe"));
//通过name
WebElement cheese = driver.findElement(By.name("cheese"));
//通过linkText
<a href="http://www.google.com/search?q=cheese">cheese</a>
WebElement cheese = driver.findElement(By.linkText("cheese"));
//通过部分linkText
<a href="http://www.google.com/search?q=cheese">search for cheese</a>
WebElement cheese = driver.findElement(By.partialLinkText("cheese"));
//通过css
<div id="food"><span class="dairy">milk</span><span class="dairy aged">cheese</span></div>
WebElement cheese = driver.findElement(By.cssSelector("#food span.dairy.aged"));
//通过xpath,比较麻烦
//通过javaScript
WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("return $('.cheese')[0]");
List<WebElement> labels = driver.findElements(By.tagName("label"));
List<WebElement> inputs = (List<WebElement>) ((JavascriptExecutor)driver).executeScript(
    "var labels = arguments[0], inputs = []; for (var i=0; i < labels.length; i++){" +
    "inputs.push(document.getElementById(labels[i].getAttribute('for'))); } return inputs;", labels);

 3.操作元素

一个WebElement可以对应html很多控件,如按钮,单选按钮(select和deselect,click),复选按钮(跟单选按钮差不多),表单(submit),文件上传可以进行上传文件(sendKeys)
 除了WebElement还有Select,表示多选的下拉列表.

原文地址:https://www.cnblogs.com/weiyinfu/p/5930468.html