http://code.google.com/p/selenium/downloads/listcss
官方User Guide:http://seleniumhq.org/docs/web
咱們經常使用的瀏覽器有firefox和IE兩種,firefox是selenium支持得比較成熟的瀏覽器。可是作頁面的測試,速度一般很慢,嚴重影響持續集成的速度,這個時候建議使用HtmlUnit,不過HtmlUnitDirver運行時是看不到界面的,對調試就不方便了。使用哪一種瀏覽器,能夠作成配置項,根據須要靈活配置。瀏覽器
//Create a newinstance of the Firefox driverapp
WebDriver driver = newFirefoxDriver(); ide
//Create a newinstance of the Internet Explorer driver測試
WebDriver driver = newInternetExplorerDriver ();ui
打開HtmlUnit瀏覽器this
//Createa new instance of the Internet Explorer driver google
WebDriverdriver = new HtmlUnitDriver(); url
對頁面對測試,首先要打開被測試頁面的地址(如:http://www.google.com),web driver 提供的get方法能夠打開一個頁面:
// And now use thedriver to visit Google
driver.get("http://www.google.com");
Webdriver的findElement方法能夠用來找到頁面的某個元素,最經常使用的方法是用id和name查找。
假設頁面寫成這樣:
<input type="text" name="passwd"id="passwd-id" />
那麼能夠這樣找到頁面的元素:
經過id查找:
WebElement element = driver.findElement(By.id("passwd-id"));
或經過name查找:
WebElement element = driver.findElement(By.name("passwd"));
或經過xpath查找:
WebElement element =driver.findElement(By.xpath("//input[@id='passwd-id']"));
但頁面的元素常常在找的時候由於出現得慢而找不到,建議是在查找的時候等一個時間間隔。
找到頁面元素後,怎樣對頁面進行操做呢?咱們能夠根據不一樣的類型的元素來進行一一說明。
找到輸入框元素:
WebElement element = driver.findElement(By.id("passwd-id"));
在輸入框中輸入內容:
element.sendKeys(「test」);
將輸入框清空:
element.clear();
獲取輸入框的文本內容:
element.getText();
找到下拉選擇框的元素:
Select select = new Select(driver.findElement(By.id("select"))); 選擇對應的選擇項:
select.selectByVisibleText(「mediaAgencyA」);
或
select.selectByValue(「MA_ID_001」);
不選擇對應的選擇項:
select.deselectAll();
select.deselectByValue(「MA_ID_001」);
select.deselectByVisibleText(「mediaAgencyA」);
或者獲取選擇項的值:
select.getAllSelectedOptions();
select.getFirstSelectedOption();
找到單選框元素:
WebElement bookMode =driver.findElement(By.id("BookMode"));
選擇某個單選項:
bookMode.click();
清空某個單選項:
bookMode.clear();
判斷某個單選項是否已經被選擇:
bookMode.isSelected();
多選項的操做和單選的差很少:
WebElement checkbox = driver.findElement(By.id("myCheckbox."));
checkbox.click();
checkbox.clear();
checkbox.isSelected();
checkbox.isEnabled();
找到按鈕元素:
WebElement saveButton = driver.findElement(By.id("save"));
點擊按鈕:
saveButton.click();
判斷按鈕是否enable:
saveButton.isEnabled ();
也就是左邊是可供選擇項,選擇後移動到右邊的框中,反之亦然。例如:
Select lang = new Select(driver.findElement(By.id("languages")));
lang.selectByVisibleText(「English」);
WebElement addLanguage =driver.findElement(By.id("addButton"));
addLanguage.click();
Alert alert = driver.switchTo().alert();
alert.accept();
alert.dismiss();
alert.getText();
Form中的元素的操做和其它的元素操做同樣,對元素操做完成後對錶單的提交能夠:
WebElement approve = driver.findElement(By.id("approve"));
approve.click();
或
approve.submit();//只適合於表單的提交
上傳文件的元素操做:
WebElement adFileUpload =driver.findElement(By.id("WAP-upload"));
String filePath = "C:\test\\uploadfile\\media_ads\\test.jpg";
adFileUpload.sendKeys(filePath);
通常來講,登陸後建議是先:
driver.switchTo().defaultContent();
切換到某個frame:
driver.switchTo().frame("leftFrame");
從一個frame切換到另外一個frame:
driver.switchTo().frame("mainFrame");
切換到某個window:
driver.switchTo().window("windowName");
Web driver對Java Script的調用是經過JavascriptExecutor來實現的,例如:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("(function(){inventoryGridMgr.setTableFieldValue('"+ inventoryId + "','" + fieldName + "','"
+ value + "');})()");
頁面的操做比較慢,一般須要等待一段時間,頁面元素纔出現,但webdriver沒有提供現成的方法,須要本身寫。
等一段時間再對頁面元素進行操做:
public void waitForPageToLoad(longtime) {
try {
Thread.sleep(time);
} catch (Exceptione) {
}
}
在找WebElement的時候等待:
public WebElementwaitFindElement(By by) {
returnwaitFindElement(by, Long.parseLong(CommonConstant.GUI_FIND_ELEMENT_TIMEOUT),Long
.parseLong(CommonConstant.GUI_FIND_ELEMENT_INTERVAL));
}
public WebElementwaitFindElement(By by, long timeout, long interval) {
long start = System.currentTimeMillis();
while (true) {
try {
return driver.findElement(by);
} catch(NoSuchElementException nse) {
if (System.currentTimeMillis()- start >= timeout) {
throw newError("Timeout reached and element[" + by + "]not found");
} else {
try {
synchronized(this) {
wait(interval);
}
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Selenium2.0中使用WeDriver API對頁面進行操做,它最大的優勢是不須要安裝一個selenium server就能夠運行,可是對頁面進行操做不如selenium1.0的Selenium RC API那麼方便。Selenium2.0提供了使用Selenium RC API的方法:
// You may use any WebDriver implementation. Firefox is used hereas an example
WebDriver driver = new FirefoxDriver();
// A "base url", used by selenium to resolve relativeURLs
String baseUrl ="http://www.google.com";
// Create the Selenium implementation
Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);
// Perform actions with selenium
selenium.open("http://www.google.com");
selenium.type("name=q", "cheese");
selenium.click("name=btnG");
// Get the underlying WebDriver implementation back. This willrefer to the
// same WebDriver instance as the "driver" variableabove.
WebDriver driverInstance = ((WebDriverBackedSelenium)selenium).getUnderlyingWebDriver();
//Finally, close thebrowser. Call stop on the WebDriverBackedSelenium instance
//instead of callingdriver.quit(). Otherwise, the JVM will continue running after
//the browser has beenclosed.
selenium.stop();
我分別使用WebDriver API和SeleniumRC API寫了一個Login的腳本,很明顯,後者的操做更加簡單明瞭。
WebDriver API寫的Login腳本:
public void login() {
driver.switchTo().defaultContent();
driver.switchTo().frame("mainFrame");
WebElement eUsername= waitFindElement(By.id("username"));
eUsername.sendKeys(manager@ericsson.com);
WebElement ePassword= waitFindElement(By.id("password"));
ePassword.sendKeys(manager);
WebElementeLoginButton = waitFindElement(By.id("loginButton"));
eLoginButton.click();
}
SeleniumRC API寫的Login腳本:
public void login() {
selenium.selectFrame("relative=top");
selenium.selectFrame("mainFrame");
selenium.type("username","manager@ericsson.com");
selenium.type("password","manager");
selenium.click("loginButton");
}