微博自动登录
2015-12-09 10:58
211 查看
微博自动登录后 先根据 redirect_uri 获取code 再根据code获取access_token
python 依赖安装包
pip install requests
pip install sinaweibopy
class WeiBo(object):
def __init__(self):
self.session = requests.session()
def get_code(self, name , password , redirect_uri):
#import pdb; pdb.set_trace()
try:
WEIBO_RAND_URL = 'http://login.weibo.cn/login/'
WEIBO_LOGIN_PREFIX = 'http://login.weibo.cn/login/'
h = self.session.post(WEIBO_RAND_URL,data = {})
soup = BeautifulSoup(h.text, 'html.parser')
rand = soup.form["action"]
self.url = WEIBO_LOGIN_PREFIX+rand
for v in soup.select('input[name="vk"]'):
vk = v["value"]
for p in soup.select('input[type="password"]'):
passwordrand = p["name"]
headers = {
'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36',
}
self.data = { 'mobile': name,
passwordrand: password,
'remember': 'on',
'backURL': 'http://weibo.cn/',
'backTitle': u'新浪微博',
'vk': vk,
'submit': u'登录',
'encoding': 'utf-8' }
personal_page = self.session.post(self.url, data=self.data, headers=headers)
except Exception,e:
pass
redirect_page = self.session.post(redirect_uri)
red_url = redirect_page.url
glogger.debug('redirect_page_url : %s' % red_url)
if red_url.__contains__('code='):
code = red_url.split('code=')[-1]
return code
else:
return self.__authorize(redirect_page.text, redirect_uri)
def __authorize(self, response_body, redirect_uri):
soup = BeautifulSoup(response_body, 'html.parser')
datas = soup.find(class_='oauth_login_box01 clearfix')
if not datas: return None
inputs = datas.find_all('input')
url = 'https://api.weibo.com/oauth2/authorize'
headers = { 'referer':redirect_uri}
param = { 'display':'default',
'action':'authorize',
'scope':'',
'withOfficalFlag':0,
'withOfficalAccount':'',
'ticket':'',
'isLoginSina':'',
'response_type':'code',
'regCallback':'',
'redirect_uri':'',
'client_id':'',
'appkey62':'',
'state':'',
'from':'',
'uid':'',
'url':'',
'verifyToken':'',
'visible':0}
for input in inpu
9f89
ts:
try:
param[input.get('name')]=input.get('value')
except Exception:
continue
req = self.session.post(url, data = param, headers = headers)
red_url = req.url
if red_url.__contains__('code='):
code = red_url.split('code=')[-1]
return code
else:
return None
@classmethod
def get_weibo_access_token(cls, account_name, account_passwd):
'''
获取微博账号的access_token
'''
try:
#import pdb; pdb.set_trace()
api_client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=REDIRECT_URL)
authorize_url = api_client.get_authorize_url()
account_code = WeiBo().get_code(account_name, account_passwd, authorize_url)
if None == account_code: return None, None, None, None
req_ac_token = api_client.request_access_token(account_code,REDIRECT_URL)
api_client.set_access_token(req_ac_token.access_token, req_ac_token.expires_in)
user_info = api_client.users.show.get(uid = int(req_ac_token.uid))
return req_ac_token.access_token, req_ac_token.expires_in, req_ac_token.uid, user_info.screen_name
except APIError, e:
errstr = STR_WEIBO_ERROR(e.error_code)
if not errstr:
errstr = 'code:%s; error:%s' % (e.error_code, str(e))
raise ValueError, errstr
except Exception:
return None, None, None, None
使用方法:
WeiBo.get_weibo_access_token('账号','密码')
返回:
access_token, expires_in, uid, screen_name
python 依赖安装包
pip install requests
pip install sinaweibopy
''' 微博应用信息 ''' APP_KEY = '***********' APP_SECRET = "**********************************" REDIRECT_URL = 'http://*************************'
class WeiBo(object):
def __init__(self):
self.session = requests.session()
def get_code(self, name , password , redirect_uri):
#import pdb; pdb.set_trace()
try:
WEIBO_RAND_URL = 'http://login.weibo.cn/login/'
WEIBO_LOGIN_PREFIX = 'http://login.weibo.cn/login/'
h = self.session.post(WEIBO_RAND_URL,data = {})
soup = BeautifulSoup(h.text, 'html.parser')
rand = soup.form["action"]
self.url = WEIBO_LOGIN_PREFIX+rand
for v in soup.select('input[name="vk"]'):
vk = v["value"]
for p in soup.select('input[type="password"]'):
passwordrand = p["name"]
headers = {
'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36',
}
self.data = { 'mobile': name,
passwordrand: password,
'remember': 'on',
'backURL': 'http://weibo.cn/',
'backTitle': u'新浪微博',
'vk': vk,
'submit': u'登录',
'encoding': 'utf-8' }
personal_page = self.session.post(self.url, data=self.data, headers=headers)
except Exception,e:
pass
redirect_page = self.session.post(redirect_uri)
red_url = redirect_page.url
glogger.debug('redirect_page_url : %s' % red_url)
if red_url.__contains__('code='):
code = red_url.split('code=')[-1]
return code
else:
return self.__authorize(redirect_page.text, redirect_uri)
def __authorize(self, response_body, redirect_uri):
soup = BeautifulSoup(response_body, 'html.parser')
datas = soup.find(class_='oauth_login_box01 clearfix')
if not datas: return None
inputs = datas.find_all('input')
url = 'https://api.weibo.com/oauth2/authorize'
headers = { 'referer':redirect_uri}
param = { 'display':'default',
'action':'authorize',
'scope':'',
'withOfficalFlag':0,
'withOfficalAccount':'',
'ticket':'',
'isLoginSina':'',
'response_type':'code',
'regCallback':'',
'redirect_uri':'',
'client_id':'',
'appkey62':'',
'state':'',
'from':'',
'uid':'',
'url':'',
'verifyToken':'',
'visible':0}
for input in inpu
9f89
ts:
try:
param[input.get('name')]=input.get('value')
except Exception:
continue
req = self.session.post(url, data = param, headers = headers)
red_url = req.url
if red_url.__contains__('code='):
code = red_url.split('code=')[-1]
return code
else:
return None
@classmethod
def get_weibo_access_token(cls, account_name, account_passwd):
'''
获取微博账号的access_token
'''
try:
#import pdb; pdb.set_trace()
api_client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=REDIRECT_URL)
authorize_url = api_client.get_authorize_url()
account_code = WeiBo().get_code(account_name, account_passwd, authorize_url)
if None == account_code: return None, None, None, None
req_ac_token = api_client.request_access_token(account_code,REDIRECT_URL)
api_client.set_access_token(req_ac_token.access_token, req_ac_token.expires_in)
user_info = api_client.users.show.get(uid = int(req_ac_token.uid))
return req_ac_token.access_token, req_ac_token.expires_in, req_ac_token.uid, user_info.screen_name
except APIError, e:
errstr = STR_WEIBO_ERROR(e.error_code)
if not errstr:
errstr = 'code:%s; error:%s' % (e.error_code, str(e))
raise ValueError, errstr
except Exception:
return None, None, None, None
使用方法:
WeiBo.get_weibo_access_token('账号','密码')
返回:
access_token, expires_in, uid, screen_name
相关文章推荐
- Windows下一键安装Redmine
- 关于Android app首次安装完成后在安装界面直接“打开”应用再按home键返回桌面,重新进入app重复实例化launcher activity的问题的解决
- 自定义UIView UITableViewCell等控件
- Elastic Search Filter Script
- From Facial Parts Responses to Face Detection: A Deep Learning Approach
- cocos2dx[3.2](21)——观察者模式NotificationCenter
- PS快捷键大全
- 渲染直线
- perl 监控网站域名劫持
- angularjs中radio表单提交问题
- Android Service
- 【html】【10】div布局[div水平垂直居中]
- timestamp在DB2和Oracle
- C 预定义宏
- 40、BGP状态解析
- 【JEECG技术博文】JEECG 简单实例讲解权限控制
- 记录 关于Video——stitching的问题
- Using Legacy C APIs with Swift
- js生成二维码实例(真实有效)
- ngrok或类似工具收集