环境:
ubuntu 18.10
python 3.6
pip install sinaweibopy3
说下:
m.weibo.cn
weibo.cn
weibo.com
我们只使用第一个,用来获取代码中需要的id
open.weibo.com自己完成认证以后,
打开自己新建的应用找到下面两个东西:
App Key:502108417
App Secret:794019e15ae228d4295f2509be2603a4
先了解新浪API的授权机制,总之就是一堆破事儿。
#-*- coding:utf-8 -*-
# import sys
# reload(sys)
# sys.setdefaultencoding("utf-8")
from weibo import APIClient
# import sinaweibopy3
import webbrowser #python内置的包,支持对浏览器进行操作
APP_KEY = '502108417'
APP_SECRET = '794019e15ae228d4295f2509be2603a4'
CALLBACK_URL = 'https://api.weibo.com/oauth2/default.html' #回调授权页面,用户完成授权后返回的页面
client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
print (dir(client))
url = client.get_authorize_url() #得到授权页面的url
print("-----------------------------")
print(url)
webbrowser.open_new(url) #打开这个url
把输出的url在浏览器里面打开,然后得到:
https://blog.csdn.net/appleyuchi?code=7046b0d8dc5de854f48a6a81b0c095ad
那么code就是a35919c585efd0e96d50578d17b63385
然后把code以及App Key和APP_SECRET 填入以下代码.
##########################################################################
然后运行code2.py
from weibo import APIClient
import webbrowser #python内置的包,支持对浏览器进行操作
APP_KEY = '502108417'
APP_SECRET = '794019e15ae228d4295f2509be2603a4'
CALLBACK_URL = 'https://api.weibo.com/oauth2/default.html'
#回调授权页面,用户完成授权后返回的页面
code="7046b0d8dc5de854f48a6a81b0c095ad"
client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
print(dir(client))
r = client.request_access_token(code)
access_token = r.access_token # 新浪(授权服务器)返回的token
expires_in = r.expires_in
client.set_access_token(access_token, expires_in)
# print(client.get.comments__show(id=4154417035431509))#这个是获取当前使用的app_key的账号id
r=client.comments.show.get(id = 4392052659521357,count = 200,page = 2)
print(type(r))
print(r)
# client.get的意思就是对应下面接口文档[5]中的https://api.weibo.com/2/
必须在m.weibo.cn中的地址栏中找id
一条微博对应一个代码中的id
注意上面的id从需要的微博文的网址中获取,例如:
https://m.weibo.cn/status/4392052659521357
运行python code2.py后效果如下:
############################################################################################
如果碰到以下问题:
weibo.APIError: APIError: 21325: invalid_grant, request: /oauth2/access_token
可以参考[3]
参考链接:
[1]如何通过python调用新浪微博的API
[2]新浪授权机制
[3]新浪API授权故障
[4]API使用频率限制
[5]评论接口文档