XPATH

XPATH counts from 1

Python counts from 0


Differnece between signle '/' or double '//':

Single slash '/' anywhere in xpath signifies to look for the element immediately inside the parent element.

Double slash '//' signifies to look for any child or nested-child element inside the parent element.


Using Text of  the element to build xpath:

//div[@class='homepage-hero']//a[text()='Enroll now']

Using contains to find the elements:

//div[@id='navbar']//a[contains(@class,'navbar-link') and contains(@href,'sign_in')]

Using Starts-With to find the elements:

//div[@id='navbar']//a[starts-with(@class,'navbar-link')]


Parent/Preceding Sibling/Following Sibling

//parent::<tag>
//preceding-sibling::<tag>
//following-sibling::<tag>


XPath 是一种用于在 XML 和 HTML 文档中定位和选择节点的强大语言。它广泛应用于网页数据抓取、自动化测试等领域,通过路径表达式可以精准获取所需的数据。 ### 基础语法 #### 节点选取 - `nodename`:选择该名称的所有子节点。 - `/`:从根节点开始选取。 - `//`:无论当前所处位置如何,均可匹配任意符合条件的节点。 - `.`:表示当前节点。 - `..`:表示父节点。 - `@attribute_name`:选取特定属性。 例如,在下面这个简单的 XML 结构里: ```xml <bookstore> <book> <title lang="eng">Harry</title> <price>29</price> </book> <book> <title lang="kmg">Learning</title> <price>39.95</price> </book> </bookstore> ``` 我们可以使用如下 XPath 表达式: - 获取所有 `<book>` 元素:`/bookstore/book` - 获取第一个 `<book>` 的价格:`/bookstore/book[1]/price/text()` #### 特殊操作符 - `*`:通配符,代表任何元素节点。 - `text()`:提取文本内容。 - `last()`:返回最后一个项目的索引号。 - `contains(., '部分文字')` 或者 `contains(@attr, 'value_part')` :模糊匹配字符串的一部分。 ### Python 中的应用实例 要处理 HTML 并执行 XPath 查询,通常会利用到第三方库如 `lxml` 。以下是具体的操作流程以及示例代码: ```python import requests from lxml import etree as le url = "https://www.runoob.com/html/html-tutorial.html" response = requests.get(url) html_content = response.content.decode('utf-8') # 将接收到的HTML转换为XML对象以便后续解析 tree = le.HTML(html_content) # 应用XPath来筛选目标数据;这里假设我们想获得侧边栏菜单项 menu_items = tree.xpath('//div[@id="leftcolumn"]/a/text()') for item in menu_items: print(item.strip()) ``` 这段脚本演示了怎样访问指定网址并从中抽取左侧栏目里的链接标题[^3]。 ### 开发辅助工具 为了更高效地编写与调试 XPath 表达式,推荐安装浏览器扩展程序比如 Chrome 上的 **XPath Helper** 或 Firefox 自带的开发者选项中的相应功能。这类工具有助于即时查看不同查询语句的效果,从而快速调整至最优状态[^2]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值