一.简介

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:\Users\weidiao\AppData\Local\Google\Chrome\User Data\ShaderCache\GPUCache to C:\Users\weidiao\AppData\Local\Google\Chrome\User Data\ShaderCache\old_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出来一个WebDriver对象,调用它的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,表示多选的下拉列表.

java用selenium库控制chrome的更多相关文章

  1. Java使用Selenium几个例子

    零.姿势 Selenium分为两个版本:Selenium RC和Selenium Webdriver.现在用Selenium Webdriver比较多. Selenium是一套工具,而不仅仅是一个操纵 ...

  2. Python 中 selenium 库

    目录 selenium 基础语法 一. 环境配置 1. 安装环境 2. 配置参数 3. 常用参数搭配 4. 分浏览器启动 二. 基本语法 1. 元素定位 2. 控制浏览器操作 3. 操作元素的方法 3 ...

  3. python爬虫---selenium库的用法

    python爬虫---selenium库的用法 selenium是一个自动化测试工具,支持Firefox,Chrome等众多浏览器 在爬虫中的应用主要是用来解决JS渲染的问题. 1.使用前需要安装这个 ...

  4. 浅谈python中selenium库调动webdriver驱动浏览器的实现原理

    最近学web自动化时用到selenium库,感觉很神奇,遂琢磨了一下,写了点心得. 当我们输入以下三行代码并执行时,会发现新打开了一个浏览器窗口并访问了百度首页,然而这是怎么做到的呢? from se ...

  5. Java 框架、库和软件的精选列表(awesome java)

    原创翻译,原始链接 本文为awesome系列中的awesome java Awesome Java Java 框架.库和软件的精选列表 项目 Bean映射 简化 bean 映射的框架 dOOv - 为 ...

  6. 为采集动态网页安装和测试Python Selenium库

    1. 引言上一篇<为编写网络爬虫程序安装Python3.5>中测试小例子对静态网页做了一个简单的采集程序,而动态网页因为需要动态加载js获取数据,所以使用urllib直接openurl已经 ...

  7. python利用selenium库识别点触验证码

    利用selenium库和超级鹰识别点触验证码(学习于静谧大大的书,想自己整理一下思路) 一.超级鹰注册:超级鹰入口 1.首先注册一个超级鹰账号,然后在超级鹰免费测试地方可以关注公众号,领取1000积分 ...

  8. java.util.stream 库简介

    Java Stream简介 Java SE 8 中主要的新语言特性是拉姆达表达式.可以将拉姆达表达式想作一种匿名方法:像方法一样,拉姆达表达式具有带类型的参数.主体和返回类型.但真正的亮点不是拉姆达表 ...

  9. selenium 定制启动 chrome 的选项

    序 使用 selenium 时,我们可能需要对 chrome 做一些特殊的设置,以完成我们期望的浏览器行为,比如阻止图片加载,阻止JavaScript执行 等动作.这些需要 selenium的 Chr ...

随机推荐

  1. position: fixed用在iframe里面失效了

    iframe真是各种坑啊,,,可是找不到别的代替 $(parent.window).scroll(function(){ $('固定元素').css({ top : $(parent.window). ...

  2. 在C#开发中如何使用Client Object Model客户端代码获得SharePoint 网站、列表的权限情况

    自从人类学会了使用火,烤制的方式替代了人类的消化系统部分功能,从此人类的消化系统更加简单,加速了人脑的进化:自从SharePoint 2010开始有了Client Side Object Model ...

  3. Sharepoint学习笔记—习题系列--70-576习题解析 -(Q99-Q101)

    Question  99 You have designed a new SharePoint 2010 Web Part that was deployed to the testing envir ...

  4. iOS用三种途径实现一方法有多个返回值

    以前觉得这种标题有点偏向于理论,实际开发中怎么会有这种诡异的需求,但是真正遇到了这种硬需求时觉得还是有那么点价值的,理论付诸了实践在此也就做了个整理. 以我私下开发中的一处代码为例,本意是希望有这么一 ...

  5. Android 滑动菜单框架--SwipeMenuListView框架完全解析

    SwipeMenuListView(滑动菜单) A swipe menu for ListView.--一个非常好的滑动菜单开源项目. Demo 一.简介 看了挺长时间的自定义View和事件分发,想找 ...

  6. pod的SDK报错,Linker command failed with exit code1(use -v to see invocation)

    错误1789个重复的符号: 原因是我用cocopads 导入了重复的SDK 环信的SDK EaseMobSDK: 不包含语音的 EaseMobSDKFull: 包含语音的  在Podfile中将导入E ...

  7. 初学HTML 常见的标签(三) 插入类标签

    第三篇博客, 这次说的是插入链接类标签, 我们平常在网页中经常能看到蓝色的链接类标签, 或者是一张图片, 一个电邮, 这些都是插入链接类的标签起的作用. <a></a>链接标签 ...

  8. iOS 学习 - 19 结构体

    //创建新类型typedef struct { int age; ];//最大字节为 20 }Student; Student value2 = {,*strcpy(value2.name, &quo ...

  9. border 外边框

    语法: border:<line-width> || <line-style> || <color> <line-width> = <length ...

  10. linux下重启服务命令

    1.查找进程id命令 ps -ef | grep -v grep|grep bdse-tour-service-1.0-jar-with-dependencies.jar | awk '{print ...