首页 新闻 搜索 专区 学院

python想自动获取新浪微博api返回的code,请指点

0
悬赏园豆:180 [已关闭问题] 关闭于 2016-01-21 19:03

在使用新浪微博提供的API时,首先需要通过认证和授权。大家会发现每次要使用微博API之前,都需要我们手动输入code参数的值才行。其中,code参数的值是在浏览器的地址栏中。

   目的就是要获取从这个登陆页面获取登陆后的URL。

  页面跳转后如下.获取其中的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(用户名,密码)

 

还有下面这份代码:  

 

# -*- coding:utf-8 -*-

from weibo import APIClient
import urllib
import urllib2
import cookielib
try:
    import json
except ImportError:
    import simplejson as json

APP_KEY = '1612210697'
APP_SECRET = 'EEC5D28BF9284B4EAD0EB3509CA7D524268AD8DA'
REDIRECT_URL = 'http://sinaapi.daoke.me:8080/weibo.html'
USERID = 'mirrtalk@foxmail.com'
USERPASSWD = ''
client = APIClient(app_key=APP_KEY, app_secret = APP_SECRET, redirect_uri = REDIRECT_URL)
class SmartRedirectHandler(urllib2.HTTPRedirectHandler):
        def http_error_301(cls, req, fp, code, msg, headers):
                result = urllib2.HTTPRedirectHandler.http_error_301(cls, req, fp, code, msg, headers)
                result.status = code
                print headers
                return result

        def http_error_302(cls, req, fp, code, msg, headers):
                result = urllib2.HTTPRedirectHandler.http_error_302(cls, req, fp, code, msg, headers)
                result.status = code
                print headers
                return result

def get_cookie():
        cookies = cookielib.CookieJar()
        return urllib2.HTTPCookieProcessor(cookies)

def get_opener(proxy=False):
        rv=urllib2.build_opener(get_cookie(), SmartRedirectHandler())
        rv.addheaders = [('User-agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)')]
        return rv

def GetCode():
        params = urllib.urlencode({
                'action':'submit',
                'withOfficalFlag':'0',
                'ticket':'',
                'isLoginSina':'',
                'response_type':'code',
                'regCallback':'',
                'redirect_uri':REDIRECT_URL,
                'client_id':APP_KEY,
                'state':'',
                'from':'',
                'userId':USERID,
                'passwd':USERPASSWD,
        })
        login_url = 'https://api.weibo.com/oauth2/authorize'
        url = client.get_authorize_url()       
        content = urllib2.urlopen(url)
        if content:
                headers = {'Referer':url}
                request = urllib2.Request(login_url, params, headers)
                opener = get_opener(False)
                urllib2.install_opener(opener)
                try:
                        f = opener.open(request)
                        return_redirect_uri = f.url
                except urllib2.HTTPError, e:
                        return_redirect_uri = e.geturl()
                return return_redirect_uri
                #code = return_redirect_uri.split('=')[1]
                #return code
if __name__ == '__main__':
        print GetCode()

 


  求大神指导!

Fighting蔚的主页 Fighting蔚 | 初学一级 | 园豆:2
提问于:2016-01-19 15:29
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册