网站首页 > 知识剖析 正文
关于XPath定位方法的系统总结,结合了各类语法特性及HTML代码示例说明不同XPath定位方法的使用场景和实现方式:
<!-- 登录表单 -->
<form id="loginForm" class="auth-form">
<div class="input-group">
<input type="text" id="username" placeholder="用户名">
<input type="password" name="pwd" data-testid="password-input">
</div>
<button type="submit" class="btn-primary">立即登录</button>
</form>
<!-- 商品列表 -->
<ul class="product-list">
<li class="item">手机 <span price="2999">¥2999</span></li>
<li class="item active">笔记本 <span price="5999">¥5999</span></li>
<li class="item">耳机 <span price="399">¥399</span></li>
</ul>
<!-- 操作菜单 -->
<div class="actions">
<a href="/cart" title="查看购物车"><i class="icon-cart"></i></a>
<a href="/profile" class="disabled">个人中心</a>
</div>
一、基础定位示例
1. 属性精准匹配定位用户名输入框:
//input[@id='username']
//*[@id='username'] //通用标签选择
2. 模糊匹配定位密码输入框(动态属性场景):
//input[contains(@data-testid, 'password')]
3. 逻辑运算符定位可用的提交按钮:
//button[@type='submit' and not(@disabled)]
4. 数值比较定位价格高于500的商品:
//span[@price > 500]/parent::li
二、路径定位示例
1. 绝对路径定位第一个商品价格(脆弱路径,不推荐):
/html/body/div[2]/ul/li[1]/span
2. 相对路径定位当前表单内的密码输入框:
//form[@id='loginForm']//input[@type='password']
三、轴定位实战
1. 同级导航定位第二个商品后的所有商品:
//li[@class='item'][2]/following-sibling::li
2. 层级穿透定位价格元素的父级<li>:
//span[text()='¥399']/ancestor::li[1]
3. 属性链式获取获取购物车图标的链接地址:
//a[contains(@title,'购物车')]/attribute::href
4. 动态元素追踪定位激活状态的商品:
//li[contains(@class,'active')]/descendant::span
四、复合定位案例
1. 排除干扰项定位非禁用状态的个人中心链接:
//a[text()='个人中心' and not(contains(@class,'disabled'))]
2. 多层过滤定位价格在300-500之间的商品:
//span[@price >= 300 and @price <= 500]/parent::li
3. 文本组合定位定位包含特定文字和价格的商品:
//li[contains(text(),'手机') and span[@price='2999']]
五、性能优化对比
1. 低效写法
//div//span[contains(@class,'price')] //全文档扫描
2. 优化写法
//ul[@class='product-list']/li/span[@class='item-price'] //限定上下文
六、特殊场景处理
1. 动态ID应对
//input[starts-with(@id,'user_')]
2. 部分匹配属性定位包含icon-前缀的图标:
//i[contains(@class,'icon-')]
3. 多层嵌套定位定位登录表单中的密码框:
//form[@id='loginForm']/div[@class='input-group']/input[@type='password']
通过结合具体HTML结构和业务场景的代码示例,可以更直观理解XPath定位策略的实际应用。建议在开发者工具中直接测试表达式(Chrome的XPath控制台快捷键:Ctrl+F),观察是否能准确匹配目标元素。
- 上一篇: 肖sir_python的xpath定位方法详解
- 下一篇:已经是最后一篇了
猜你喜欢
- 2025-06-23 肖sir_python的xpath定位方法详解
- 2025-06-23 用 JSP 连接 MySQL 登入注册项目实践(JSP + HTML + CSS + MySQL)
- 2025-06-23 定位猫-手机虚拟定位app(定位猫安卓免费下载2016)
- 2025-06-23 Html之position粘性定位(html固定定位语法)
- 2025-06-23 理解CSS中的百分比单位:相对尺寸的核心规则
- 2025-06-23 CSS 定位详解(css定位例子)
- 2025-06-23 干货 | CSS中的四种定位有什么区别?
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)