如何防止 Python 的 urllib(2) 跟随重定向 [英] How do I prevent Python's urllib(2) from following a redirect

查看:50
本文介绍了如何防止 Python 的 urllib(2) 跟随重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently trying to log into a site using Python however the site seems to be sending a cookie and a redirect statement on the same page. Python seems to be following that redirect thus preventing me from reading the cookie send by the login page. How do I prevent Python's urllib (or urllib2) urlopen from following the redirect?

推荐答案

你可以做几件事:

  1. 构建您自己的 HTTPRedirectHandler 来拦截每个重定向
  2. 创建 HTTPCookieProcessor 的实例并安装该开启程序,以便您可以访问 cookiejar.

这是一个快速显示两者的小东西

This is a quick little thing that shows both

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

这篇关于如何防止 Python 的 urllib(2) 跟随重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆