吐槽两句
恕我直言
微博API的文档就是”依托“
官方SDK甚至只有适配python 2的版本
创建账号
这方面的教程还是有的 , 如 这个教程
登录微博官网 开发者网站
注册账号
提交材料信息进行审核(两个工作日)
OAuth 2 授权
我实在不理解为什么教程都会贴一张OAuth 2 的原理图,我觉得正常人都完全不会关心这个。
实测要做的事情是只要信息审核通过后,创建微链接应用,甚至不用提交审核,只要点进去就可以拿到专属的
APP_KEY
和
APP_SECRET
这两个自己记录一下,之后会用到
同时在“应用信息”里的“高级信息”设置授权回调页
https://api.weibo.com/oauth2/default.html
在GitHub上Clone sinaweibopy3
git clone https://github.com/olwolf/sinaweibopy3.git
注意:这个项目目前并不能直接运行!
由于sinaweibopy3.py文件里面,获取最新微博的接口json文件名是public_timeline.json,现在已经变成了home_timeline.json
只用将sinaweibopy3 文件中的public_timeline方法中的地址改为home_timeline.json就可以了!
修改完的函数如下
def public_timeline(self):
'''
get new public weibo,the parameters followed can be used in _http_get in this method
access_token : (string) the token you got after OAuth
count : (int) the record items in one single page,default 50 items
page : (int) the page number,default one page
base_app : (int) whether get data in current app or not,0 is not(all data),1 is yes(current app),default 0
'''
result = _http_get('%s'% (self.api_url) + 'statuses/home_timeline.json',
access_token=self.access_token,
count=50,
page=1,
base_app=0,
)
return result
修改完毕!
运行
通过之前的key 和 secret做一个类似登录的操作
import sinaweibopy3
APP_KEY ='xxxxxx' ##Your Key
APP_SECRET = 'xxxxxx'### Your Secret
REDIRECT_URL= 'https://api.weibo.com/oauth2/default.html'
client = sinaweibopy3.APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=REDIRECT_URL)
调出一个网页获取code.运行这里的代码会打开一个网页,需要复制一个code并在运行时输入
url = client.get_authorize_url()
webbrowser.open_new(url)
result = client.request_access_token(input("please input code : "))
client.set_access_token(result.access_token, result.expires_in)
测试能否获得数据
res = client.public_timeline().statuses
l = len(res)
for i in range(0,l):
print(f'昵称:'+res[i]['user']['screen_name'])
print(f'简介:'+res[i]['user']['description'])
print(f'位置:'+res[i]['user']['location'])
print(f'微博:'+res[i]['text'])