数据提取是爬虫的核心环节。本文详细介绍五种主流数据提取方法:JSON(处理结构化数据)、正则表达式、XPath、JSONPath、BeautifulSoup4(处理非结构化HTML)。掌握这些方法,让你的爬虫如虎添翼!
📊 结构化数据
格式:JSON、XML
处理:json.dumps/loads
📄 非结构化数据
格式:HTML、文本
处理:正则、XPath、BS4
💡 什么是 JSON?
JSON(JavaScript Object Notation)是一种轻量级数据交换格式,易于阅读和编写,方便机器解析和生成。常用于前后端数据交互场景。
字典 → JSON 字符串
import json
# json.dumps: Python字典 → JSON字符串
# indent=2: 缩进2空格
# ensure_ascii=False: 中文保持原样
json_str = json.dumps(mydict, indent=2, ensure_ascii=False)JSON 字符串 → 字典
import json
# json.loads: JSON字符串 → Python字典
my_dict = json.loads(json_str)💡 什么是 XPath?
XPath(XML Path Language)即XML路径语言,最初用于在XML文档中查找信息,现也适用于HTML文档。XPath将整个DOM视为树形结构进行定位,能轻松实现各种数据定位需求。
XPath 核心语法
/ | |
// | |
. | |
.. | |
@ | |
text() |
XPath 路径表达式示例
/bookstore | |
//book | |
//book/title/@lang | |
//book/title/text() | |
//title[@lang="eng"] | |
/bookstore/book[1] | |
/bookstore/book[last()] | |
//book/title[text()='Harry Potter'] |
XPath 实战示例
from lxml import etree
text = '''
<div><ul>
<li class="item-1"><a>first item</a></li>
<li class="item-1"><a href="link2.html">second item</a></li>
<li class="item-inactive"><a href="link3.html">third item</a></li>
<li class="item-1"><a href="link4.html">fourth item</a></li>
</ul></div>'''
html = etree.HTML(text)
# 提取 href 属性
href_list = html.xpath("//li[@class='item-1']/a/@href")
# 提取文本内容
title_list = html.xpath("//li[@class='item-1']/a/text()")🎯 XPath 使用要点
✅ 安装:pip install lxml
✅ 导包:from lxml import etree
✅ 解析:etree.HTML(text)
✅ 提取:data.xpath("//div/text()")
⚠️ 注意:返回结果都是列表类型
JSONPath 类似于 XPath,但专门用于解析多层嵌套的 JSON 数据。对于复杂的 JSON 结构,JSONPath 能快速定位提取所需数据。
语法对照表(XPath vs JSONPath)
/ | $ | |
. | @ | |
/ | . 或 [] | |
// | .. | |
* | * | |
[] | [] | |
| | [,] | |
[] | ?() |
💡 什么是正则表达式?
正则表达式(Regular Expression)是一种强大的文本匹配工具,通过特殊符号组合成"模式"来描述和匹配字符串。适用于处理复杂的、不规则的文本数据。
Python 中使用正则
import re
# match: 从字符串开头匹配
result = re.match(pattern, string)
# search: 搜索整个字符串,找到第一个匹配
result = re.search(pattern, string)
# findall: 找出所有匹配,返回列表
results = re.findall(pattern, string)
# sub: 替换匹配的内容
new_string = re.sub(pattern, repl, string)常用元字符
. | a.c | |
\d | \d{11} | |
\w | \w+ | |
\s | \s+ | |
^ | ^hello | |
$ | world$ | |
* | ab*c | |
+ | ab+c | |
? | colou?r | |
[] | [aeiou] | |
() | (\d+) | |
| | cat|dog |
实战示例:提取手机号和邮箱
import re
text ="联系方式:13812345678,邮箱 test@163.com"
# 提取手机号(11位数字)
phone = re.findall(r'1[3-9]\d{9}', text)
# 结果: ['13812345678']
# 提取邮箱
email = re.findall(r'\w+@\w+\.\w+', text)
# 结果: ['test@163.com']
# 提取标题内容
html ='<title>Python教程</title>'
title = re.findall(r'<title>(.*?)</title>', html)
# 结果: ['Python教程']🎯 正则表达式使用要点
✅ 导包:import re
✅ match() → 开头匹配
✅ search() → 搜索第一个
✅ findall() → 查找所有
✅ sub() → 替换内容
✅ 使用 r 前缀避免转义
⚠️ 复杂场景优先考虑 XPath/BS4
💡 什么是 BS4?
BeautifulSoup4 简称 BS4,是一个 HTML/XML 解析器。BS4 基于 DOM 树,API 非常人性化,支持 CSS 选择器,使用简单直观。
安装:pip install bs4
基本使用
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "lxml")
# 格式化输出
print(soup.prettify())find_all 方法参数
name | |
attrs | |
string | |
limit | |
find 方法
soup.find('title')返回第一个匹配结果
find_all 方法
soup.find_all('a')返回所有匹配的列表
CSS 选择器
标签名 | soup.select('a') | |
.class名 | soup.select('.sister') | |
#id名 | soup.select('#link1') | |
空格分隔 | soup.select('p #link1') | |
标签[属性] | soup.select('a[class]') |
获取数据
# 获取文本内容
for tag in soup.select('title'):
print(tag.get_text())
# 获取属性
for tag in soup.select('a'):
print(tag.get('href'))实战示例:提取新闻列表
from bs4importBeautifulSoup
html ='''
<div class="news-list">
<h2 class="title">Python入门教程</h2>
<ul>
<li class="item">
<a href="/python/1.html">第一章:变量</a>
</li>
<li class="item">
<a href="/python/2.html">第二章:循环</a>
</li>
<li class="item">
<a href="/python/3.html">第三章:函数</a>
</li>
</ul>
</div>'''
soup = BeautifulSoup(html,'lxml')
# 方法1:find + find_all
news_div = soup.find('div', class_='news-list')
title = news_div.find('h2', class_='title').get_text()
items = news_div.find_all('li', class_='item')
# 方法2:CSS选择器(更简洁)
title = soup.select_one('.news-list .title').get_text()
links = soup.select('.item a')
# 提取数据
forlinkinlinks:
item = {
'title': link.get_text(),
'href': link.get('href')
}
print(item)🎯 BeautifulSoup4 使用要点
✅ 安装:pip install bs4
✅ 导包:from bs4 import BeautifulSoup
✅ 解析:BeautifulSoup(html)
✅ find → 返回单个对象
✅ find_all/select → 返回列表
✅ get_text() → 获取文本
✅ get('属性名') → 获取属性
📌 五种方法对比总结
| JSON | ||
| 正则 | ||
| XPath | ||
| JSONPath | ||
| BS4 |
💡 作者推荐
推荐优先使用 BeautifulSoup4,CSS 选择器写法直观易上手。
其次推荐 XPath,可从浏览器开发者工具直接复制路径。
正则表达式适合处理不规则的文本数据,功能强大但语法较复杂。
觉得有用请点赞收藏 ⭐
欢迎转发分享