【好文要转】Python:模拟登录以获取新浪微博OAuth的code参数值

时间:2023-03-09 16:00:01
【好文要转】Python:模拟登录以获取新浪微博OAuth的code参数值

【转自】http://www.tuicool.com/articles/zAz6zi

【原文】http://blog.segmentfault.com/hongfei/1190000000343851

在使用新浪微博提供的API时,首先需要通过认证和授权,关于这部分,大家可以参考下 这篇文章

在完成以上步骤后,大家会发现每次要使用微博API之前,都需要我们手动输入code参数的值才行。
其中,code参数的值是在浏览器的地址栏中,也就是说,只要我们能使用代码正确地模拟浏览器发包,那么也就能得到code参数的值。
以下贴上相应的实现代码:

__author__ = 'Fly'
# -*- coding: utf-8 -*-
from weibo import APIClient
import urllib2
import urllib #APP_KEY和APP_SECRET,需要新建一个微博应用才能得到
APP_KEY = 'xxxxxxxx'
APP_SECRET = 'xxxxxxxxxxxxxxxxxxx'
#管理中心---应用信息---高级信息,将"授权回调页"的值改成https://api.weibo.com/oauth2/default.html
CALLBACK_URL = 'https://api.weibo.com/oauth2/default.html'
AUTH_URL = 'https://api.weibo.com/oauth2/authorize' def GetCode(userid,passwd):
client = APIClient(app_key = APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)
referer_url = client.get_authorize_url()
postdata = {
"action": "login",
"client_id": APP_KEY,
"redirect_uri":CALLBACK_URL,
"userId": userid,
"passwd": passwd,
} headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0",
"Referer":referer_url,
"Connection":"keep-alive"
}
req = urllib2.Request(
url = AUTH_URL,
data = urllib.urlencode(postdata),
headers = headers
)
resp = urllib2.urlopen(req)
return resp.geturl()[-32:]
if __name__ == "__main__":
print GetCode(用户名,密码)