(五)、Python自动化测试--Selenium之Xpath和css定位

1、xpath 是一种再XML文档中定位元素的语言。因为HTML可以看做XML的一种实现,所以可以使用xpath定位方式。

表达式

描述

/

从匹配选择的当前节点选择文档中的节点

//

从根节点选取

.

选取当前节点

选取当前节点的父节点

@

选取属性

*

匹配任何元素节点

@*

匹配任何属性节点

node()

匹配任何类型的节点

2、CSS (Cascading Style Sheets)是一种语言,它用来描述HTML XML文档的表现,CSS使用选择器来为页面元素绑定属性。

3、xpath定位:

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及属性名称定位元素 元素属性类型:@id 、@name、@type、@class、@tittle //查找所有input标签中含有type属性的元素 WebElement ele = driver.findElement(By.xpath("//input[@type]"));

f、部分属性值匹配 WebElement ele = driver.findElement(By.xpath("//input[start-with(@id,'fuck')]")); //匹配id以fuck开头的元素,id='fuckyou' 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的元素。

4、css定位:

元素层级css还支持三个方法,分别是first-child、last-child、nth-child(n)

(1)first-child:第一个后代元素

(2)last-child:最后一个后代元素

(3)nth-child(N):指定第N个后代元素下面举例:

(a)input:first-child  定位所有层次第一个为input的元素,注意是第一个元素为input标签的

(b)span input:first-child   定位span标签下,第一个为input标签的元素

(c)span :last-child  定位span标签下,最后一个元素

(d)span input:last-child   定位span标签下,最后一个为input标签的元素

(e)span :nth-child(2) 定位span标签下,第二个元素

(f)form.fm>:nth-child(2) 定位form标签,class等于fm下的第二个元素

发布了138 篇原创文章 · 获赞 21 · 访问量 22万+

猜你喜欢

转载自blog.csdn.net/grl18840839630/article/details/104735652