如何用python爬取京东评论
时间: 2025-02-04 12:22:10 浏览: 49
要使用Python爬取京东的评论,可以使用`requests`库来发送HTTP请求,使用`BeautifulSoup`库来解析HTML内容。以下是一个简单的示例代码,演示如何爬取京东商品评论:
1. 安装必要的库:
```bash
pip install requests
pip install beautifulsoup4
```
2. 编写爬虫代码:
```python
import requests
from bs4 import BeautifulSoup
import json
def get_comments(product_id, page_num):
url = f'https://sclub.jd.com/comment/productPageComments.action?productId={product_id}&page={page_num}&pageSize=10&sortType=5&score=0&fold=1'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
comments = data['comments']
for comment in comments:
print(comment['content'])
else:
print(f'Failed to retrieve comments: {response.status_code}')
if __name__ == '__main__':
product_id = '123456' # 替换为你要爬取的商品的ID
for page in range(10): # 爬取前10页评论
get_comments(product_id, page)
```
### 代码说明:
1. **导入库**:导入`requests`用于发送HTTP请求,`BeautifulSoup`用于解析HTML内容,`json`用于处理JSON数据。
2. **定义函数`get_comments`**:该函数接收商品ID和页码作为参数,构造请求URL并发送GET请求。
3. **设置请求头**:设置`User-Agent`以模拟浏览器请求。
4. **发送请求并解析响应**:如果请求成功,解析JSON数据并打印评论内容。
5. **主程序**:在主程序中,替换`product_id`为你要爬取的商品的ID,并循环爬取前10页的评论。
### 注意事项:
1. **合法性和道德性**:爬取网站数据时请确保遵守相关法律法规和网站的使用条款。
2. **反爬措施**:京东可能有反爬措施,如IP封禁、验证码等,爬取时请注意控制频率,避免被封禁。
阅读全文
相关推荐

















