写一段爬虫京东评论的代码
时间: 2023-12-01 15:44:48 浏览: 56
当然可以!下面是一个简单的Python代码示例,使用BeautifulSoup和Requests库来爬取京东商品评论:
```python
import requests
from bs4 import BeautifulSoup
def get_jd_comments(product_id):
url = 'https://item.jd.com/{}.html#comment'.format(product_id)
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')
comments = []
for item in soup.find_all('div', class_='comment-item'):
comment = item.find('div', class_='comment-con').text.strip()
comments.append(comment)
return comments
# 使用示例
product_id = '1000123456789' # 替换为你想要爬取评论的商品ID
comments = get_jd_comments(product_id)
for comment in comments:
print(comment)
```
请确保你已经安装了必要的库(requests和BeautifulSoup)。
以上代码会爬取指定商品ID的京东商品评论,并将评论文本打印出来。你可以根据需要对代码进行修改和扩展,如保存评论到文件、提取更多信息等。注意,爬取网页内容时需要设置合适的请求头(User-Agent),以模拟浏览器访问,避免被网站屏蔽。