WebDriver API 1---XPath(虫师《selenium3自动化测试实战--基于Python语言笔记9》)

XPath定位:find_element_by_xpath()方法

1.绝对路径定位

例如:百度输入框的绝对路径定位:

# 百度输入框
find_element_by_xpath("/html/body/div/div/div/div/div/form/span/input")
# 百度搜索按钮
find_element_by_xpath("/html/body/div/div/div/div/div/form/span[2]/input")
注意:span[2]表示当前层次下的第2个span

2.利用元素属性定位

find_element_by_xpath("//标签名或*[@属性=属性值]")

find_element_by_xpath("//input[@id = 'kw']")
find_element_by_xpath("//*[@id = 'kw']")

Xpath不局限于id,name,class属性值 ,只要能唯一标识一个元素

3.层级与属性结合

 find_element_by_xpath("//标签名1或*[@属性名 = ' 属性值']/标签名2")

如果一个元素本身没有唯一标识这个元素的属性值,可通过查找上一级元素。

例如:

 通过上级定位百度输入框:

find_element_by_xpath("//span[@class='bg s_ipt_wr']/input")

通过上上级定位百度输入框:

find_element_by_xpath("//form[@id='form']/span/input")

4.使用逻辑运算符

逻辑运算符and连接多个属性来查找元素,表示必须同时满足多个条件来定位元素

5.使用contains方法 

用于匹配一个属性中包含的字符串

例如:span标签的class属性为"bg s_ipt_wr"(上图标识数字10的位置)

find_element_by_xpath("//span[contains(@class,'s_ipt_wr')]/input")

6.使用text()方法

用于匹配显示文本信息

例如:

find_element_by_xpath("//a[text(),'新闻']")
# 等效于link text定位文本
find_element_link_text("新闻")

contains和text()结合使用:

find_element_by_xpath("//a[contains(text(),'一个很长的')]")
# 等效于 partial link 定位文本
find_element_by_partial_link_text("一个很长的")

猜你喜欢

转载自www.cnblogs.com/kite123/p/11452365.html