python爬取京东商品评论数据
模块
模块使用了re、httpx、time这些库
httpx模块是一个可以发送网络请求的模块,他与requests库相似但有一个requests库没有的功能,就是httpx可以发送http2协议的请求
re库是一个正则表达式的一个工具
关于这两个库大家可以去官网了解我就不过多介绍了
# 安装方式(安装了可以跳过):
pip install httpx
# 上面安装的httpx没办法使用http2请求我们还需要继续安装下面这个
pip install httpx['http2']
# 这样就可以使用http2协议进行请求了
pip install re
分析
接下来我们需要分析一下,分析什么呢?分析我们需要的数据在哪个接口,有没有加密,有没有表单需要写的
数据在哪里?
首先在爬取之前我们肯定需要知道数据在哪里是吧,俗话说:工欲善其事,必先利其器。那么我们需要的数据又在哪里呢?非常简单跟着我走就行。
首先我们打开网站然后随便选择一个商品,然后按F12打开我们熟知的开发者工具,然后刷新一下按ctrl+f打开搜索复制一个评论进行搜索。

表单?
然后我们查看表单进行分析

通过图片我们可以知道除了我画的这三个其他的都没有动,但是在第二页的api中会添加一个新的键具体可以看我的代码
知道这些那么我们就知道需要解决的表单的键有哪些了,时间戳可以使用time模块,而productid就是页面的编码,具体操作看代码我就不细说了
编写代码
接下来就可以编写代码了
这里我就直接展示全部代码了
# Copyright (c) 2024. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
# Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
# Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
# Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
# Vestibulum commodo. Ut rhoncus gravida arcu.
```
import time
import httpx
import re
```
def get_dispose_comments2(alldata):
comments = alldata['comments'] # 评论全部数据
results = []
for data in comments:
if "location" in data:
content = data['content'] # 评论
creationtime = data['creationTime'] # 时间
location = data['location'] # ip
productcolor = data['productColor'] # 商品款式
results.append((content, creationtime, location, productcolor)) # 这里可以方便大家保存数据
print('评价:' + content, '时间:' + creationtime, 'IP:' + location, '商品款式:' + productcolor)
else:
content = data['content'] # 评论
creationtime =