Selenium-xpath详解

时间:2021-11-12 10:47:38

1、XPATH是什么

XPATH是一门在XML文档中查找信息的语言,XPATH可用来在XML文档中对元素和属性进行遍历,主流的浏览器都支持XPATH,因为HTML页面在DOM中表示为XHTML文档。
XPATH语言是基于XML文档的树结构,并提供了浏览树的能力,通过多样的标准来选择节点。
Selenium WebDriver支持使用XPATH表达式来定位元素。
XPATH和CSS选择器最重要的区别是XPATH可以向前和向后查询DOM结构的元素,而CSS选择器只能向前查询,这意味着XPATH可以通过子元素来定位父元素!

2、XPATH使用方法

使用XPATH有如下几种方法定位元素(相比CSS选择器,方法稍微多一点):

a、通过绝对路径定位元素(不推荐!)

WebElement ele = driver.findElement(By.xpath("html/body/div/form/input"));

b、通过相对路径定位元素

WebElement ele = driver.findElement(By.xpath("//input"));

c、使用索引定位元素

WebElement ele = driver.findElement(By.xpath("//input[4]"));

d、使用XPATH及属性值定位元素

WebElement ele = driver.findElement(By.xpath("//input[@id='fuck']"));
//其他方法(看字面意思应该能理解吧)
WebElement ele = driver.findElement(By.xpath("//input[@type='submit'][@name='fuck']"));
WebElement ele = driver.findElement(By.xpath("//input[@type='submit' and @name='fuck']"));
WebElement ele = driver.findElement(By.xpath("//input[@type='submit' or @name='fuck']"));

e、使用XPATH及属性名称定位元素

//查找所有input标签中含有type属性的元素
WebElement ele = driver.findElement(By.xpath("//input[@type]"));

f、部分属性值匹配(和CSS选择器类似)

WebElement ele = driver.findElement(By.xpath("//input[start-with(@id,'fuck')]"));//匹配id以fuck开头的元素,id='fuckyou'
WebElement ele = driver.findElement(By.xpath("//input[ends-with(@id,'fuck')]"));//匹配id以fuck结尾的元素,id='youfuck'
WebElement ele = driver.findElement(By.xpath("//input[contains(@id,'fuck')]"));//匹配id中含有fuck的元素,id='youfuckyou'

g、使用任意值来匹配属性及元素

WebElement ele = driver.findElement(By.xpath("//input[@*='fuck']"));//匹配所有input元素中含有属性的值为fuck的元素

h、使用XPATH轴来定位元素

//XPATH轴没有实际经验,所以本文不讨论它。

元素定位总结

//注:本专题只介绍java版
//By id
WebElement ele = driver.findElement(By.id());
//By Name
WebElement ele = driver.findElement(By.id());
//By className
WebElement ele = driver.findElement(By.className());
//By tabName
WebElement ele = driver.findElement(By.tagName());
//By linkText
WebElement ele = driver.findElement(By.linkText());
//By partialLinkText
WebElement ele = driver.findElement(By.partialLinkText());//通过部分文本定位连接
//By cssSelector
WebElement ele = driver.findElement(By.cssSelector());
//By XPATH
WebElement ele = driver.findElement(By.xpath());