1.1 下載selenium2.0的lib包
http://code.google.com/p/selenium/downloads/list
官方User Guide:http://seleniumhq.org/docs/
1、MouseOver嘗試
selenium.mouseOver(db.getElementXpath("tool_printerInfo_Image"));
MySelenium.CpaturePicture(selenium,browser, "90601002");
result.resultOfIsTrue(selenium.isTextPresent("HPENVY 120 series"));
assertTrue(result.isResult());
1.2 用webdriver打開一個瀏覽器
我們常用的瀏覽器有firefox和IE兩種,firefox是selenium支持得比較成熟的瀏覽器。但是做頁面的測試,速度通常很慢,嚴重影 響持續集成的速度,這個時候建議使用HtmlUnit,不過HtmlUnitDirver運行時是看不到界面的,對調試就不方便了。使用哪種瀏覽器,可以 做成配置項,根據需要靈活配置。
- 打開firefox瀏覽器:
//Create a newinstance of the Firefox driver
WebDriver driver = newFirefoxDriver();
- 打開IE瀏覽器
//Create a newinstance of the Internet Explorer driver
WebDriver driver = newInternetExplorerDriver ();
打開HtmlUnit瀏覽器
//Createa new instance of the Internet Explorer driver
WebDriverdriver = new HtmlUnitDriver();
1.3 打開測試頁面
對頁面對測試,首先要打開被測試頁面的地址(如:http://www.google.com),web driver 提供的get方法可以打開一個頁面:
// And now use thedriver to visit Google
driver.get("http://www.google.com");
1.4 如何找到頁面元素
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']"));
但頁面的元素經常在找的時候因爲出現得慢而找不到,建議是在查找的時候等一個時間間隔。
1.5 如何對頁面元素進行操作
找到頁面元素後,怎樣對頁面進行操作呢?我們可以根據不同的類型的元素來進行一一說明。
1.5.1輸入框(text fieldor textarea)
找到輸入框元素:
WebElement element =driver.findElement(By.id("passwd-id"));
在輸入框中輸入內容:
element.sendKeys(“test”);
將輸入框清空:
element.clear();
獲取輸入框的文本內容:
element.getText();
1.5.2下拉選擇框(Select)
找到下拉選擇框的元素:
Select select = newSelect(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();
1.5.3單選項(Radio Button)
找到單選框元素:
WebElement bookMode=driver.findElement(By.id("BookMode"));
選擇某個單選項:
bookMode.click();
清空某個單選項:
bookMode.clear();
判斷某個單選項是否已經被選擇:
bookMode.isSelected();
1.5.4多選項(checkbox)
多選項的操作和單選的差不多:
WebElement checkbox =driver.findElement(By.id("myCheckbox."));
checkbox.click();
checkbox.clear();
checkbox.isSelected();
checkbox.isEnabled();
1.5.5按鈕(button)
找到按鈕元素:
WebElement saveButton =driver.findElement(By.id("save"));
點擊按鈕:
saveButton.click();
判斷按鈕是否enable:
saveButton.isEnabled ();
1.5.6左右選擇框
也就是左邊是可供選擇項,選擇後移動到右邊的框中,反之亦然。例如:
Select lang = newSelect(driver.findElement(By.id("languages")));
lang.selectByVisibleText(“English”);
WebElement addLanguage=driver.findElement(By.id("addButton"));
addLanguage.click();
1.5.7彈出對話框(Popup dialogs)
Alert alert =driver.switchTo().alert();
alert.accept();
alert.dismiss();
alert.getText();
1.5.8表單(Form)
Form中的元素的操作和其它的元素操作一樣,對元素操作完成後對錶單的提交可以:
WebElement approve =driver.findElement(By.id("approve"));
approve.click();
或
approve.submit();//只適合於表單的提交
1.5.9上傳文件
上傳文件的元素操作:
WebElement adFileUpload=driver.findElement(By.id("WAP-upload"));
String filePath ="C:\test\\uploadfile\\media_ads\\test.jpg";
adFileUpload.sendKeys(filePath);
1.6 Windows和 Frames之間的切換
一般來說,登錄後建議是先:
driver.switchTo().defaultContent();
切換到某個frame:
driver.switchTo().frame("leftFrame");
從一個frame切換到另一個frame:
driver.switchTo().frame("mainFrame");
切換到某個window:
driver.switchTo().window("windowName");
1.7 調用Java Script
Web driver對Java Script的調用是通過JavascriptExecutor來實現的,例如:
JavascriptExecutor js =(JavascriptExecutor) driver;
js.executeScript("(function(){inventoryGridMgr.setTableFieldValue('"+inventoryId + "','" + fieldName + "','"
+ value + "');})()");
1.8 頁面等待
頁面的操作比較慢,通常需要等待一段時間,頁面元素纔出現,但webdriver沒有提供現成的方法,需要自己寫。
等一段時間再對頁面元素進行操作:
public voidwaitForPageToLoad(longtime) {
try {
Thread.sleep(time);
} catch (Exceptione) {
}
}
在找WebElement的時候等待:
publicWebElementwaitFindElement(By by) {
returnwaitFindElement(by, Long.parseLong(CommonConstant.GUI_FIND_ELEMENT_TIMEOUT),Long
.parseLong(CommonConstant.GUI_FIND_ELEMENT_INTERVAL));
}
publicWebElementwaitFindElement(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 + "]notfound");
} else {
try {
synchronized(this) {
wait(interval);
}
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
1.9 在selenium2.0中使用selenium1.0的API
Selenium2.0中使用WeDriver API對頁面進行操作,它最大的優點是不需要安裝一個selenium server就可以運行,但是對頁面進行操作不如selenium1.0的Selenium RC API那麼方便。Selenium2.0提供了使用Selenium RC API的方法:
// You may use any WebDriverimplementation. Firefox is used hereas an example
WebDriver driver = newFirefoxDriver();
// A "base url", used byselenium to resolve relativeURLs
String baseUrl="http://www.google.com";
// Create the Seleniumimplementation
Selenium selenium = newWebDriverBackedSelenium(driver, baseUrl);
// Perform actions with selenium
selenium.open("http://www.google.com");
selenium.type("name=q","cheese");
selenium.click("name=btnG");
// Get the underlying WebDriverimplementation back. This willrefer to the
// same WebDriver instance as the"driver" variableabove.
WebDriver driverInstance =((WebDriverBackedSelenium)selenium).getUnderlyingWebDriver();
//Finally, closethebrowser. Call stop on the WebDriverBackedSelenium instance
//instead ofcallingdriver.quit(). Otherwise, the JVM will continue running after
//the browser hasbeenclosed.
selenium.stop();
我分別使用WebDriver API和SeleniumRC API寫了一個Login的腳本,很明顯,後者的操作更加簡單明瞭。
WebDriver API寫的Login腳本:
public voidlogin() {
driver.switchTo().defaultContent();
driver.switchTo().frame("mainFrame");
WebElement eUsername= waitFindElement(By.id("username"));
eUsername.sendKeys([email protected]);
WebElement ePassword= waitFindElement(By.id("password"));
ePassword.sendKeys(manager);
WebElementeLoginButton = waitFindElement(By.id("loginButton"));
eLoginButton.click();
}
SeleniumRC API寫的Login腳本:
public voidlogin() {
selenium.selectFrame("relative=top");
selenium.selectFrame("mainFrame");
selenium.type("username","[email protected]");
selenium.type("password","manager");
selenium.click("loginButton");
}
右鍵點擊:
Actions action = new Actions(driver); action.contextClick(driver.findElement(By.xpath("/html/body/div/div[2]/div[2]/div/div/div/div/div/div/div[2]/ul/li/ul/li[2]/ul/li/ul/li[5]/div/a/span"))).perform();
元素移動
Actions builder = newActions(driver); builder.moveToElement(driver.findElement(By.xpath("/html/body/div[6]/div/div/form/div[3]/div[2]/div/div/div/div[2]/div/table/tbody/tr/td/table/tbody/tr/td[3]/table/tbody/tr[2]/td[2]/em/button"))).perform();
元素雙擊
builder.doubleClick(onElement)
WebDriver實現窗體的最大化
最優方法:driver.manage().window().maximize();
@Test
@Parameters( { "webSite" })
publicvoid setUp_ChromeDriver(String webSite) throws Exception {
//.\\lib\\IEDriverServer.exe 是lib目錄下的驅動
System.setProperty("webdriver.chrome.driver","./lib/chromedriver.exe");
driver = new ChromeDriver();
maximise(driver);
Thread.sleep(2000);
baseUrl = webSite;
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
script(driver);
}
//使窗口最大化函數,通過檢測顯示器的寬和高來實現
publicstaticvoid maximise(WebDriver driver) {
final JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.open('','testwindow','width=400,height=200')");
driver.close();
driver.switchTo().window("testwindow");
js.executeScript("window.moveTo(0,0);");
/*1280和1024分別爲窗口的寬和高,可以用下面的代碼得到
screenDims = Toolkit.getDefaultToolkit().getScreenSize();
width = (int)screenDims.getWidth();
height = (int)screenDims.getHeight(); */
js.executeScript("window.resizeTo(1440,900);");
System.out.println(Toolkit.getDefaultToolkit().getScreenSize().getWidth());
System.out.println(Toolkit.getDefaultToolkit().getScreenSize().getHeight());
}