selenium定位方法(java实例)(二)

 从下图中可以看到selenium有三类定位元素的方法,一种是直接通过属性、标签以及链接来定位,一种是XPath方式,最后一种是CSS方式。

 

下表列举了元素定位的例子

selenium之页面元素定位方法
   方法  例子
   通过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.利用text()方法定位 WebElement wElement = driver.findElement(By.xpath("//span[text()='确定']"))    span可以使用*替换
   5.利用contains()方法定位

WebElement wElement = driver.findElement(By.xpath("//a[contains(@href,'basicinfo')"))

WebElement wElement = driver.findElement(By.xpath("//*[contains(text(),'退出')]"))

   6.层级与属性结合  WebElement wElement = driver.findElement(By.xpath("//span[@class='bg s_ipt_wr iptfocus quickdelete-wrap']/input"))
   7.使用逻辑运算符  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 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <body link="#0000cc">
 5 <div id="swfEveryCookieWrap" data-for="result" style=" 0px; height: 0px; overflow: hidden;">
 6 <script>
 7 <div id="wrapper" style="display: block;">
 8 <script>
 9 <div id="head">
10 <div class="head_wrapper">
11 <div class="s_form">
12 <div class="s_form_wrapper">
13 <div id="lg">
14 <a id="result_logo" onmousedown="return c({'fm':'tab','tab':'logo'})" href="/">
15 <form id="form" class="fm" action="/s" name="f">
16 <input type="hidden" value="utf-8" name="ie">
17 <input type="hidden" value="8" name="f">
18 <input type="hidden" value="1" name="rsv_bp">
19 <input type="hidden" value="1" name="rsv_idx">
20 <input type="hidden" value="" name="ch">
21 <input type="hidden" value="baidu" name="tn">
22 <input type="hidden" value="" name="bar">
23 <span class="bg s_ipt_wr iptfocus quickdelete-wrap">
24 <input id="kw" class="s_ipt" autocomplete="off" maxlength="255" value="" name="wd">
25 </span>
26 <span class="bg s_btn_wr">
27 <input id="su" class="bg s_btn" type="submit" value="百度一下">
28 </span>
29 <span class="tools">
30 <input type="hidden" value="" name="rn">
31 <input type="hidden" value="" name="oq">
32 <input type="hidden" value="e142557200096242" name="rsv_pq">
33 <input type="hidden" value="51ebs1YfGfrIuFRBo4wcRYuW9Io+gk3kpwseb9ioGcn4djCUsWDwr56pCKk" name="rsv_t">
34 <input type="hidden" value="cn" name="rqlang">
35 </form>
36 <div id="m"></div>
37 </div>
38 </div>
39 <div id="u">
40 <div id="u1">
41 </div>
42 </div>
43 <div id="s_tab" class="s_tab">
44 <div id="ftCon">
45 <div id="wrapper_wrapper"></div>
46 </div>
47 <div id="c-tips-container" class="c-tips-container"></div>
48 <script>
49 <script>
50 <script>
51 <script src="https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/static/protocol/https/jquery/jquery-1.10.2.min_f2fb5194.js" type="text/javascript">
52 <script>
53 <script type="text/javascript">
54 <script>
55 <script>
56 </body>
57 </html>

 下图是利用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         List<WebElement> inputs = driver.findElements(By.tagName("input"));
 84         Iterator<WebElement> 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     @Test
115     public void test005_GetByLink(){
116         
117         //点击新闻链接
118         driver.findElement(By.linkText("新闻")).click();
119         
120         //获取title
121         Boolean flag = driver.getTitle().toString().contains("新闻");
122         assertTrue(""新闻" is not included in title",flag);
123     }
124   ===============================================================================================================  
125     //通过PartialLink来定位
126     @Test
127     public void test006_GetByPartialLink(){
128                 
129         driver.findElement(By.partialLinkText("使用百度")).click();
130         
131         //获取title
132         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属性值等于kw
168          * 
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     @Test
181     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     @Test
192     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     @Test
205     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     @Test
217     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     @Test
229     public void test014_GetByTagAttribute(){
230         //清空输入框,并输入查询关键字“selenium”,然后点击查询按钮
231         //input 这个tag在百度首页中比较多,所以需要使用findElements(),将所有input返回,并从中找寻需要的两个input
232         List<WebElement> inputs = driver.findElements(By.cssSelector("input"));
233         Iterator<WebElement> 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 block
261             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     @Test
271     public void test015_GetByParentTag(){
272         //清空输入框,并输入查询关键字“selenium”,然后点击查询按钮
273         //input 这个tag在百度首页中比较多,所以需要使用findElements(),将所有input返回,并从中找寻需要的两个input
274         List<WebElement> inputs = driver.findElements(By.cssSelector("span>input"));
275         Iterator<WebElement> 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 block
303             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     @Test
313     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         @Test
325         public void test017_GetByAttributeAndWildcard(){
326             
327             //[class$=_ipt]代表以_ipt结尾
328             //[class^=bg]代表以bg开头
329             //[class*=_ip]代表中间内容是_ip
330             //这种方法存在一定的不稳定性,因为会出现匹配到多个元素的情况
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 block
338                 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     @Test
347     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 }

 以上方法都是为了定位到目标元素,没有好坏之分,只要能够定位到元素,使用上面的任何一个方法都可以。

原文地址:https://www.cnblogs.com/moonpool/p/5631550.html