相关疑难解决方法(0)

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

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

python urllib2

47
推荐指数
3
解决办法
4万
查看次数

python只使用urllib2获取头文件

我必须使用urllib2实现一个函数来获取头文件(不进行GET或POST).这是我的功能:

def getheadersonly(url, redirections = True):
    if not redirections:
        class MyHTTPRedirectHandler(urllib2.HTTPRedirectHandler):
            def http_error_302(self, req, fp, code, msg, headers):
                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)

    class HeadRequest(urllib2.Request):
        def get_method(self):
            return "HEAD"

    info = {}
    info['headers'] = dict(urllib2.urlopen(HeadRequest(url)).info()) 
    info['finalurl'] = urllib2.urlopen(HeadRequest(url)).geturl() 
    return info
Run Code Online (Sandbox Code Playgroud)

使用代码回答这个这个.但是,即使标志是,也会进行重定向False.我试过代码:

print getheadersonly("http://ms.com", redirections = False)['finalurl']
print getheadersonly("http://ms.com")['finalurl']
Run Code Online (Sandbox Code Playgroud)

它在两种情况下给予morganstanley.com.这有什么不对?

python urllib2

1
推荐指数
1
解决办法
5581
查看次数

标签 统计

python ×2

urllib2 ×2