#!/usr/bin/python3
# -*- coding: utf-8 -*-
#微博API Python3版
import time, datetime
import urllib.request, urllib.parse
import json, sys
import webbrowser
class WEIBO:
#比特量化 测试
_app_key = "1556452704"
_app_secret = ""
_redirect_uri = "https://api.weibo.com/oauth2/default.html"
apiurl = "https://api.weibo.com/"
access_token = ""
def __init__(self, app_key="", app_secret="", redirect_uri="", accesstoken=""):
if app_key != '' and app_secret != '' and redirect_uri != '':
self._app_key = app_key
self._app_secret = app_secret
self._redirect_uri = redirect_uri
if accesstoken != '':
self.access_token = accesstoken
else:
url = self.apiurl + "oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code"%(self._app_key, self._redirect_uri)
webbrowser.open(url)
code = input("Input code:") #输入授权地址中获得的CODE
ret = self.oauth2_access_token(code)
print(ret)
self.access_token = ret["access_token"]
# 获取 access token
def oauth2_access_token(self, code):
data = {'client_id': self._app_key,
'client_secret': self._app_secret,
'grant_type': "authorization_code",
'code': code,
'redirect_uri': self._redirect_uri
}
url = self.apiurl + "oauth2/access_token"
return self.http_request(url, data)
# 获取用户基本信息
def users_show(self, uid):
url = self.apiurl + "2/users/show.json?access_token=%s&uid=%s"%(self.access_token, uid)
return self.http_request(url)
# 第三方分享到微博
def statuses_share(self, status):
data = {'status': status,
}
url = self.apiurl + "2/statuses/share.json"
return self.http_request(url, data)
# 发布一条新微博
def statuses_update(self, status):
data = {'status': status,
}
url = self.apiurl + "2/statuses/update.json"
return self.http_request(url, data)
# HTTP请求
def http_request(self, url, params = None):
try:
req = urllib.request.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36')
if params: # POST
req.add_header('Authorization', 'OAuth2 %s' % self.access_token)
data = urllib.parse.urlencode(params).encode(encoding='utf-8')
r = urllib.request.urlopen(req, data)
else: # GET
r = urllib.request.urlopen(req)
result = json.loads(r.read().decode('utf-8'))
return result
except Exception as e:
print([url, params])
print(repr(e))
if __name__ == '__main__':
# weibo = WEIBO(accesstoken="")
weibo = WEIBO()
print(weibo.users_show('22'))
print(weibo.statuses_share('Python3 发微博 https://blog.csdn.net/bitquant' + str(time.time())))
微博API SDK-Python3版
最新推荐文章于 2021-11-30 09:03:46 发布