如何获得重定向url?

How to get redirect url?

我正在使用 urllib.request 在 python 3.6 中执行一系列 http 调用。我需要检索响应 urllib.request.urlopen 调用而返回的 302 http 重定向的值...

import urllib.request

... many previous http calls ...

post_data = {'foo': 'bar', 'some': 'otherdata'}
encoded = urllib.parse.urlencode(post_data).encode('utf-8')
req = urllib.request.Request('https://some-url', encoded)
redirected_url = urllib.request.urlopen(req).geturl()

我收到类似...

的错误
urllib.error.HTTPError: HTTP Error 302: Found - Redirection to url 'gibberish://login_callback?code=ABCD......' is not allowed

我需要的是实际获取 302 中返回的 url 作为 .geturl() 方法应该提供的,但是我得到了一个错误。

请不要回答 "Hey use this other library that I'm super into right now" 之类的问题,因为我们花了很长时间使用 urllib2 构建此脚本,而我们的 python 知识很少。

感谢您的帮助。

如果您不想使用请求库(此时它几乎是核心库的一部分),您需要使用 urllib2 编写自定义 HTTPRedirectHandler。

import urllib2

class CustomHTTPRedirectHandler(urllib2.HTTPRedirectHandler):
    def http_error_302(self, req, fp, code, msg, headers):
        ### DO YOUR STUFF HERE
        return urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)

    http_error_301 = http_error_303 = http_error_307 = http_error_302

opener = urllib2.build_opener(CustomHTTPRedirectHandler)
post_data = {'foo': 'bar', 'some': 'otherdata'}
encoded = urllib.parse.urlencode(post_data).encode('utf-8')
req = urllib.request.Request('https://some-url', encoded)
opener.urlopen(req)