今天,總結一下selenium怎么操作web頁面常見的元素。
主要有:
- 上傳
- alter dialog
- prompt dialog
- confirm dialog
- select list
- radio box
- input box
- checkBox
測試頁面如下:

1 <html> 2 <head> 3 <title>selenium處理基本頁面元素</title> 4 <style type="text/css"> 5 table{font-size:26;text-align:center;width:80%;border-collapse:collapse;margin:auto} 6 table th{background: #aff} 7 .display{color:red} 8 .widgetStyle{text-align:left;padding-left:100px} 9 </style> 10 <script language= "javascript" type="text/javascript"> 11 function clickbutton(flag) 12 { 13 if (flag == 1) alert("測試alert對話框"); 14 if (flag == 2) 15 { 16 var name=prompt("測試prompt對話框",""); 17 if (name!=null && name!="") 18 { 19 //document.write(name); 20 alert(name); 21 } 22 } 23 if (flag == 3) 24 { 25 var r=confirm('測試confirm對話框', '測試confirm對話框?',"測試結果:") 26 if (r==true) 27 { 28 //document.write("You pressed OK!") 29 alert("You pressed OK!"); 30 } 31 else 32 { 33 //document.write("You pressed Cancel!") 34 35 alert("You pressed Cancel!"); 36 } 37 } 38 if (flag == 4) 39 40 alert(document.getElementById("edit").value); 41 42 43 } 44 45 46 47 48 function getOptions() 49 { 50 var x=document.getElementById("Selector"); 51 var y=x.options[x.selectedIndex].text 52 // document.write(y); 53 alert(y); 54 } 55 </script> 56 </head> 57 58 <body> 59 <center> 60 </br> 61 <div> 62 <p> 63 64 <div class="text" style="font-size:36;text-align:center"><b>seleniun處理基本元素</b></div> 65 </p> 66 <hr> 67 </div> 68 <p> 69 <table cellpadding="10" cellspacing="0" border="2"> 70 <thead> 71 <tr> 72 <th width=20% class="widgetleft">測試內容</th> 73 <th width=80% class="widgetStyle">頁面基本元素</th> 74 </tr> 75 </thead> 76 77 78 <tr> 79 <td>文件上傳</td> 80 <td><input type="file" name="attach[]" /></td> 81 </tr> 82 83 <tr> 84 <td>alter對話框</td> 85 <td> 86 <input type="button" name="alterbutton" value="測試alter對話框" onclick = "clickbutton(1);" /> 87 </td> 88 </tr> 89 90 <tr> 91 <td>prompt對話框</td> 92 <td> 93 <input type="button" name="promptbutton" value="測試prompt對話框" onclick = "clickbutton(2);" /> 94 </td> 95 </tr> 96 97 <tr> 98 <td>confirm對話框</td> 99 <td> 100 <input type="button" name="confirmbutton" value="測試confirm對話框" onclick = "clickbutton(3);" /> 101 </td> 102 </tr> 103 <tr> 104 <td>select菜單</td> 105 <td> 106 <select id="Selector"> 107 <option value="apple" index="1" >蘋果</option> 108 <option value="peach" index="2" >桃子</option> 109 <option value="banana" index="3" >香蕉</option> 110 <option value="orange" index="4">桔子</option> 111 <option value="grape" index="5">葡萄</option> 112 <option value="mango" index="6">芒果</option> 113 </select> 114 <br /><br /> 115 <input type="button" id="showSelectResult" name="showSelectResult" onclick="getOptions()" value="選擇結果"> 116 </td> 117 </tr> 118 119 <tr> 120 <td>文本框</td> 121 <td> 122 <input type="text" name="edit" id="edit" value="" /> 123 <input type="button" name="submit" value="submit" onclick = "clickbutton(4);"/> 124 </td> 125 </tr> 126 127 <tr> 128 <td>RadioBox</td> 129 <td class="widgetStyle"> 130 <label> 131 Which is your favourite company? 132 </label> 133 <div id='radio' > 134 <input type='radio' name="company" class='Baidu'/> 135 <span class="pip"></span> 136 <label>百度</label> 137 </br> 138 <input type='radio' name="company" class='AliBaBa'/> 139 <span class="pip"></span> 140 <label>阿里巴巴</label></br> 141 <input type='radio' name="company" class='Tencent' checked/> 142 <span class="pip"></span> 143 <label>騰訊</label></br> 144 <input type='radio' name="company" class='Mi' disabled="true"/> 145 <span class="pip"></span> 146 <label>小米</label> 147 </td> 148 </tr> 149 150 <tr> 151 <td>CheckBox</td> 152 <td class="widgetStyle"> 153 <label> 154 In which way do you know about Selenium 155 <label> 156 <div id='checkbox'> 157 <input type="checkbox" name="checkbox1" id="web"/><label>網絡</label></br> 158 <input type="checkbox" name="checkbox2" id="training"/><label>培訓</label></br> 159 <input type="checkbox" name="checkbox3" id="friend"/><label>朋友介紹</label></br> 160 <input type="checkbox" name="checkbox4" id="other" /><label>其他方式</label> 161 </div> 162 </td> 163 </tr> 164 <tr> 165 <td>Select Links</td> 166 <td> 167 <div class="links"> 168 <select name="jumpMenu" id="jumpMenu" onchange="window.open(this.value)"> 169 <option selected="selected">市縣教育局</option> 170 <option value="http://www.zzjy.gov.cn/" >鄭州市教育局</option> 171 <option value="http://www.kfedu.com.cn/" >開封教育網</option> 172 <option value="http://www.lyenet.org/" >洛陽市教育局</option> 173 <option value="http://www.pdsedu.gov.cn/" >平頂山教育網</option> 174 <option value="http://www.anyangedu.com/" >安陽教育信息網</option> 175 <option value="http://www.hnhbedu.net/" >鶴壁教育信息網</option> 176 <option value="http://www.xxjy.gov.cn/" >新鄉市教育局</option> 177 <option value="http://www.jzedu.cn/" >焦作市教育局</option> 178 <option value="http://www.xcsjyw.com/" >許昌教育網</option> 179 <option value="http://www.lhjy.net/" >漯河教育網</option> 180 <option value="http://www.smxjy.cn/" >三門峽教育信息港</option> 181 <option value="http://www.sqedu.gov.cn/" >商丘市教育局</option> 182 <option value="http://www.zkedu.gov.cn/" >周口市教育局</option> 183 <option value="http://www.zmdedu.net/" >駐馬店教育局 </option> 184 <option value="http://www.nyedu.net/" >南陽教育局</option> 185 <option value="http://www.xinyangedu.gov.cn/" >信陽市教育局</option> 186 <option value="http://www.jyedu.org/" >濟源教育網</option> 187 </select> 188 </div> 189 </td> 190 </tr> 191 </table> 192 193 194 </p> 195 <p> 196 <label for="edit">轉載請注明出處</label> 197 </br> 198 <a href="http://www.cnblogs.com/tobecrazy/" >Copyright 2015 to be crazy </a> 199 </p> 200 201 </center> 202 </body> 203 </html>
selenium 最核心的技巧是WebElement的識別和定位
selenium總共有八種定位方法
- By.id() 通過id定位
- By.name() 通過name 定位
- By.xpath() 通過xpath定位
- By.className() 通過className定位
- By.cssSelector() 通過CSS 定位
- By.linkText() 通過linkText
- By.tagName() 通過tagName
- By.partialLinkText() 通過匹到的部分linkText
目前,使用比較多的是cssSelector和xpath,因為一個頁面中Id name className tagName LinkText等比較容易重復 不容易 確定唯一
接下來會有具體的例子來演示如何定位
上傳文件
一般,上傳頁面如果是input,像這樣的,可以使用sendkeys
首先,這里使用xpath定位到該元素,然后使用sendKeys即可,sendKeys send你要上傳的文件的絕對路徑
1 //td/input[@type='file']
也可以使用cssSelector,關於xpath和cssSelector更多知識,以后會做一些專題
1 td>input[type='file']
如何驗證你寫的xptah/cssSelector是正確的呢?
有以下幾種方法:
- F12 ,使用瀏覽器的console ,xpath使用$x() function,css使用 $() function
- 使用第三方插件firebug
- 使用selenium IDE
alert對話框
細分三種,Alert,prompt,confirm
Selenium有以下方法:
Alert alert =driver.switchTo().alert();
1. driver.switchTo().alert(); 獲取alert
2. alert.accept(); 點確定
3. alert.dismiss(); 點取消
4. alert.getText();獲取alert的內容
select菜單
select也是比較常見的,selenium封裝了以下方法
創建select
WebElement selector = driver.findElement(By.id("Selector")); Select select = new Select(selector);
選擇select的option有以下三種方法
- selectByIndex(int index) 通過index
- selectByVisibleText(String text) 通過匹配到的可見字符
- selectByValue(String value) 通過匹配到標簽里的value
WebElement selector = driver.findElement(By.id("Selector")); Select select = new Select(selector); select.selectByIndex(3); select.selectByVisibleText("桃子"); select.selectByValue("apple");
輸入框
輸入框就比較簡單了,不再多說
sendKeys()輸入內容
clear() 清空
單選框(RadioBox)
單選框可以有獲取狀態,是否被選中
radioBox.isSelected();
是否enable
radioBox.isEnabled()
使用click方法選中
復選框(checkBox)
復選框和單選框基本差不多,此處略
超鏈接
超鏈接比較常見,一般都是標簽a
<a href="http://www.cnblogs.com/tobecrazy/" >Copyright 2015 to be crazy </a>
一般使用click方法
這里我們了解一下瀏覽器打開超鏈接時,如果是chrome,點超鏈接的同時按下Ctrl會打開新標簽,按下shift會打開新窗口
這里單講一下不同窗口切換.
selenium有兩個關於獲取窗口的方法:
1. driver.getWindowHandle(); 返回的是字符串,獲取當前窗口的句柄
2. driver.getWindowHandles(); 返回的是 Set<String> ,獲取所有窗口
如果你想在窗口之間切換
driver.switchTo().window(window);
小技巧: 如何滾動到你定位的元素
這里使用java script
// scroll to mylink JavascriptExecutor scroll = (JavascriptExecutor) driver; scroll.executeScript("arguments[0].scrollIntoView();", myLink);
接下來是所有測試代碼:
package com.packt.webdriver.chapter1; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.Select; import org.testng.Assert; import com.packt.webdriver.chapter3.DriverFactory; /** * this method is for deal with base web elements * * @author Young * */ public class dealWithElements { public static void main(String[] args) throws Exception { String URL = "file://demo.html"; String chromdriver="E:\\chromedriver.exe"; System.setProperty("webdriver.chrome.driver", chromdriver); ChromeOptions options = new ChromeOptions(); // options.addExtensions(new File("")); DesiredCapabilities capabilities = DesiredCapabilities.chrome(); capabilities.setCapability("chrome.switches", Arrays.asList("--start-maximized")); options.addArguments("--test-type", "--start-maximized"); WebDriver driver=new ChromeDriver(options); driver.get(URL); // max size the browser driver.manage().window().maximize(); driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); WebElement upload = driver.findElement(By .xpath("//td/input[@type='file']")); upload.sendKeys("C:/Users/Young/Desktop/demo.html"); Assert.assertTrue(upload.getAttribute("value").contains("demo")); // for alert WebElement clickOnAlert = driver.findElement(By .xpath("//td/input[@name='alterbutton']")); clickOnAlert.click(); delay(2); // get alert Alert alert = driver.switchTo().alert(); Assert.assertTrue(alert.getText().contains("alert")); // click alert ok alert.accept(); delay(2); // for prompt WebElement clickOnPrompt = driver.findElement(By .xpath("//td/input[@name='promptbutton']")); clickOnPrompt.click(); delay(2); Alert prompt = driver.switchTo().alert(); prompt.sendKeys("I love Selenium"); prompt.accept(); delay(5); Alert afterAccept = driver.switchTo().alert(); Assert.assertTrue(afterAccept.getText().contains("I love Selenium")); // click alert ok afterAccept.accept(); delay(2); // for confirm WebElement clickOnConfirm = driver.findElement(By .xpath("//td/input[@name='confirmbutton']")); clickOnConfirm.click(); delay(2); Alert confirm = driver.switchTo().alert(); confirm.dismiss(); delay(2); Alert afterDismiss = driver.switchTo().alert(); Assert.assertTrue(afterDismiss.getText().contains("You pressed Cancel")); delay(2); afterDismiss.accept(); driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); WebElement selector = driver.findElement(By.id("Selector")); Select select = new Select(selector); select.selectByIndex(3); select.selectByVisibleText("桃子"); select.selectByValue("apple"); System.out.println(select.getAllSelectedOptions().toString()); delay(2); WebElement showSelectResult = driver.findElement(By .name("showSelectResult")); showSelectResult.click(); delay(2); Alert yourSelect = driver.switchTo().alert(); Assert.assertTrue(yourSelect.getText().contains("蘋果")); delay(2); yourSelect.accept(); // input box WebElement editBox = driver.findElement(By .xpath("//td/input[@id='edit']")); editBox.sendKeys("Selenium is good"); WebElement submitButton = driver.findElement(By .xpath("//input[@type='button' and @name='submit']")); submitButton.click(); delay(2); Alert submitAlert = driver.switchTo().alert(); Assert.assertEquals(submitAlert.getText(), "Selenium is good"); submitAlert.accept(); delay(2); // for radio Box WebElement duRadioBox = driver.findElement(By .cssSelector("div#radio>input.Baidu")); WebElement aLiRadioBox = driver.findElement(By .cssSelector("div#radio>input.Alibaba")); WebElement TXRadioBox = driver.findElement(By .cssSelector("div#radio>input.Tencent")); WebElement MiRadioBox = driver.findElement(By .cssSelector("div#radio>input.Mi")); delay(2); Assert.assertTrue(TXRadioBox.isSelected()); Assert.assertTrue(!MiRadioBox.isEnabled()); delay(2); duRadioBox.click(); Assert.assertTrue(duRadioBox.isSelected()); delay(2); aLiRadioBox.click(); Assert.assertTrue(aLiRadioBox.isSelected()); delay(2); // for checkBox List<WebElement> webCheckBox = driver.findElements(By .xpath("//input[@type='checkbox']")); for (WebElement e : webCheckBox) { e.click(); Assert.assertTrue(e.isSelected()); delay(2); } // for links String defaultWindow = driver.getWindowHandle(); WebElement myLink = driver.findElement(By .linkText("Copyright 2015 to be crazy")); delay(3); // scroll to mylink JavascriptExecutor scroll = (JavascriptExecutor) driver; scroll.executeScript("arguments[0].scrollIntoView();", myLink); // open link in a new windows press shift when you click delay(2); Actions actions = new Actions(driver); actions.keyDown(Keys.SHIFT).click(myLink).perform(); delay(3); Set<String> currentWindows = driver.getWindowHandles(); System.out.println(currentWindows.size()); for (String window : currentWindows) { if (!window.endsWith(defaultWindow)) { driver = driver.switchTo().window(window); driver.manage().timeouts() .pageLoadTimeout(60, TimeUnit.SECONDS); driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); break; } } Assert.assertTrue(driver.getCurrentUrl().contains("tobecrazy")); delay(10); driver.quit(); } /** * @author Young * @param seconds */ public static void delay(int seconds) { try { Thread.sleep(seconds * 1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }