从下图中可以看到selenium有三类定位元素的方法,一种是直接通过属性、标签以及链接来定位,一种是XPath方式,最后一种是CSS方式。
下表列举了元素定位的例子
方法 | 例子 | |
通过ID来定位 | WebElement wElement = driver.findElement(By.id("kw")) | |
通过Name来定位 | WebElement wElement = driver.findElement(By.name("wd")) | |
通过Class定位 | WebElement wElement = driver.findElement(By.className("s_ipt")) | |
通过Tag来定位 | List<WebElement> inputs = driver.findElements(By.tagName("input")) | |
通过Link来定位 | WebElement wElement = driver.findElement(By.linkText("新闻")) | |
通过PartialLink来定位 | WebElement wElement = driver.findElement(By.partialLinkText("使用百度")) | |
XPath定位 | 1.绝对路径 | WebElement wElement = driver.findElement(By.xpath("/html/body/div/div/div/div/div/form/span/input")) |
2.相对路径 | WebElement wElement = driver.findElement(By.xpath("//form/span/input")) | |
3.利用元素属性定位 | WebElement wElement = driver.findElement(By.xpath("//input[@id='kw']")) | |
4.层级与属性结合 | WebElement wElement = driver.findElement(By.xpath("//span[@class='bg s_ipt_wr iptfocus quickdelete-wrap']/input")) | |
5.使用逻辑运算符 | WebElement wElement = driver.findElement(By.xpath("//input[@class='s_ipt' and @id='kw']")) | |
CSS定位 | 1.通过class属性定位 | WebElement wElement = driver.findElement(By.cssSelector(".s_ipt")) |
2.通过id属性定位 | WebElement wElement = driver.findElement(By.cssSelector("#kw")) | |
3.通过标签名定位 | List<WebElement> inputs = driver.findElements(By.cssSelector("input")) | |
4.通过父子关系定位 | List<WebElement> inputs = driver.findElements(By.cssSelector("span>input")) | |
5.通过属性定位 | WebElement wElement = driver.findElement(By.cssSelector("[id=kw]")) | |
6.通配符 | WebElement wElement = driver.findElement(By.cssSelector("[class$=_ipt]")) | |
7.组合定位 | WebElement wElement = driver.findElement(By.cssSelector("form.fm>span>input.s_ipt")) |
注:driver.findElement代表定位到一个元素,driver.findElements代表返回一组元素。
下面通过实例来说明:
下面是百度首页的部分HTML代码,其中黄底部分就是一个输入框和一个按钮,将使用百度首页来编写测试脚本,并验证脚本。
1 2 3 4 56
下图是利用firefox中的firebug插件查看百度首页信息的截图。
下面编写了18个test,分别对应本页面顶部的表格内容。
1 package com.test.location; 2 3 import static org.junit.Assert.*; 4 5 import java.util.Iterator; 6 import java.util.List; 7 import java.util.concurrent.TimeUnit; 8 9 import javax.lang.model.element.Element; 10 11 import org.junit.After; 12 import org.junit.Before; 13 import org.junit.Test; 14 import org.openqa.selenium.By; 15 import org.openqa.selenium.WebDriver; 16 import org.openqa.selenium.WebElement; 17 import org.openqa.selenium.firefox.FirefoxDriver; 18 import org.openqa.selenium.interactions.Actions; 19 20 public class TestLocation { 21 WebDriver driver; 22 23 @Before 24 public void setUp() throws Exception { 25 26 //获取Driver 27 driver = new FirefoxDriver(); 28 driver.get("http://www.baidu.com/"); 29 //将屏幕最大化 30 driver.manage().window().maximize(); 31 //driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); 32 } 33 34 @After 35 public void tearDown() throws Exception { 36 //退出浏览器 37 38 driver.quit(); 39 } 40 ================================================================================================================== 41 //通过ID来定位 42 @Test 43 public void test001_GetByID() { 44 //清空输入框,并输入查询关键字“selenium”,然后点击查询按钮 45 driver.findElement(By.id("kw")).clear(); 46 driver.findElement(By.id("kw")).sendKeys("selenium"); 47 driver.findElement(By.id("su")).click(); 48 49 Boolean flag = driver.findElement(By.linkText("Selenium - Web Browser Automation")).isDisplayed(); 50 assertTrue("\"Selenium - Web Browser Automation\" is not display",flag); 51 } 52 =================================================================================================================== 53 //通过Name来定位 54 @Test 55 public void test002_GetByName(){ 56 //清空输入框,并输入查询关键字“selenium”,然后点击查询按钮 57 driver.findElement(By.name("wd")).clear(); 58 driver.findElement(By.name("wd")).sendKeys("selenium"); 59 driver.findElement(By.id("su")).click(); 60 61 Boolean flag = driver.findElement(By.linkText("Selenium - Web Browser Automation")).isDisplayed(); 62 assertTrue("\"Selenium - Web Browser Automation\" is not display",flag); 63 } 64 ==================================================================================================================== 65 //通过Class定位 66 @Test 67 public void test003_GetByClass(){ 68 //清空输入框,并输入查询关键字“selenium”,然后点击查询按钮 69 driver.findElement(By.className("s_ipt")).clear(); 70 driver.findElement(By.className("s_ipt")).sendKeys("selenium"); 71 driver.findElement(By.id("su")).click(); 72 73 74 Boolean flag = driver.findElement(By.linkText("Selenium - Web Browser Automation")).isDisplayed(); 75 assertTrue("\"Selenium - Web Browser Automation\" is not display",flag); 76 } 77 ==================================================================================================================== 78 //通过Tag来定位 79 @Test 80 public void test004_GetByTag(){ 81 //清空输入框,并输入查询关键字“selenium”,然后点击查询按钮 82 //input 这个tag在百度首页中比较多,所以需要使用findElements(),将所有input返回,并从中找寻需要的两个input 83 Listinputs = driver.findElements(By.tagName("input")); 84 Iterator it = inputs.iterator(); 85 WebElement we = null; 86 WebElement inputWe = null; 87 WebElement buttonWe = null; 88 while(it.hasNext()){ 89 we = (WebElement)it.next(); 90 if(we.getAttribute("id").toString().equals("kw")){ 91 inputWe = we; 92 } 93 94 if(we.getAttribute("id").toString().equals("su")){ 95 buttonWe = we; 96 } 97 } 98 99 //找到之后开始操作100 if(inputWe!=null && buttonWe!=null){101 inputWe.clear();102 inputWe.sendKeys("selenium");103 buttonWe.click(); 104 }else{ 105 System.out.println("can not find input and button"); 106 }107 108 //判断结果109 Boolean flag = driver.findElement(By.linkText("Selenium - Web Browser Automation")).isDisplayed();110 assertTrue("\"Selenium - Web Browser Automation\" is not display",flag); 111 }112 ============================================================================================================================ 113 //通过Link来定位114 @Test115 public void test005_GetByLink(){116 117 //点击新闻链接118 driver.findElement(By.linkText("新闻")).click();119 120 //获取title121 Boolean flag = driver.getTitle().toString().contains("新闻");122 assertTrue("\"新闻\" is not included in title",flag);123 }124 =============================================================================================================== 125 //通过PartialLink来定位126 @Test127 public void test006_GetByPartialLink(){128 129 driver.findElement(By.partialLinkText("使用百度")).click();130 131 //获取title132 Boolean flag = driver.getTitle().toString().contains("百度免责");133 assertTrue("the page of \"百度免责声明\" is not open",flag);134 }135 ================================================================================================================ 136 //XPath定位137 //XPath定位-1.绝对路径138 @Test 139 public void test007_GetByAbsolutePath(){140 141 driver.findElement(By.xpath("/html/body/div/div/div/div/div/form/span/input")).sendKeys("selenium");142 driver.findElement(By.xpath("/html/body/div/div/div/div/div/form/span[2]/input")).click();143 144 Boolean flag = driver.findElement(By.linkText("Selenium - Web Browser Automation")).isDisplayed();145 assertTrue("\"Selenium - Web Browser Automation\" is not display",flag);146 }147 =========================================================================================================================== 148 @Test //XPath定位-2.相对路径149 public void test008_GetByRelativePath(){150 151 driver.findElement(By.xpath("//form/span/input")).sendKeys("selenium");152 driver.findElement(By.xpath("//form/span[2]/input")).click();153 154 Boolean flag = driver.findElement(By.linkText("Selenium - Web Browser Automation")).isDisplayed();155 assertTrue("\"Selenium - Web Browser Automation\" is not display",flag);156 }157 ============================================================================================================================== 158 //XPath定位-3.利用元素属性定位159 @Test 160 public void test009_GetByElementAttribute(){161 162 driver.findElement(By.xpath("//input[@id='kw']")).sendKeys("selenium");163 driver.findElement(By.xpath("//input[@id='su']")).click();164 165 /*// 表示当前页面某个某个目录166 * input 表示定位元素的标签名167 * [@id='kw']表示这个元素的id属性值等于kw168 * 169 * 除了使用id这个属性,也可以使用name和class属性等其他属性来定位,只要值是唯一的。170 *1.//input[@name='wd']171 *2.//input[@class='s_ipt']172 *3.//*[@class='bg s_btn'] 符号* 代表不想指定标签名173 */ 174 175 Boolean flag = driver.findElement(By.linkText("Selenium - Web Browser Automation")).isDisplayed();176 assertTrue("\"Selenium - Web Browser Automation\" is not display",flag);177 }178 ================================================================================================================================== 179 //XPath定位-4.层级与属性结合180 @Test181 public void test010_GetByParent(){182 183 driver.findElement(By.xpath("//span[@class='bg s_ipt_wr iptfocus quickdelete-wrap']/input")).sendKeys("selenium");184 driver.findElement(By.xpath("//span[@class='bg s_btn_wr']/input")).click();185 //可以通过先定位父元素,在加上层级关系来定位目标元素。 这种方法还可以扩展到先查找爷爷元素。186 Boolean flag = driver.findElement(By.linkText("Selenium - Web Browser Automation")).isDisplayed();187 assertTrue("\"Selenium - Web Browser Automation\" is not display",flag);188 }189 =================================================================================================================================== 190 //XPath定位-5.使用逻辑运算符191 @Test192 public void test011_GetByAttributeCombination(){193 //这里就是元素属性的组合194 driver.findElement(By.xpath("//input[@class='s_ipt' and @id='kw']")).sendKeys("selenium");195 driver.findElement(By.xpath("//input[@class='bg s_btn' and @id='su']")).click();196 197 Boolean flag = driver.findElement(By.linkText("Selenium - Web Browser Automation")).isDisplayed();198 assertTrue("\"Selenium - Web Browser Automation\" is not display",flag);199 }200 201 ================================================================================================================================== 202 //CSS定位203 //CSS定位-1.通过class属性定位204 @Test205 public void test012_GetByClassAttribute(){206 207 //使用符号(.)来表示用class属性来定位208 driver.findElement(By.cssSelector(".s_ipt")).sendKeys("selenium");209 driver.findElement(By.id("su")).click();;210 211 Boolean flag = driver.findElement(By.linkText("Selenium - Web Browser Automation")).isDisplayed();212 assertTrue("\"Selenium - Web Browser Automation\" is not display",flag);213 }214 ================================================================================================================================= 215 //CSS定位-2.通过id属性定位216 @Test217 public void test013_GetByIdAttribute(){218 219 //使用符号(#)来表示用id属性来定位220 driver.findElement(By.cssSelector("#kw")).sendKeys("selenium");221 driver.findElement(By.cssSelector("#su")).click();;222 223 Boolean flag = driver.findElement(By.linkText("Selenium - Web Browser Automation")).isDisplayed();224 assertTrue("\"Selenium - Web Browser Automation\" is not display",flag);225 }226 ====================================================================================================================================== 227 //CSS定位-3.通过标签名定位228 @Test229 public void test014_GetByTagAttribute(){230 //清空输入框,并输入查询关键字“selenium”,然后点击查询按钮231 //input 这个tag在百度首页中比较多,所以需要使用findElements(),将所有input返回,并从中找寻需要的两个input232 List inputs = driver.findElements(By.cssSelector("input"));233 Iterator it = inputs.iterator(); 234 WebElement we = null;235 WebElement inputWe = null;236 WebElement buttonWe = null;237 while(it.hasNext()){238 we = (WebElement)it.next();239 if(we.getAttribute("id").toString().equals("kw")){240 inputWe = we;241 }242 243 if(we.getAttribute("id").toString().equals("su")){244 buttonWe = we;245 }246 }247 248 //找到之后开始操作249 if(inputWe!=null && buttonWe!=null){250 inputWe.clear();251 inputWe.sendKeys("selenium");252 buttonWe.click(); 253 }else{ 254 System.out.println("can not find input and button"); 255 }256 257 try {258 Thread.sleep(3000);259 } catch (InterruptedException e) {260 // TODO Auto-generated catch block261 e.printStackTrace();262 }263 264 //判断结果265 Boolean flag = driver.findElement(By.linkText("Selenium - Web Browser Automation")).isDisplayed();266 assertTrue("\"Selenium - Web Browser Automation\" is not display",flag); 267 }268 ============================================================================================================================= 269 //CSS定位-通过父子关系定位270 @Test271 public void test015_GetByParentTag(){272 //清空输入框,并输入查询关键字“selenium”,然后点击查询按钮273 //input 这个tag在百度首页中比较多,所以需要使用findElements(),将所有input返回,并从中找寻需要的两个input274 List inputs = driver.findElements(By.cssSelector("span>input"));275 Iterator it = inputs.iterator(); 276 WebElement we = null;277 WebElement inputWe = null;278 WebElement buttonWe = null;279 while(it.hasNext()){280 we = (WebElement)it.next();281 if(we.getAttribute("id").toString().equals("kw")){282 inputWe = we;283 }284 285 if(we.getAttribute("id").toString().equals("su")){286 buttonWe = we;287 }288 }289 290 //找到之后开始操作291 if(inputWe!=null && buttonWe!=null){292 inputWe.clear();293 inputWe.sendKeys("selenium");294 buttonWe.click(); 295 }else{ 296 System.out.println("can not find input and button"); 297 }298 299 try {300 Thread.sleep(3000);301 } catch (InterruptedException e) {302 // TODO Auto-generated catch block303 e.printStackTrace();304 }305 306 //判断结果307 Boolean flag = driver.findElement(By.linkText("Selenium - Web Browser Automation")).isDisplayed();308 assertTrue("\"Selenium - Web Browser Automation\" is not display",flag); 309 }310 =========================================================================================================================== 311 //CSS定位-通过属性定位312 @Test313 public void test016_GetByAttribute(){314 315 //在中括号[]中可以放置任意唯一的属性值对来定位316 driver.findElement(By.cssSelector("[id=kw]")).sendKeys("selenium");317 driver.findElement(By.cssSelector("[id=su]")).click();;318 319 Boolean flag = driver.findElement(By.linkText("Selenium - Web Browser Automation")).isDisplayed();320 assertTrue("\"Selenium - Web Browser Automation\" is not display",flag);321 }322 =========================================================================================================================== 323 //CSS定位-通配符324 @Test325 public void test017_GetByAttributeAndWildcard(){326 327 //[class$=_ipt]代表以_ipt结尾328 //[class^=bg]代表以bg开头329 //[class*=_ip]代表中间内容是_ip330 //这种方法存在一定的不稳定性,因为会出现匹配到多个元素的情况331 driver.findElement(By.cssSelector("[class$=_ipt]")).sendKeys("selenium");332 driver.findElement(By.cssSelector("[class^=bg]")).click();;333 334 try {335 Thread.sleep(3000);336 } catch (InterruptedException e) {337 // TODO Auto-generated catch block338 e.printStackTrace();339 }340 341 Boolean flag = driver.findElement(By.linkText("Selenium - Web Browser Automation")).isDisplayed();342 assertTrue("\"Selenium - Web Browser Automation\" is not display",flag);343 }344================================================================================================================================== 345 //CSS定位-组合定位346 @Test347 public void test018_GetByCombination(){348 349 //通过先定位父元素,再定位子元素。通过元素的class或者id属性来定位。350 driver.findElement(By.cssSelector("form.fm>span>input.s_ipt")).sendKeys("selenium");351 driver.findElement(By.cssSelector("form#form>span>input#su")).click();;352 353 354 Boolean flag = driver.findElement(By.linkText("Selenium - Web Browser Automation")).isDisplayed();355 assertTrue("\"Selenium - Web Browser Automation\" is not display",flag);356 }357 358 359 }
以上方法都是为了定位到目标元素,没有好坏之分,只要能够定位到元素,使用上面的任何一个方法都可以。