使用python在微博中抓取杭州女子被造谣案件评论
时间: 2023-07-31 14:01:20 浏览: 51
使用Python抓取微博数据的方式有多种,以下是一个简单的方法:
首先,我们需要安装第三方库`weibo`和`pandas`。
```python
pip install weibo pandas
```
导入所需的库:
```python
import weibo
import pandas as pd
```
通过微博开放平台申请一个应用,获取到`APP_KEY`和`APP_SECRET`以及`REDIRECT_URI`,并获取到访问令牌`access_token`。
```python
APP_KEY = 'your_app_key'
APP_SECRET = 'your_app_secret'
REDIRECT_URI = 'your_redirect_uri'
access_token = 'your_access_token'
```
初始化微博客户端:
```python
client = weibo.APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=REDIRECT_URI)
client.set_access_token(access_token, expires_in=3600)
```
使用微博API获取指定微博的评论:
```python
wb_id = 'your_weibo_id' # 微博ID
comments = client.comments.show.get(id=wb_id, count=100) # 获取100条评论
```
将评论数据保存到DataFrame:
```python
comments_data = []
for comment in comments['comments']:
comments_data.append(comment['text'])
df = pd.DataFrame(comments_data, columns=['评论内容'])
```
将DataFrame保存到CSV文件:
```python
df.to_csv('comments.csv', index=False)
```
以上代码仅供参考,实际情况可能会有所调整。另外,请确保你有合法的访问令牌和微博API的权限。使用时要注意遵循微博API的使用规范,防止滥用和侵犯他人隐私。