Python:模擬登陸以獲取新浪微博OAuth的code參數值

在使用新浪微博提供的API時,首先須要經過認證和受權,關於這部分,你們能夠參考下這篇文章html


在完成以上步驟後,你們會發現每次要使用微博API以前,都須要咱們手動輸入code參數的值才行。
其中,code參數的值是在瀏覽器的地址欄中,也就是說,只要咱們能使用代碼正確地模擬瀏覽器發包,那麼也就能獲得code參數的值。
如下貼上相應的實現代碼:api

__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(用戶名,密碼)
相關文章
相關標籤/搜索