xpath

我们平时在使用seleinum定位元素时,会经常使用到xpath定位,下面就来谈谈xpath定位相关知识。

xpath核心用法写法://元素标签名[@属性名='属性值'],例如://input[@name='password']

双斜杠开头:相对路径
单斜杠开头:绝对路径

1、多个条件的组合
//input[@name='password'][@type='text'] 或 //input[@name='password' and @type='text']

2、根据父级元素查找子元素:元素本身特征不明显,但是其父级元素特征很明显
//form[@method='post']/input[@name='password']

3、根据子级元素查找父元素:元素本身特征不明显,但是其子级元素特征很明显
//input[@name='password']/..

4、通过祖先元素查找子孙元素(跨代):
//div[@id='status']//input[@name='password']

5、通过子孙元素查找祖先元素(跨代):
//input[@name='password']/../../..       隔了几层就几个/..

6、根据text文本查找元素:
//div[text()='application_date']
注:与driver.find_element('link_text')相比,通过text文本可以查找任意类型标签元素,而driver.find_element('link_text')只能查找a标签元素

7、根据包含关系查找元素:不仅仅可以用在text()文本上
//div[contains(text(), 'application_d')]
//div[contains(@name, 'application_d')]
//div[contains(@class, 'application_d')]

8、轴运算:找祖先、兄妹、子孙元素皆可
//input[@name='password']/preceding-sibling::input[@name='username']        找哥哥元素
//input[@name='password']/following-sibling::input[@name='username']         找妹妹元素
//input[@name='password']/ancestor::div[@name='info']                 找祖先元素

posted @ 2022-07-30 18:51  少年不太冷2  阅读(207)  评论(0)    收藏  举报