Selenium2(webdirver)入門之環境搭建(Java版)
一、開發環境:
1、JDK1.6
2、Eclipse:Version: Kepler Service Release 1,下載地址:http://www.eclipse.org/downloads/
3、Selenium:selenium-java-2.52.0.zip,下載地址:http://docs.seleniumhq.org/download/
解壓selenium-java包,這個包里面包含四部分,如下圖:
二、新建一個Java Project:
1、然后把上面解壓出來的文件拷到新建的project目錄下,目錄結構如下圖:
2、添加build path,項目目錄右鍵-->Build Path--> config build path-->Java Build Path-->Libraries-->Add JARs
把libs文件夾下的jar包全部添加上,再添加selenium-java-2.39.0和selenium-java-2.39.0-srcs
3、添加完之后目錄結構如下圖,多了Referenced Libraries,這里就是上面那一步添加進去的jar包:
4、關聯webdriver的源碼:
至此,環境工作准備就緒,下面來寫一個簡單的小例子。
三、在src下面新建測試類,如下圖:
代碼如下,主要是打開百度,然后在搜索框輸入glen,點擊搜索按鈕,關閉瀏覽器。

1 package com.selenium.Glen; 2 3 import org.openqa.selenium.By; 4 import org.openqa.selenium.WebDriver; 5 import org.openqa.selenium.WebElement; 6 import org.openqa.selenium.firefox.*; 7 8 public class TestHelloWorld { 9 10 public static void main(String[] args) { 11 12 //如果火狐瀏覽器沒有默認安裝在C盤,需要制定其路徑 13 //System.setProperty("webdriver.firefox.bin", "D:/Program Files/Mozilla firefox/firefox.exe"); 14 WebDriver driver = new FirefoxDriver(); 15 driver.get("http://www.baidu.com/"); 16 17 driver.manage().window().maximize(); 18 19 WebElement txtbox = driver.findElement(By.name("wd")); 20 txtbox.sendKeys("Glen"); 21 22 WebElement btn = driver.findElement(By.id("su")); 23 btn.click(); 24 25 driver.close(); 26 27 } 28 29 }
然后直接右鍵-->Run As-->Java Application就可以看到效果了。