为什么我的浏览器会使用此URL重定向我,但Python不会?

时间:2017-08-20 06:55:24

标签: python-2.7 api redirect vk

当我在Python 2.7上使用urllib,urllib2或请求时,当我将起始网址复制并粘贴到Chrome或FireFox for Mac时,这两个网址都不会像我一样。

编辑:我怀疑这是因为必须登录vk.com才能重定向。如果是这种情况,如何将登录添加到我的脚本中?谢谢!

起始网址:https://oauth.vk.com/authorize?client_id=PRIVATE&redirect_uri=https://oauth.vk.com/blank.html&scope=friends&response_type=token&v=5.68

实际最终(重定向)网址:https://oauth.vk.com/blank.html#access_token=PRIVATE_TOKEN&expires_in=86400&user_id=PRIVATE

PRIVATE,PRIVATE_TOKEN =审查信息

以下是此次尝试之一:

import requests

APPID = 'PRIVATE'
DISPLAY_OPTION = 'popup' # or 'window' or 'mobile' or 'popup'
REDIRECT_URL = 'https://oauth.vk.com/blank.html'
SCOPE = 'friends' # https://vk.com/dev/permissions
RESPONSE_TYPE = 'token' # Documentation is vague on this. I don't know what 
        # other options there are, but given the context, i.e. that we want an
        # "access token", I suppose this is the correct input

URL = 'https://oauth.vk.com/authorize?client_id=' + APPID + \
      '&display='+ DISPLAY_OPTION + \
      '&redirect_uri=' + REDIRECT_URL + \
      '&scope=' + SCOPE + \
      '&response_type=' + RESPONSE_TYPE + \
      '&v=5.68'

# with requests

REQUEST = requests.get(URL)

RESPONSE_URL = REQUEST.url

我希望你注意到我的代码出了什么问题。

额外信息:我需要重定向,因为进一步编程需要PRIVATE_TOKEN值。

我尝试了一些调试但是解释器和IPython都没有打印出调试信息。

谢谢!

1 个答案:

答案 0 :(得分:0)

问题是未在Python环境中登录的结果。

解决方案:

使用twill在Python中创建浏览器并登录。

代码:

from twill.commands import *

BROWSER = get_browser()

BROWSER.go(URL) # URL is the URL concatenated in the question

RESPONSE_URL = BROWSER.get_url()
相关问题