自从上次的
Selenium教程之下载安装与配置以后受到了很大的欢迎,iquicktest这边也收到了不少网友的一些反馈和问题,其中提到最多的就是如何使用selenium-webdriver来驱动chrome浏览器(看来目前使用chrome浏览器的真不在少数),那么我们再次简单介绍下如何来驱动Chrome浏览器。
很多网友在看过上次的教程之后尝试着将
WebDriver driver =
new
FireFoxDriver();
替换成
WebDriver driver = new ChromeDriver();
但是最终却发现无法成功驱动Chrome浏览器,并且提示错误:
The path to the driver executable must be set by the webdriver.chrome.driver system property;
那么我们如何来解决这样的问题呢?
其实要驱动chrome浏览器必须要依赖Chromedriver文件才行,
下载地址:
http://code.google.com/p/chromedriver/downloads/list
找到适合你自己系统的包之后下载解压出Chromedriver文件,并将此文件拷贝到
java项目的根目录。还是拿上此教程的为例,我们直接爸chromedriver文件拷贝到HelloSelenium项目的根目录下也就是HelloSelenium目录下。这样就可以直接运行了。
package com.iquicktest;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class HelloSelenium {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//实例化Firefox Driver
WebDriver driver = new ChromeDriver();
//跳转到baidu首页
driver.get("http://www.baidu.com");
//对象识别
By tbSearchElement = By.name("wd");
By btnSearchElement = By.xpath("//input[@value='百度一下']");
WebElement tbSearch = driver.findElement(tbSearchElement);
WebElement btnSearch = driver.findElement(btnSearchElement);
//对象操作
tbSearch.sendKeys("iquicktest");
btnSearch.click();
driver.close();
}
}
如上脚本即可打开chrome浏览器并进行一系列自动化操作,这里的脚本还是沿用了上次课程的脚本,有问题的朋友可以回看上一次的教程。
这里注意一下,如果你不希望把chromedriver拷贝到项目根目录下,也可以直接进行指定路径,使用如下脚本:
System.setProperty("webdriver.chrome.driver", "e:/chromedriver");
如果chrome浏览器安装不在默认路径下, 也可以直接指定路径 System.setProperty("webdriver.chrome.bin", "D:\\Program Files\\Internet Explorer\\iexplore.exe")