(五)selenium定位方式Xpath

豆瓣网: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.* 通配符

例如:

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

posted @   mygrace  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示