简体   繁体   English

如何获取重定向网址?

[英]How to get redirect url?

I am using urllib.request to perform a sequence of http calls in python 3.6. 我正在使用urllib.request在python 3.6中执行一系列http调用。 I need to retrieve the value of a 302 http redirect that is returned in response to a urllib.request.urlopen call like so... 我需要检索响应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()

I get an error like... 我收到类似...的错误

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

What I need is to actually get the url that is being returned in the 302 as the .geturl() method should provide, but instead I get an error. 我需要的实际上是获取.geturl()方法应提供的302中返回的url,但是却出现了错误。

Please no answers like "Hey use this other library that I'm super into right now" as we've spent a long time building this script using urllib2 and we have very little python knowledge. 请不要回答“嘿,请使用我现在超级喜欢的另一个库”,因为我们花了很长时间使用urllib2构建此脚本,而我们对python的了解却很少。

Thanks for your help. 谢谢你的帮助。

If you dont want to use the requests library (which is almost part of the core libs at this point), you need to write a custom HTTPRedirectHandler using urllib2. 如果您不想使用请求库(此时几乎是核心库的一部分),则需要使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM