从下图中可以看到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.层级与属性结合  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 <!DOCTYPE html>
2 <html>
3 <head>
4 <body link="#0000cc">
5 <div id="swfEveryCookieWrap" data-for="result" style="width: 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 }

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

selenium定位方法(java实例)(二)的更多相关文章

  1. selenium定位方法实例

    selenium定位方法实例 首先打开浏览器输入微博的网址,将网页最大化,等待3秒 from selenium import webdriver import time driver = webdri ...

  2. selenium定位方法(二)

    selenium定位方法(二)  1.xpath定位:xpath是在XML中查找节点所在的路径的表达式 1)绝对路径的Xpath表达式 例:/html/body/div/div[1]/ul//li[3 ...

  3. selenium定位方法(一)

    selenium定位方法-(一) 1.定位页面元素的方式(By类的方法) 1)id定位:通过页面元素的id属性值来定位一个页面元素       注意事项:如果每次刷新网页之后元素的id属性值都不同,说 ...

  4. selenium定位方法-iframe元素定位方法

    在自动化测试中,如果无法定位到一个元素,那么最大的可能是定位的元素是在iframe框架中,iframe对象代表一个HTML的内联框架,在HTML中,iframe每出现一次,一个iframe对象就会被创 ...

  5. selenium定位方法

  6. Java 学习(21):Java 实例

    Java 实例 本章节我们将为大家介绍 Java 常用的实例,通过实例学习我们可以更快的掌握 Java 的应用. Java 环境设置实例 //HelloWorld.java 文件 public cla ...

  7. Java - 35 Java 实例

    Java 实例 本章节我们将为大家介绍 Java 常用的实例,通过实例学习我们可以更快的掌握 Java 的应用. Java 环境设置实例 Java 实例 – 如何编译一个Java 文件? Java 实 ...

  8. Java-Runoob-高级教程:Java 实例

    ylbtech-Java-Runoob-高级教程:Java 实例 1.返回顶部 1. Java 实例 本章节我们将为大家介绍 Java 常用的实例,通过实例学习我们可以更快的掌握 Java 的应用. ...

  9. Java 实例

    Java 实例 本章节我们将为大家介绍 Java 常用的实例,通过实例学习我们可以更快的掌握 Java 的应用. Java 环境设置实例 Java 实例 – 如何编译一个Java 文件? Java 实 ...

随机推荐

  1. Android JSBridge的原理与实现

    在Android中.JSBridge已经不是什么新奇的事物了,各家的实现方式也略有差异. 大多数人都知道WebView存在一个漏洞.见WebView中接口隐患与手机挂马利用,尽管该漏洞已经在Andro ...

  2. DataGridView在Cell编辑状态响应回车键下的KeyPress/KeyDown/KeyUp事件

    我们知道由于DataGridView的单元格DataGridCell处于编辑的时候,当你按Enter键,那么DataGridView是不会激发KewPress/KeyDown/KeyUp这些事件的,因 ...

  3. 在python中配置MySQL数据库

    MySQL数据库(1) 尽管用文件形式将数据保存到磁盘,已经是一种不错的方式.但是,人们还是发明了更具有格式化特点,并且写入和读取更快速便捷的东西——数据库(如果阅读港台的资料,它们称之为“资料库”) ...

  4. 清理linux 某个文件夹下面所有的log文件

    #!/bin/sh #目标文件夹下面所有问题 target_dir="/app/" #删除2天前新建的后缀为log的文件 -name "*.log" -exec ...

  5. IO模型-java版

    描述IO,我们需要从两个层面: 编程语言 实现原理 底层基础 从编程语言层面 BIO | NIO | AIO 以Java的角度,理解,linux c里也有AIO的概念(库),本文只从Java角度入手. ...

  6. onethink后台边栏,添加新的方法后不显示,是需要在后台系统中添加功能,如下图

  7. Cocos2d-x stack corruption detected: aborted

    adb logcat错误 :堆栈错误,,或者访问过界...通常不太好调试:: 但是以下两种情况最最常见: 1. ]; strcpy(aa,"abcdefghijk123457890" ...

  8. hdoj 1166 敌兵布阵 线段数和树状数组

    敌兵布阵 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Submis ...

  9. 九、Null在Java中的精确表示

    让我们从下面的语句开始: String x = null; 1.           这个语句具体的做了什么? 回一下什么是变量和什么是值.通常的比喻是变量类似于一个盒子. 就像你可以用盒子来存储东西 ...

  10. 【Maven学习】Maven打包生成包含所有依赖的jar包

    http://blog.csdn.net/u013177446/article/details/54134583 ******************************************* ...