以前用过一次sinaweibopy3来获取新浪的数据,但是太麻烦了!!!经过研究之后,发现weibopy库比sinaweibopy3方便很多,简单易懂方便上手,短短几行代码就能搞定,于是决定分享出来。
环境:python3.7
准备:pip install weibopy
pip install webbrowser
网站:https://m.weibo.cn/
提前申请新浪微博的app_key和app_secret https://jingyan.baidu.com/article/375c8e19b8024125f2a22913.html
代码整理如下:
#-*- coding:utf-8 -*-
# import sys
# reload(sys)
# sys.setdefaultencoding("utf-8")
from weibopy import WeiboOauth2, WeiboClient
import webbrowser
APP_KEY = '000000000'
APP_SECRET = '0000000000000xxxxxxxxxxxxxxxxxx'
CALLBACK_URL = 'https://api.weibo.com/oauth2/default.html'
#回调授权页面,用户完成授权后返回的页面
client= WeiboOauth2(client_id=APP_KEY, client_secret=APP_SECRET, redirect_url=CALLBACK_URL)
#得到授权页面的url,并打开这个url
url = client.authorize_url
webbrowser.open_new(url)
code = input("please input code : ")
r = client.auth_access(code)
b = WeiboClient(r['access_token'])
# 获取评论信息
for i in range(1,10):
result = b.get(suffix='comments/show.json', params={'id': 4459137180328909, 'count': 200, 'page': i})
comments = result['comments']
for j in comments:
text = j["text"]
id = j["id"]
created_at = j["created_at"]
print('page:{}'.format(i),text,id,created_at)
运行后效果如图所示:
根据新浪comments/show文档https://open.weibo.com/wiki/2/comments/show,提取自己需要的数据。