以下是 Python parsel 库的完整使用指南,整合官方文档与社区实践,覆盖安装、解析、数据提取及实战技巧:


🔧 一、安装与环境配置

pip install parsel# 基础安装
依赖库:自动安装 lxml(核心解析引擎)和 cssselect(CSS转XPath)。

二、核心功能与语法

1. 创建 Selector 对象

from parsel import Selector

# 从HTML字符串创建
html = "<div><h1>Title</h1></div>"
selector = Selector(text=html)

# 从网络请求创建(结合Requests)
import requests
response = requests.get("https://example.com")
selector = Selector(text=response.text)# [[3][11]]

2. 数据提取方法

方法用途示例
CSS选择器通过类名/ID/标签选择selector.css(".item::text").get() → 提取class="item"的文本
XPath复杂结构定位selector.xpath("//a[@href]/text()").getall() → 所有带链接的文本
正则表达式模糊匹配文本selector.css("p").re_first(r"\d+") → 首个数字
JMESPath解析JSON数据selector.css("script::text").jmespath("price").get() → JSON中的price

三、关键操作详解

1. 文本提取

  • 单元素文本

    title = selector.css("h1.title::text").get()# → "Title" [[11][21]]
  • 多元素文本

    items = selector.css(".item::text").getall()# → ["Item1", "Item2"]
  • 嵌套文本

    nested_text = selector.xpath("//div//span/text()").get()# 深层嵌套文本

2. 属性提取

# CSS选择器提取属性
link = selector.css("a::attr(href)").get()# → "https://example.com" [[21][31]]

# XPath提取属性
image_src = selector.xpath("//img/@src").get()# → "image.png"

3. 链式调用与嵌套查询

# 链式调用CSS与XPath
price = selector.css(".product").xpath("./span[@class='price']/text()").get()

# 遍历嵌套元素
for product in selector.css(".product-list > li"):
name = product.css("h2::text").get()
print(name)#

🔧 四、高级技巧

1. 处理默认值

# 提取失败时返回默认值
rating = selector.css(".rating::text").get(default="0")# → "0"

2. 正则表达式增强提取

# 提取价格中的数字
price_text = selector.css(".price::text").re_first(r"(\d+\.\d+)")# → "29.99"

3. 动态内容应对

# 等待异步加载(需配合Selenium)
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://example.com")
selector = Selector(text=driver.page_source)#

️ 五、常见问题与优化

1. 性能优化

  • 缓存解析结果:重复查询同一文档时复用Selector对象 。
  • 避免深层嵌套:精简XPath路径(如用//替代多层/div/span)。

2. 错误排查

问题解决方案
提取结果为空检查元素是否动态加载 → 结合Selenium
编码错误指定编码:Selector(text=html, encoding='utf-8')
复杂结构定位失败使用XPath轴:following-sibling::div

💻 六、实战案例:电商商品提取

from parsel import Selector
import requests

url = "https://example-store.com/products"
response = requests.get(url)
selector = Selector(text=response.text)

products = []
for item in selector.css(".product-card"):
name = item.css("h2::text").get().strip()
price = item.css(".price::text").re_first(r"\d+\.\d+")
link = item.css("a::attr(href)").get()
products.append({"name": name, "price": price, "link": link})

print(f"提取 {len(products)} 件商品")

输出

[{"name": "Product A", "price": "29.99", "link": "/product-a"}, ...]

💡 七、适用场景对比

解析库优势适用场景
Parsel支持XPath+CSS混合、正则扩展Scrapy项目、复杂页面
BeautifulSoupHTML树修改友好小型项目、快速原型
lxml纯XPath高性能XML解析、精确数据定位

提示

分类: 默认分类技术 标签: python爬虫Python爬虫数据采集parsel

评论

暂无评论数据

暂无评论数据

目录