(五)selenium定位方式Xpath

发布时间 2023-06-27 15:30:45作者: mygrace

豆瓣网:https://book.douban.com/ 作为例子,更好的理解和探索Xpath的定位方法(网页定期更新后如果元素不存在了,请参考截图)

简单的定位例子:

//div[@class='top-nav-info']

准备工作:

 打开网页elements: ctrl+shift+c

 自带的定位:ctrl+f (也有好用的工具例如:POM或chropath 更好定位元素)

 

xpath用法:

1. //input[@name=" "]

2. and 组合属性

例如://input[@name='q' and @type='text']

3. 单斜杠通过父亲找儿子

例如: //div/input 

4. 通过祖先找子孙

例如://div//input 

5. 儿子找父亲

例如://div[@class='anony-srh']/../../..

6. 通过文本

例如://a[text()="豆瓣读书"]  通过文本

7. text() 经常和contains 组合使用:

例如:

//*[contains(text(),"豆瓣读书")]

//a[contains(@class,'anony')]

8. 索引有两个注意事项:1、加括号 2、索引从1开始

例如:(//a[contains(text(),"豆瓣读书")])[1]

9.轴:一般不用,除非特别复杂

弟弟:follow-sibling

哥哥:preceding-sibling

祖先:ancestor

例如:

(//a[contains(text(),"豆瓣读书")])//ancestor::div[@id='anony-nav']
 
//*[@class='account-form-3rd-hd']//following-sibling::div//preceding-sibling::div

10.* 通配符

例如:

//a[contains(text(),"豆瓣读书")]