您的位置:首页 > 编程语言 > Java开发

java selenium webdriver实战 页面元素定位

2016-10-19 11:20 603 查看
自动化测试实施过程中,测试程序中常用的页面操作有三个步骤

1.定位网页上的页面元素,并存储到一个变量中

2.对变量中存储的页面元素进行操作,单击,下拉或者输入文字等

3.设定页面元素的操作值,比如,选择下拉列表中的那个下拉列表或者输入框中输入什么值

其中定位页面元素是三步骤的第一步,本篇介绍常用的定位方法

 

webDriver对象的findElement函数用于定位一个页面元素,findElements函数用户定位多个页面元素,定位的页面元素使用webElement对象进行存储

常用的方法有:

1.使用ID定位

driver.findElement(By.id("ID值"));
WebElement element = driver.findElement(By.id("username"));


 

2.使用name定位

driver.findElement(By.name("name值"));
WebElement element = driver.findElement(By.name("username"));


 

3.使用链接的全部文字定位

driver.findElement(By.linkText("链接的全部文字内容"));
driver.findElement(By.linkText("我的项目"));


 

4.使用部分链接文字定位

driver.findElement(By.partialLinkText("链接的部分文字内容"));
driver.findElement(By.partialLinkText("项目"));


 

5.使用xPath方式定位

XPATH是一门在XML文档中查找信息的语言,它是XML Path的简称.
XPATH可用来在XML文档中对元素和属性进行遍历,提供了浏览树的能力
这个方法是非常强大的元素查找方式,使用这种方法几乎可以定位到页面上的任意元素.
浏览器都自带html导出xPath的功能

这里导出的xPath为://*[@id="lst-ib"]
1.xPath绝对定位
查找value值为button的div

webElement button = driver.findElement(By.xpath("/html/body/div/input[@value='查询']"));


使用绝对路径方式是十分脆弱的,因为即便也买你代码发生了微小的变化,也会造成原有的xPath表达式定位失败

2.使用相对路径定位

webElement button = driver.findElement(By.xpath("//div/input[@value='查询']"));


实用举例:

 

查询第二个input,xPath是从1开始的

driver.findElement(By.xpath("//input[2]"));


定位页面的第一张图片

driver.findElement(By.xpath("//img[@href='xxx']"));


定位第二个div中第一个input输入框

driver.findElement(By.xpath("(//div[@class='mob-share-list'])[2]/input[1]"));


模糊定位:start-with

寻找rel属性以ahaha开头的a元素

driver.findElement(By.xpath("//a[starts-with(@rel,'ahaha')]"));


模糊定位:contains

需找内容含有提交二字的button

driver.findElement(By.xpath("//button[contains(text(),'提交')]"));


寻找rel属性包含ahaha的a元素

driver.findElement(By.xpath("//a[contains(@rel,'ahaha')]"));


 

 

5.使用css方式定位

driver.findElement(By.cssSelector("css定位表达式"));
driver.findElement(By.cssSelector("img.plusImg"));
driver.findElement(By.cssSelector("input[type='button']"));
driver.findElement(By.cssSelector("input#div1input"));//根据id的属性值
driver.findElement(By.cssSelector("Img[alt='img1'][href='http://www.sougou.com']"));


 

 

6.使用class名称定位

driver.findElement(By.className("页面的class属性值"));
driver.findElement(By.className("tight left"));//要写全


 

7.使用标签名称定位

driver.findElement(By.tagName("页面的html标签名称"));

webElement element = driver.findElement(By.tagName("a"));
list<webElement> elements = driver.findElements(By.tagName("a"));


 

8.使用js表达式

((JavascriptExecutor) driver).executeScript("js表达式");
JavascriptExecutor js1 = (JavascriptExecutor) driver;
js1.executeScript("document.getElementsByClassName(\"ke-edit-iframe\")[0].setAttribute(\"name\",\"frame-name\")");


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息