gpt-4-0314· OpenAI
WildChat-4.8M (AI2)
帮我写一个抓取京东商品评论的脚本
- User
帮我写一个抓取京东商品评论的脚本
- Assistant
这是一个使用Python和BeautifulSoup库的京东评论抓取脚本。注意这个脚本仅用于演示学习目的,实际使用前请确保遵守京东和地区相关法律法规。
import requests from bs4 import BeautifulSoup import json # 设置请求头信息,模拟浏览器请求 headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3" } # 从URL中提取产品ID def get_product_id(url): return url.split('/')[-1].split('.')[0] # 从JSON代码中提取评论数据 def parse_json(json_data): comments = [] for item in json_data['comments']: comment = { 'user_name': item['nickname'], 'content': item['content'], 'creation_time': item['creationTime'], 'score': item['score'], 'product_color': item['productColor'], 'product_size': item['productSize'] } comments.append(comment) return comments # 获取产品评论的函数 def get_product_comments(product_id: str, page: int): url = f"https://club.jd.com/comment/skuProductPageComments.action?callback=fetchJSON_comment98&productId={product_id}&score=0&sortType=5&page={page}&pageSize=10&isShadowSku=0&rid=0&fold=1" response = requests.get(url, headers=headers) result = response.text.lstrip('fetchJSON_comment98(').rstrip(');') jd_comments = json.loads(result) comments = parse_json(jd_comments) return comments # 主函数 def main(): # 抓取的产品页面 product_url = "https://item.jd.com/5641552.html" product_id = get_product_id(product_url) # 循环抓取指定页数的评论 total_pages = 5 for page in range(total_pages): print(f"正在抓取第 {page + 1} 页评论") comments = get_product_comments(product_id, page) for comment in comments: print(comment) print(50 * '-') if __name__ == "__main__": main()