Selenium Web 自動化
阿新 • • 發佈:2019-02-14
1 對瀏覽器操作
1.1 用webdriver開啟一個瀏覽器
//開啟firefox瀏覽器: WebDriver driver = new FirefoxDriver(); //開啟IE瀏覽器 WebDriver driver = new InternetExplorerDriver (); //開啟HtmlUnit瀏覽器 WebDriverdriver = new HtmlUnitDriver(); //開啟chrome瀏覽器 WebDriverdriver = new ChromeDriver();
1.2 最大化瀏覽器&關閉瀏覽器
WebDriver driver = newFirefoxDriver(); driver.manage().window().maximize(); driver.close(); driver.quit();
1.3 設定瀏覽器視窗大小
private static void SetWindowTest(WebDriver driver)
throws InterruptedException {
// 設定視窗的 寬度為:800,高度為600
Dimension d = new Dimension(800, 600);
driver.manage().window().setSize(d);
Thread.sleep(2000);
// 設定視窗最大化
driver.manage().window().maximize();
Thread.sleep(2000);
// 設定窗口出現在螢幕上的座標
Point p = new Point(500, 300);
// 執行設定
driver.manage().window().setPosition(p);
Thread.sleep(2000);
}
1.4 開啟測試頁面
開啟測試頁面 driver.get("http://www.baidu.com/"); driver.navigate().to("http://www.baidu.com/"); //navigate方法會產生1個Navigator物件,其封裝了與導航相關的一些方法,比如前進後退等
1.5 處理瀏覽器彈出的新視窗
private static void MutiWindowTest(WebDriver driver)
throws InterruptedException {
WebDriver newWindow = null ;
driver.get("http://www.hao123.com/");
//瀏覽器最大化
driver.manage().window().maximize();
//獲取當前頁面控制代碼
String current_handles = driver.getWindowHandle();
//點選 百度連結
driver.findElement(By.xpath("//*[@data-title='百度']")).click();
//接下來會有新的視窗開啟,獲取所有視窗控制代碼
Set<String> all_handles = driver.getWindowHandles();
//迴圈判斷,把當前控制代碼從所有控制代碼中移除,剩下的就是你想要的新視窗
Iterator<String> it = all_handles.iterator();
while(it.hasNext()){
if(current_handles == it.next()) continue;
//跳入新視窗,並獲得新視窗的driver - newWindow
newWindow = driver.switchTo().window(it.next());
}
//接下來在新頁面進行操作,也就是百度首頁,我們輸入一個java關鍵字進行搜尋
Thread.sleep(5000);
WebElement baidu_keyowrd = newWindow.findElement(By.id("kw"));
baidu_keyowrd.sendKeys("java");
Thread.sleep(1000);
//關閉當前視窗,主要使用close而不是quite,
newWindow.close();
driver.switchTo().window(current_handles);
System.out.println(driver.getCurrentUrl());
}
2 頁面元素定位
Webdriver提供下面兩種方法來定位頁面元素,引數是By對像,最常用是By.id和By.name查詢。
- findElement 定位某個元素,如果沒有找到元素會丟擲異常:NoSuchElementException
- findElements 定位一組元素
例如需要定位如下元素:
<input class="input_class" type="text" name="passwd" id="passwd-id" />
//By.id WebElement element = driver.findElement(By.id("passwd-id")); //By.name WebElement element = driver.findElement(By.name("passwd")); //By.xpath WebElement element =driver.findElement(By.xpath("//input[@id='passwd-id']")); //By.className WebElement element = driver.findElement(By.className("input_class")); //By.cssSelector WebElement element = driver.findElement(By.cssSelector(".input_class")); //By.linkText //通俗點就是精確查詢 WebDriver driver = new FirefoxDriver(); driver.get("http://www.baidu.com/"); WebElement element = driver.findElement(By.linkText("百科")); //By.partialLinkText: //這個方法就是模糊查詢 WebDriver driver = new FirefoxDriver(); driver.get("http://www.baidu.com/"); WebElement element = driver.findElement(By.partialLinkText("hao")); //By.tagName WebDriver driver = new FirefoxDriver(); driver.get("http://www.baidu.com/"); String test= driver.findElement(By.tagName("form")).getAttribute("name"); System.out.println(test);
3 如何對頁面元素進行操作
3.1 WebElement相關方法
Method Summary | |
void clear() | If this element is a text entry element, this will clear the value. |
void click() | Click this element. |
WebElement findElement(By by) | Find the first WebElement using the given method. |
java.util.List<WebElement>findElement(By by) | Find all elements within the current context using the given mechanism. |
java.lang.StringgetAttribute(java.lang.String name) | Get the value of a the given attribute of the element. |
java.lang.StringgetCssValue(java.lang.String.propertyName) | Get the value of a given CSS property. |
Point GetLocation() | Where on the page is the top left-hand corner of the rendered element? |
Dimension getSize() | What is the width and height of the rendered element? |
java.lang.String getTagName() | Get the tag name of this element. |
java.lang.String getText() | Get the visible (i.e. not hidden by CSS) innerText of this element, including |
sub-elements, without any leading or trailing whitespace. | |
boolean isDisplayed() | Is this element displayed or not? This method avoids the problem of having to parse an element's "style" attribute. |
boolean isEnabled() | Is the element currently enabled or not? This will generally return true for everything but disabled input elements. |
boolean isSelected() | Determine whether or not this element is selected or not. |
voidsendKeys(java.lang.CharSequence... keysToSend) | Use this method to simulate typing into an element, which may set its value. |
void submit() | If this current element is a form, or an element within a form, then this will be submitted to the remote server. |
3.2 iFrame的處理
driver.switchTo().frame(“city_set_ifr”); //傳入的是iframe的ID
dr.switchTo().defaultContent(); //如果要返回到以前的預設content
3.3 輸入框(text field or textarea)
WebElement element = driver.findElement(By.id("passwd-id")); element.sendKeys(“test”);//在輸入框中輸入內容: element.clear(); //將輸入框清空 element.getText(); //獲取輸入框的文字內容:
3.4 下拉選擇框(Select)
Select select = new Select(driver.findElement(By.id("select"))); select.selectByVisibleText(“A”); select.selectByValue(“1”); select.deselectAll(); select.deselectByValue(“1”); select.deselectByVisibleText(“A”); select.getAllSelectedOptions(); select.getFirstSelectedOption();
示例:
package seleniumAPIDemo;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class SelectDemo {
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
iframeAndSelectTest(driver);
driver.quit();
}
private static void iframeAndSelectTest(WebDriver driver)
throws InterruptedException {
driver.get("http://www.2345.com/");
//瀏覽器最大化
driver.manage().window().maximize();
//點選切換按鈕
driver.findElement(By.id("J_city_switch")).click();
//進入天氣城市選擇iframe
driver.switchTo().frame("city_set_ifr");
Thread.sleep(2000);
//然後在進行選擇城市
//定位 省下拉框
Select province = new Select(driver.findElement(By.id("province")));
province.selectByValue("20");
Thread.sleep(2000);
//定位 城市下拉框
Select city = new Select(driver.findElement(By.id("chengs")));
city.selectByIndex(0);
Thread.sleep(2000);
//定位區
Select region = new Select(driver.findElement(By.id("cityqx")));
region.selectByVisibleText("X 新密");
Thread.sleep(2000);
//點選定製按鈕
driver.findElement(By.id("buttonsdm")).click();
Thread.sleep(2000);
//返回預設的content
driver.switchTo().defaultContent();
}
}
3.5 單選項(Radio Button)
WebElement radio=driver.findElement(By.id("BookMode")); radio.click(); //選擇某個單選項 radio.clear(); //清空某個單選項 radio.isSelected(); //判斷某個單選項是否已經被選擇
3.6 多選項(checkbox)
WebElement checkbox = driver.findElement(By.id("myCheckbox."));
checkbox.click();
checkbox.clear();
checkbox.isSelected();
checkbox.isEnabled();
3.7 按鈕(button)
WebElement btn= driver.findElement(By.id("save")); btn.click(); //點選按鈕 btn.isEnabled (); //判斷按鈕是否enable
3.8 處理Alert
彈出對話方塊(Popup dialogs)
Alert alert = driver.switchTo().alert();
alert.accept(); //確定
alert.dismiss(); //取消
alert.getText(); //獲取文字
示例:
private static void alertTest(WebDriver driver) throws InterruptedException {
driver.get("http://www.w3school.com.cn/tiy/t.asp?f=hdom_alert");
//瀏覽器最大化
driver.manage().window().maximize();
//進入frame
driver.switchTo().frame("i");
//找到按鈕並點選按鈕
driver.findElement(By.xpath("//*[@value='顯示訊息框']")).click();
Thread.sleep(2000);
//獲取Alert
Alert a = driver.switchTo().alert();
//打印出文字內容
System.out.println(a.getText());
//點選確定
Thread.sleep(2000);
a.accept();
// 如果alert上有取消按鈕,可以使用a.dismiss()程式碼
}
3.9 上傳檔案
3.9.1 元素標籤是Input時上傳方式
Upload.html檔案內容如下:
<body>
<input type="file" id="fileControl" value="選擇檔案"/>
</body>
程式碼如下:
private static void uploadTest1(WebDriver driver) throws InterruptedException {
//開啟上傳的網頁 - get中輸入upload的地址
driver.get("D:\\DownLoad\\UploadTest\\upload.html");
WebElement e1 = driver.findElement(By.id("fileControl"));
Thread.sleep(2000);
//輸入要上傳檔案的地址
e1.sendKeys("D:\\DownLoad\\UploadTest\\被上傳的檔案.txt");
Thread.sleep(2000);
}
3.9.2 通過操作桌面瀏覽視窗上傳
3.10 Selenium處理HTML5
3.10.1 處理Vedio
private static void html5VedioTest(WebDriver driver)
throws InterruptedException {
driver.get("http://videojs.com/");
Thread.sleep(2000);
//找到vedio元素
WebElement vedio = driver.findElement(By.id("preview-player_html5_api"));
//宣告js執行器
JavascriptExecutor js = (JavascriptExecutor) driver;
//對vedio這個元素執行播放操作
js.executeScript("arguments[0].play()", vedio);
//為了觀察效果暫停5秒
Thread.sleep(5000);
//對vedio這個元素執行暫停操作
js.executeScript("arguments[0].pause()", vedio);
//為了觀察效果暫停2秒
Thread.sleep(2000);
//對vedio這個元素執行播放操作
js.executeScript("arguments[0].play()", vedio);
//為了觀察效果暫停2秒
Thread.sleep(2000);
//對vedio這個元素執行重新載入視訊的操作
js.executeScript("arguments[0].load()", vedio);
//為了觀察效果暫停2秒
Thread.sleep(2000);
}
3.10.2 處理Canvas
private static void Html5CanvasTest(WebDriver driver)
throws InterruptedException {
driver.get("http://literallycanvas.com/");
Thread.sleep(2000);
//找到canvas元素
WebElement canvas = driver.findElement(By.xpath("//*[@id='literally-canvas']//canvas[1]"));
//宣告一個操作類
Actions drawPen = new Actions(driver);
//點選並保持不放滑鼠 ,按照給定的座標點移動
drawPen.clickAndHold(canvas).moveByOffset(20, 100).moveByOffset(100, 20).moveByOffset(-20, -100).moveByOffset(-100, -20).release().perform();
Thread.sleep(2000);
}
3.11 表單(Form)
//Form中的元素的操作和其它的元素操作一樣,對元素操作完成後對錶單的提交可以: WebElement approve = driver.findElement(By.id("approve")); approve.click(); //或 approve.submit();//只適合於表單的提交
4 其他
4.1 等待元素載入
超時設定
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //識別元素時的超時時間
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); //頁面載入時的超時時間
driver.manage().timeouts().setScriptTimeout(10, TimeUnit.SECONDS); //非同步指令碼的超時時間
- 硬性等待 Thread.sleep(int sleeptime);
- 智慧等待
- 設定等待頁面載入完畢
private static void waitElementTest(WebDriver driver) {
//設定等待頁面完全載入的時間是10秒,如果在10秒內載入完畢,剩餘時間不在等待
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
driver.get("https://www.baidu.com/");
By inputBox = By.id("kw");
By searchButton = By.id("su");
//智慧等待元素加載出來
intelligentWait(driver, 10, inputBox);
//智慧等待元素加載出來
intelligentWait(driver, 10, searchButton);
//輸入內容
driver.findElement(inputBox).sendKeys("JAVA");
//點選查詢
driver.findElement(searchButton).click();
}
public static void intelligentWait(WebDriver driver,int timeOut, final By by){
try {
(new WebDriverWait(driver, timeOut)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
WebElement element = driver.findElement(by);
return element.isDisplayed();
}
});
} catch (TimeoutException e) {
Assert.fail("超時!! " + timeOut + " 秒之後還沒找到元素 [" + by + "]",e);
}
}
4.2 執行JS指令碼
有時候我們需要JS指令碼來輔助我們進行測試,比如我們用JS賦值或者用js執行點選操作等。執行JS指令碼比較適用某些元素不易點選的情況下使用,比如網頁內容太長,當前視窗太長,想要點選那些不在當前視窗可以看到元素可以用此方法。
private static void runJSTest1(WebDriver driver) throws InterruptedException { String js ="alert(\"hello,this is a alert!\")"; ((org.openqa.selenium.JavascriptExecutor) driver).executeScript(js); Thread.sleep(2000); } private static void runJSTest2(WebDriver driv