要使用 Python 和 requests 库来采集豆瓣短评,您需要先了解豆瓣的 API 接口和相关数据结构。然后,您可以使用 requests 库发送 HTTP 请求并解析返回的数据。
以下是一个简单的示例,演示如何使用 Python 和 requests 库来采集豆瓣电影的短评:
import requests
# 设置请求头,模拟浏览器请求
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'
http://www.jshk.com.cn/mb/reg.asp?kefu=xiaoding;//爬虫IP免费获取;
}
# 豆瓣电影的 ID(可替换为实际电影的 ID)
movie_id = '1292052'
# 构建豆瓣短评 API 请求 URL
url = f'https://api.douban.com/v2/movie/subject/{movie_id}/comments'
# 发送请求并获取响应
response = requests.get(url, headers=headers)
# 解析响应数据
data = response.json()
# 检查响应是否成功
if response.status_code == 200:
# 提取短评信息
comments = data['comments']
# 输出短评信息
for comment in comments:
print('用户名:', comment['author']['name'])
print('评分:', comment['rating']['value'])
print('短评:', comment['content'])
print('---')
else:
# 处理错误
print('无法获取豆瓣短评。')
请注意,这只是一个简单的示例,实际中您需要替换 movie_id 为您要采集短评的电影的实际 ID。
Python是一种常用的程序语言,今天我们就用Python和requests库结合,来写一个采集豆瓣短评的程序,非常的简单,一起来学学吧。
```python
import requests
from bs4 import BeautifulSoup
# 设置代理
proxy = f'http://{proxy_host}:{proxy_port}'
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('https://book.douban.com/top250', headers=headers, proxies=proxy)
# 解析HTML
soup = BeautifulSoup(response.text, 'html.parser')
reviews = soup.find_all('span', class_='short')
# 打印短评
for review in reviews:
print(review.text)
```
每一步的解释如下:
1. 导入需要的库(requests和BeautifulSoup)。
2. 设置代理(proxy_host和proxy_port)。
3. 使用requests库的get方法,向豆瓣图书top250页面发送GET请求,同时设置headers和proxies。
4. 使用BeautifulSoup库解析返回的HTML。
5. 使用find_all方法,找到所有class为'short'的span标签,这些标签包含短评信息。
6. 使用for循环,打印出每个短评。