python爬虫获取手机评论数据
以下是包含 JSON文件存储功能 的完整代码,已标注好你需要修改的3处核心位置(用 # 需修改 标注):
import requests
from bs4 import BeautifulSoup
import time
import json # 新增:用于写入JSON文件
# 1. 配置请求头(模拟浏览器,避免被识别为爬虫)
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", # 需修改:替换成你自己的User-Agent
"Referer": "https://item.jd.com/"
}
# 2. 定义抓取函数(单页评论)
def get_phone_comments(page, product_id):
# 京东评论接口
url = f"https://club.jd.com/comment/productPageComments.action?productId={product_id}&score=0&sortType=5&page={page}&pageSize=10"
try:
time.sleep(1.5) # 延迟,反爬
response = requests.get(url, headers=headers)
response.raise_for_status() # 捕获请求错误
data = response.json()
# 提取评论核心信息
comments = []
for comment in data["comments"]:
comment_info = {
"用户": comment["nickname"],
"评分": comment["score"],
"评论时间": comment["time"],
"评论内容": comment["content"].strip()
}
comments.append(comment_info)
return comments
except Exception as e:
print(f"第 {page+1} 页抓取失败:{str(e)}")
return []
# 3. 主程序(多页抓取 + 写入JSON)
if __name__ == "__main__":
# 核心配置:3处需修改的位置
product_id = "100062815823" # 需修改:替换成目标手机的商品ID
total_pages = 5 # 需修改:调整要抓取的总页数(建议先1-2页测试)
json_file_name = "手机评论数据.json" # 可选修改:自定义JSON文件名称
all_comments = []
# 循环抓取多页
for page in range(total_pages):
print(f"正在抓取第 {page+1} 页...")
page_comments = get_phone_comments(page, product_id)
all_comments.extend(page_comments)
# 打印抓取结果
print(f"\n抓取完成!共获取 {len(all_comments)} 条手机评论")
# 写入JSON文件
with open(json_file_name, "w", encoding="utf-8") as f:
json.dump(all_comments, f, ensure_ascii=False, indent=2)
print(f"评论已保存到【{json_file_name}】(与代码文件同一目录)")
再次明确需你手动修改的3处(缺一不可)
User-Agent:百度搜索“我的User-Agent”,复制当前浏览器的标识,替换代码中对应的值(避免被识别为爬虫)。product_id:打开京东目标手机商品页,从URL中提取数字ID(如https://item.jd.com/123456789.html中的123456789),替换示例ID。total_pages:根据需求调整页数(如想抓3页就改成3),初期建议先设为1测试是否能正常生成JSON文件。
浙公网安备 33010602011771号