基于 Python 实现的淘宝商品评论爬虫,核心目标是爬取指定淘宝商品的评论数据(评论内容、评分、买家昵称、评论时间等),并保证代码可运行、易理解,同时适配淘宝的反爬机制。
实现思路
- 接口分析:淘宝评论数据通过 Ajax 异步加载,可通过抓包获取评论接口(淘宝评论接口需携带
_ksTS、callback等动态参数,核心依赖商品 ID 和页码); - 请求构造:模拟浏览器请求头,添加 Cookie(需手动登录获取)、User-Agent 等关键参数,绕过基础反爬;
- 数据解析:处理返回的 JSONP 格式数据,提取核心评论字段;
- 数据保存:将爬取结果保存为 CSV 文件,方便后续分析;
- 异常处理:添加请求超时、数据解析失败等异常捕获,保证爬虫稳定性;
- 反爬适配:添加随机延时,避免请求频率过高导致账号 /IP 被限制。
前置准备
- 安装依赖库:
pip install requests json5 pandas
- 获取淘宝 Cookie:
- 打开淘宝商品页,登录账号;
- 按 F12 打开开发者工具 → 切换到「网络」标签 → 刷新页面,筛选「XHR」请求;
- 找到任意评论相关请求,复制其「Cookie」字段(完整复制,这是爬虫能正常请求的核心)。
完整代码
import requests
import json5
import csv
import time
import random
from urllib.parse import urlencode
# -------------------------- 配置项 --------------------------
ITEM_ID = "690907351225" # 淘宝商品 ID(从商品链接中提取)
PAGE_NUM = 5 # 要爬取的评论页数(淘宝单页 20 条评论)
CSV_FILE = "taobao_comments.csv" # 保存评论的 CSV 文件名
COOKIE = "你的淘宝 Cookie,完整复制" # 替换为你自己的淘宝 Cookie(必须!否则请求会被拦截)
# -------------------------- 请求头配置 --------------------------
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
"Cookie": COOKIE,
"Referer": f"https://item.taobao.com/item.htm?id=",
: ,
: ,
: ,
:
}
():
timestamp = ((time.time() * ))
random_str = (random.randint(, ))
_ksTS =
callback =
params = {
: callback,
: ,
: ,
: ,
: item_id,
: page,
: ,
: ,
: ,
: ,
: _ksTS,
: ,
:
}
url =
:
response = requests.get(url, headers=HEADERS, timeout=)
response.raise_for_status()
json_data_str = response.text.lstrip().rstrip()
data = json5.loads(json_data_str)
comments = []
data data[]:
comment data[]:
comment_info = {
: comment.get(, ),
: comment.get(, ).replace(, ).strip(),
: comment.get(, ),
: comment.get(, ),
: comment.get(, ),
: comment.get(, {}).get(, ).replace(, ).strip(),
: comment.get(, {}).get(, )
}
comments.append(comment_info)
comments
requests.exceptions.RequestException e:
()
[]
json5.JSON5DecodeError e:
()
[]
Exception e:
()
[]
():
comments:
headers = [, , , , , , ]
(file_path, , encoding=) f:
writer = csv.DictWriter(f, fieldnames=headers)
f.tell() == :
writer.writeheader()
writer.writerows(comments)
__name__ == :
()
(CSV_FILE, , encoding=) f:
total =
page (, PAGE_NUM + ):
()
comments = get_taobao_comments(ITEM_ID, page)
comments:
save_to_csv(comments, CSV_FILE)
total += (comments)
()
:
()
time.sleep(random.uniform(, ))
()

