如何防止Python的urllib(2)遵循重定向

时间:2009-02-16 20:29:30

标签: python urllib2

我目前正在尝试使用Python登录网站,但该网站似乎在同一页面上发送了cookie和重定向语句。 Python似乎遵循该重定向,从而阻止我阅读登录页面发送的cookie。如何防止Python的urllib(或urllib2)urlopen跟随重定向?

4 个答案:

答案 0 :(得分:33)

你可以做几件事:

  1. 构建您自己的HTTPRedirectHandler,拦截每个重定向
  2. 创建一个HTTPCookieProcessor实例并安装该开启器,以便您可以访问cookiejar。
  3. 这是一个显示两者的快速小事

    import urllib2
    
    #redirect_handler = urllib2.HTTPRedirectHandler()
    
    class MyHTTPRedirectHandler(urllib2.HTTPRedirectHandler):
        def http_error_302(self, req, fp, code, msg, headers):
            print "Cookie Manip Right 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
    
    cookieprocessor = urllib2.HTTPCookieProcessor()
    
    opener = urllib2.build_opener(MyHTTPRedirectHandler, cookieprocessor)
    urllib2.install_opener(opener)
    
    response =urllib2.urlopen("WHEREEVER")
    print response.read()
    
    print cookieprocessor.cookiejar
    

答案 1 :(得分:29)

如果您只需要停止重定向,那么有一种简单的方法可以做到这一点。例如,我只想获取cookie并获得更好的性能,我不希望被重定向到任何其他页面。我也希望代码保持为3xx。例如,让我们使用302。

class MyHTTPErrorProcessor(urllib2.HTTPErrorProcessor):

    def http_response(self, request, response):
        code, msg, hdrs = response.code, response.msg, response.info()

        # only add this line to stop 302 redirection.
        if code == 302: return response

        if not (200 <= code < 300):
            response = self.parent.error(
                'http', request, response, code, msg, hdrs)
        return response

    https_response = http_response

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), MyHTTPErrorProcessor)

通过这种方式,你甚至不需要进入urllib2.HTTPRedirectHandler.http_error_302()

更常见的情况是我们只想停止重定向(根据需要):

class NoRedirection(urllib2.HTTPErrorProcessor):

    def http_response(self, request, response):
        return response

    https_response = http_response

通常以这种方式使用它:

cj = cookielib.CookieJar()
opener = urllib2.build_opener(NoRedirection, urllib2.HTTPCookieProcessor(cj))
data = {}
response = opener.open('http://www.example.com', urllib.urlencode(data))
if response.code == 302:
    redirection_target = response.headers['Location']

答案 2 :(得分:12)

urllib2.urlopen调用使用此处理程序类列表的build_opener()

handlers = [ProxyHandler, UnknownHandler, HTTPHandler,
HTTPDefaultErrorHandler, HTTPRedirectHandler,
FTPHandler, FileHandler, HTTPErrorProcessor]

您可以尝试使用省略urllib2.build_opener(handlers)的列表自行调用HTTPRedirectHandler,然后在结果上调用open()方法以打开您的网址。如果你真的不喜欢重定向,你甚至可以将urllib2.install_opener(opener)称为你自己的非重定向开启者。

听起来你真正的问题是urllib2没有按照你想要的方式做饼干。另请参阅How to use Python to login to a webpage and retrieve cookies for later usage?

答案 3 :(得分:3)

here之前询问了这个问题。

编辑:如果您必须处理古怪的网络应用程序,您应该尝试mechanize。它是一个很棒的库,可以模拟Web浏览器。你可以控制重定向,cookie,页面刷新...如果网站不依赖于JavaScript,你会很好地与机械化相处。

相关问题