在PyCharm中,如何编写代码来爬取京东商品页面(https://item.jd.com/10129014121406.html)上的商品评论?给出完整可用代码
时间: 2025-02-03 11:14:40 浏览: 33
在PyCharm中编写代码来爬取京东商品页面上的商品评论,可以使用Python的`requests`库来发送HTTP请求,使用`BeautifulSoup`库来解析HTML内容。以下是一个完整的示例代码:
```python
import requests
from bs4 import BeautifulSoup
import json
# 商品页面URL
url = 'https://item.jd.com/10129014121406.html'
# 发送HTTP请求获取页面内容
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)
soup = BeautifulSoup(response.text, 'html.parser')
# 提取商品评论的URL
comment_url = 'https://sclub.jd.com/comment/productPageComments.action?productId=10129014121406&score=0&sortType=5&page=0&pageSize=10&isShadowSku=0'
# 发送HTTP请求获取评论内容
comment_response = requests.get(comment_url, headers=headers)
comment_data = json.loads(comment_response.text)
# 提取评论内容
comments = comment_data['comments']
for comment in comments:
print(comment['content'])
```
这个代码的主要步骤如下:
1. 导入所需的库:`requests`用于发送HTTP请求,`BeautifulSoup`用于解析HTML内容,`json`用于解析JSON数据。
2. 设置商品页面的URL。
3. 发送HTTP请求获取商品页面的内容。
4. 使用`BeautifulSoup`解析页面内容。
5. 提取商品评论的URL。
6. 发送HTTP请求获取评论内容。
7. 解析评论内容的JSON数据。
8. 提取并打印评论内容。
请注意,京东的页面结构可能会发生变化,因此在实际使用中可能需要根据具体情况调整代码。
阅读全文
相关推荐













