python怎么爬取京东降噪耳机评论
时间: 2023-10-31 18:06:03 浏览: 36
以下是一些步骤可以用 Python 爬取京东降噪耳机评论:
1. 导入需要的库
```
import requests
from bs4 import BeautifulSoup
```
2. 发送 GET 请求获取商品页面内容
```
url = 'https://item.jd.com/100011113040.html' # 商品链接
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'}
response = requests.get(url, headers=headers)
html = response.text
```
3. 用 BeautifulSoup 解析页面内容
```
soup = BeautifulSoup(html, 'html.parser')
```
4. 找到评论区域的 HTML 元素并提取评论
```
comments = soup.find_all('div', class_='comment-item') # 找到评论区域
for comment in comments:
content = comment.find('div', class_='comment-con').get_text().strip() # 提取评论内容
print(content)
```
5. 可以加入循环和翻页功能,以抓取更多的评论
```
for i in range(1, 11): # 抓取前 10 页的评论
url = 'https://sclub.jd.com/comment/productPageComments.action?callback=fetchJSON_comment98vv468&productId=100011113040&score=0&sortType=5&page=%d&pageSize=10&isShadowSku=0&fold=1' % i
response = requests.get(url, headers=headers)
html = response.text
soup = BeautifulSoup(html, 'html.parser')
comments = soup.find_all('div', class_='comment-item')
for comment in comments:
content = comment.find('div', class_='comment-con').get_text().strip()
print(content)
```
这样就可以爬取京东降噪耳机的评论了。不过需要注意的是,京东有反爬虫机制,如果频繁访问同一个页面,可能会被封禁 IP,因此需要加入一些反反爬虫的措施。