XPath定位元素技巧
2025-04-23
13
参考资料
XPath定位元素技巧
1. 基本语法
/
:从根节点开始选取(绝对路径)//
:从任意位置匹配(相对路径).
:当前节点..
:父节点@
:选取属性*
:匹配任意元素[]
:条件筛选
2. 常用定位方法
2.1 按标签名定位
//div // 匹配所有<div>元素 //input // 匹配所有<input>元素
2.2 按属性定位
//input[@id="username"] // 匹配id="username"的<input> //a[@href="https://example.com"] // 匹配指定链接的<a> //div[@class="container"] // 匹配class="container"的<div>
2.3 按文本内容定位
//button[text()="Submit"] // 精确匹配文本 //a[contains(text(), "Login")] // 模糊匹配文本
2.4 模糊匹配属性
//input[contains(@class, "search")] // 匹配class包含"search"的<input> //div[starts-with(@id, "header-")] // 匹配id以"header-"开头的<div>
2.5 逻辑运算(and / or)
//input[@type="text" and @name="email"] //div[@class="box" or @class="panel"]
2.6 索引定位
(//div)[1] // 匹配第一个<div> //ul/li[3] // 匹配<ul>下的第3个<li>
3. 高级用法
3.1 轴定位(Axis)
轴名称 | 说明 | 示例 |
---|---|---|
ancestor | 所有祖先节点 | //div//ancestor::body |
child | 直接子节点 | //ul/child::li |
following | 之后的节点 | //h1/following::p |
preceding | 之前的节点 | //p/preceding::h1 |
parent | 父节点 | //span/parent::div |
3.2 函数扩展
//div[last()] // 匹配最后一个<div> //input[not(@disabled)] // 匹配未禁用的<input> //li[position() < 3] // 匹配前两个<li>
4. 示例
4.1 基础示例
//input[@name="username"] // 用户名输入框 //button[text()="Login"] // 登录按钮 //a[@href="/logout"] // 退出链接
4.2 组合示例
//form[@id="login"]//input[@type="text"] // 登录表单内的文本输入框 //div[@class="product"]/h3[contains(text(), "iPhone")] // 商品标题含"iPhone"的<h3>
4.3 复杂示例
//table[@id="orders"]//tr[td[2] > 100] // 订单金额大于100的行 //div[contains(@class, "active") and not(@hidden)] // 可见且class含"active"的<div>
5. 注意事项
避免过度依赖索引(如
//div[3]
),页面结构变化时易失效优先使用唯一属性(如
id
、name
)模糊匹配(
contains
、starts-with
)适用于动态内容XPath 1.0 是主流版本,部分浏览器支持 XPath 2.0+
适用于 Selenium、Scrapy、Playwright 等自动化测试和爬虫工具。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。