您的位置:首页 > 其它

微博自动登录

2015-12-09 10:58 211 查看
微博自动登录后 先根据 redirect_uri 获取code 再根据code获取access_token

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: