在互联网数据的海洋中,Python爬虫是我们获取信息的“渔网”。然而,捕捞上来的往往是混杂着HTML标签的网页源码,或是结构嵌套复杂的JSON数据。如何将这些原始数据转化为干净、可用的结构化信息,是爬虫开发中最核心的环节。
本文将带你深入了解Python爬虫中两大主流数据格式(HTML与JSON)的解析技巧,并分享高效的数据清洗实战经验。
工欲善其事,必先利其器。在开始之前,我们需要安装几个强大的第三方库:
安装命令:
pip install requests beautifulsoup4 lxml pandasHTML解析通常用于传统的静态网页。我们以解析一个模拟的图书列表页面为例,演示如何使用 BeautifulSoup 和 XPath。
场景假设:我们要抓取一个图书网站,提取书名、作者和价格。
import requests
from bs4 import BeautifulSoup
from lxml import etree
def parse_html_with_bs4(url):
"""
使用 BeautifulSoup 解析 HTML
"""
try:
# 1. 发送请求
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
response = requests.get(url, headers=headers, timeout=10)
response.encoding = 'utf-8' # 确保编码正确
# 2. 初始化 BeautifulSoup 对象 (使用 lxml 解析器速度更快)
soup = BeautifulSoup(response.text, 'lxml')
# 3. 定位并提取数据
# 假设所有图书都在 class="book-item" 的 div 中
books = soup.find_all('div', class_='book-item')
data_list = []
for book in books:
# 提取书名,使用 get_text 获取文本内容,strip() 去除首尾空白
title = book.find('h2', class_='title').get_text(strip=True)
# 提取价格,假设价格标签内包含货币符号,需要后续清洗
price_tag = book.find('span', class_='price')
price = price_tag.get_text(strip=True) if price_tag else "N/A"
# 提取作者 (假设在 p 标签中)
author = book.find('p', class_='author').get_text(strip=True)
data_list.append({
'书名': title,
'作者': author,
'价格': price
})
return data_list
except Exception as e:
print(f"请求或解析出错: {e}")
return []
def parse_html_with_xpath(url):
"""
使用 lxml 和 XPath 解析 HTML (适合复杂结构)
"""
try:
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers)
# 1. 将 HTML 文本转换为 lxml 的 Element 对象
html = etree.HTML(response.text)
# 2. 使用 XPath 定位节点
# //div[@class="book-item"] 表示查找所有 class 为 book-item 的 div
book_nodes = html.xpath('//div[@class="book-item"]')
data_list = []
for node in book_nodes:
# 使用 xpath 提取文本,[0] 表示取第一个匹配项
title = node.xpath('./h2[@class="title"]/text()')
title = title[0].strip() if title else "未知书名"
price = node.xpath('./span[@class="price"]/text()')
price = price[0].strip() if price else "0"
data_list.append({'书名': title, '价格': price})
return data_list
except Exception as e:
print(f"XPath解析出错: {e}")
return []现代网站(尤其是单页应用SPA)常通过Ajax异步加载数据,返回格式多为JSON。直接请求API接口往往比解析HTML更高效、更稳定。
场景假设:请求一个返回用户信息的API接口。
import requests
import json
api_url = wlt.srctzs.com
def parse_json_data(api_url):
"""
解析 JSON 格式的 API 响应
"""
try:
# 1. 发送请求
response = requests.get(api_url, timeout=10)
# 检查 HTTP 状态码
response.raise_for_status()
# 2. 将响应体直接转换为 Python 字典
# requests 内置的 json() 方法会自动处理解码
data = response.json()
# 3. 提取嵌套数据
# 假设数据结构为: {"status": 200, "data": {"users": [{"id": 1, "name": "Alice", "meta": {"age": 25}}, ...]}}
if data.get('status') == 200:
users = data['data']['users']
clean_users = []
for user in users:
# 安全地获取嵌套字段,防止 KeyError
user_id = user.get('id')
name = user.get('name')
# 使用 .get() 方法并提供默认值,防止 meta 字段不存在报错
age = user.get('meta', {}).get('age', '未知')
clean_users.append({
'ID': user_id,
'姓名': name,
'年龄': age
})
return clean_users
else:
print("API 返回错误状态")
return []
except requests.exceptions.RequestException as e:
print(f"网络请求错误: {e}")
except json.JSONDecodeError:
print("JSON 解析错误: 响应内容不是有效的 JSON")
except Exception as e:
print(f"数据处理错误: {e}")
return []抓取下来的数据往往“脏”得让人头疼:价格带有货币符号、日期格式不统一、存在空值或重复项。此时,Pandas 是最佳选择。
数据清洗实战代码:
import pandas as pd
import re
def clean_data(raw_data):
"""
使用 Pandas 进行数据清洗
raw_data: 上一步骤抓取到的字典列表
"""
# 1. 转换为 DataFrame
df = pd.DataFrame(raw_data)
print("清洗前数据预览:\n", df.head())
# 2. 去除重复行
df.drop_duplicates(inplace=True)
# 3. 处理缺失值 (例如:删除关键字段为空的行,或填充默认值)
df.dropna(subset=['书名'], inplace=True) # 假设书名必须有
df['价格'] = df['价格'].fillna('0.00') # 价格缺失填0
# 4. 字符串清洗 (使用正则表达式)
# 假设价格原始数据为 "¥123.45元" 或 "价格: $50",我们需要提取纯数字
def extract_price(text):
if not isinstance(text, str):
return 0.0
# 匹配数字和小数点
match = re.search(r'[\d.]+', text)
return float(match.group()) if match else 0.0
df['价格'] = df['价格'].apply(extract_price)
# 5. 数据类型转换
# 确保价格是 float 类型,方便后续计算
df['价格'] = df['价格'].astype(float)
# 6. 去除字符串两端的空白字符
# 对 '书名' 和 '作者' 列应用 strip 方法
if '作者' in df.columns:
df['作者'] = df['作者'].astype(str).str.strip()
df['书名'] = df['书名'].astype(str).str.strip()
print("清洗后数据预览:\n", df.head())
return df
def save_to_csv(df, filename='output.csv'):
"""
保存数据到 CSV 文件 (使用 utf-8-sig 编码防止 Excel 打开乱码)
"""
df.to_csv(filename, index=False, encoding='utf-8-sig')
print(f"数据已成功保存至 {filename}")构建一个健壮的爬虫系统,除了代码逻辑,还需要注意以下几点:
robots.txt,尊重网站的爬虫规则。User-Agent,避免被服务器识别为机器人直接拦截。time.sleep() 添加延时,避免高频请求给目标服务器造成压力,导致IP被封禁。try-except 块,确保程序不会因为单页错误而崩溃。通过结合 requests 的灵活性、BeautifulSoup/lxml 的解析能力以及 Pandas 的清洗功能,你可以轻松应对绝大多数的数据采集需求。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。