微博API官方文档
本文介绍
- 本文环境
- 成为微博开发者
- 通过鉴权
- 获取单条微博内容
环境
- Windows
- Python 3.8.10
- sinaweibopy3-1.3 (pip3 install sinaweibopy3)
- requests
成为微博开发者
微博官方新手教程 (cxn可以跳过,用博主的即可)
- 完善身份信息并认证
- 创建微链接
- 填写授权回调页
- 注:https://api.weibo.com/oauth2/default.html
通过鉴权
- 以下只为获取access_token,采用的是weiboSDK
from weibo import APIClient
import webbrowserAPP_KEY = 'xxx'
APP_SECRET = 'xxx'
CALLBACK_URL = 'https://api.weibo.com/oauth2/default.html'# 利用官方微博SDK
client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
# 得到授权页面的url,利用webbrowser打开这个url
url = client.get_authorize_url()
print(url)
webbrowser.open_new(url)
# 获取code=后面的内容
print('输入url中code后面的内容后按回车键:')
code = input()
r = client.request_access_token(code)
access_token = r.access_token # 新浪返回的token,类似abc123xyz456
expires_in = r.expires_in
# 获取 access_token
print("access_token, expires_in:", access_token, expires_in)
# 设置得到的access_token
client.set_access_token(access_token, expires_in)
# 获取uid
uid = client.get.account__get_uid()["uid"]
print(uid)
获取单条微博内容
- 以下使用requests
import json
import requestsaccess_token = "xxx"
res = requests.get(f"https://api.weibo.com/2/statuses/user_timeline.json?access_token={access_token}")weibo_list_json = json.loads(res.content)
for weibo_dict in weibo_list_json["statuses"]:weibo_id = weibo_dict["id"]print(weibo_id)res = requests.get(f"https://api.weibo.com/2/statuses/show.json?access_token={access_token}&id={weibo_id}")weibo_json = json.loads(res.content)# 获取转发量print(weibo_json["reposts_count"])