selenium java環境的安裝能夠分爲三個部分:jdk、eclipse和selenium.java
Jdk
web
jdk(java development kit)是sun公司針對java開發人員的產品,是整個java的核心,包含了java的運行環境、工具和基礎類庫。chrome
1.下載新版jdk,目前是jdk8,雙擊安裝便可,選擇安裝在D:\Program Files\Java\jdk1.8.0.windows
2.配置環境變量eclipse
3.運行cmd查看jdk版本工具
Eclipse
測試
eclipse無需多解釋,windows傻瓜式安裝,安裝完成後測試一下便可google
Selenium
spa
咱們一共須要三個文件selenium-server-standalone-2.40.0.jar、selenium-java-2.40.0.jar和selenium-java-2.40.0-srcs.jar,可自行到selenium官網下載。code
在test.java中寫入測試代碼
package test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class test { public static void main(String[] args) { WebDriver driver = new ChromeDriver(); driver.get("http://shanghai.anjuke.com"); System.out.println("Page title is: " + driver.getTitle()); } }
不出意外的報錯了,查看錯誤信息The path to the driver executable must be set by the webdriver.chrome.driver system property; 原來是沒有預先設置chrome的地址遂設置之,注意chromedriver.exe是google提供的驅動器須要另外下載並放在chrome安裝目錄下。
package test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class test { public static void main(String[] args) { //設置chromedriver地址 System.setProperty ( "webdriver.chrome.driver" , "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe" ); WebDriver driver = new ChromeDriver(); driver.get("http://shanghai.anjuke.com"); System.out.println("Page title is: " + driver.getTitle()); } }
運行之,成功輸出了網頁標題
再試試搜索功能
package test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class test { public static void main(String[] args) { //設置chromedriver地址 System.setProperty ( "webdriver.chrome.driver" , "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe" ); WebDriver driver = new ChromeDriver(); driver.get("http://shanghai.anjuke.com"); WebElement input = driver.findElement(By.xpath("//input[@id='glb_search0']")); CharSequence[] cs= new CharSequence[1]; cs[0] = "上海"; input.sendKeys(cs); WebElement btn = driver.findElement(By.xpath("//input[@id='btnSubmit']")); btn.click(); System.out.println("Page title is: " + driver.getTitle()); } }
上述代碼中import的類包在selenium-java-2.40.0.jar文件中,可自行查看源碼。