python爬取当当网书籍评论
时间: 2023-10-07 18:14:53 浏览: 98
要爬取当当网书籍评论,可以使用 Python 的 requests 库和 BeautifulSoup 库。以下是一个简单的爬取当当网某本书籍评论的示例代码:
```
import requests
from bs4 import BeautifulSoup
book_id = '123456' # 替换成你要爬取的书籍ID
url = f'https://product.dangdang.com/{book_id}.html'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
comment_list = soup.find_all('div', {'class': 'comment_items clearfix'})
for comment in comment_list:
user = comment.find('div', {'class': 'name'}).text.strip()
rating = comment.find('span', {'class': 'star'}).get('class')[1][-1]
content = comment.find('div', {'class': 'describe_detail'}).text.strip()
print(f'用户:{user},评分:{rating}星,评论:{content}')
```
注意,当当网有反爬机制,如果频繁爬取可能会被封 IP。建议加入适当的延时和代理池等措施。另外,爬取数据需要遵守相关法律法规和网站规定,不得用于商业用途。