Selenium Web 自動化 - Selenium常用API
2016-08-01
1 對瀏覽器操作
1.1 用webdriver打開一個瀏覽器
1.2 最大化瀏覽器&關閉瀏覽器
1.3 設置瀏覽器窗口大小
1.4 打開測試頁面
1.5 處理瀏覽器彈出的新窗口
2 頁面元素定位
3 如何對頁面元素進行操作
3.1 WebElement相關方法
3.2 iFrame的處理
3.3 輸入框(text field or textarea)
3.4 下拉選擇框(Select)
3.5 單選項(Radio Button)
3.6 多選項(checkbox)
3.7 按鈕(button)
3.8 處理Alert
3.9 上傳文件
3.9.1 元素標簽是Input時上傳方式
3.9.2 通過操作桌面瀏覽窗口上傳
3.10 Selenium處理HTML5
3.10.1 處理Vedio
3.10.2 處理Canvas
3.11 表單(Form)
4 其他
4.1 等待元素加載
4.2 執行JS腳本
4.3 模擬鍵盤操作
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 = new FirefoxDriver(); 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.String getAttribute(java.lang.String name) | Get the value of a the given attribute of the element. |
java.lang.String getCssValue(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. |
void sendKeys(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
這就需要了解html5中vedio的相關方法了,可以參考http://www.w3school.com.cn/tags/html_ref_audio_video_dom.asp

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 driver) throws InterruptedException { driver.get("https://www.baidu.com/"); String js ="arguments[0].click();"; driver.findElement(By.id("kw")).sendKeys("JAVA"); WebElement searchButton = driver.findElement(By.id("su")); ((org.openqa.selenium.JavascriptExecutor) driver).executeScript(js,searchButton); Thread.sleep(2000); }
4.3 模擬鍵盤操作
有時候有些元素不便點擊或者做其他的操作,這個時候可以借助selenium提供的Actions類,它可以模擬鼠標和鍵盤的一些操作,比如點擊鼠標右鍵,左鍵,移動鼠標等操作。對於這些操作,使用perform()方法進行執行。

private static void actionsTest(WebDriver driver) throws InterruptedException { // 設置等待頁面完全加載的時間是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); // 實例化action對象 Actions action = new Actions(driver); // 通過action模擬鍵盤輸入java關鍵字到 輸入框,只有使用了perform方法才會輸入進去 action.sendKeys(driver.findElement(searchButton), "java").perform(); // 鼠標模擬移動到搜索按鈕 action.moveToElement(driver.findElement(searchButton)).perform(); // 模擬點擊操作 action.click().perform(); Thread.sleep(2000); }