有没有一种简单的方法可以在python中请求URL而不遵循重定向?
时间:2020-03-06 14:30:08 来源:igfitidea点击:
查看urllib2的源代码,看起来最简单的方法是将HTTPRedirectHandler子类化,然后使用build_opener覆盖默认的HTTPRedirectHandler,但这似乎需要很多(相对复杂的工作)来完成应有的工作很简单。
解决方案
Dive Into Python有很好的章节介绍如何使用urllib2进行重定向。另一个解决方案是httplib。
>>> import httplib
>>> conn = httplib.HTTPConnection("www.bogosoft.com")
>>> conn.request("GET", "")
>>> r1 = conn.getresponse()
>>> print r1.status, r1.reason
301 Moved Permanently
>>> print r1.getheader('Location')
http://www.bogosoft.com/new/location
我第二次将olt的指针指向Dive into Python。这是一个使用urllib2重定向处理程序的实现,比应做的工作还要多?也许,耸耸肩。
import sys
import urllib2
class RedirectHandler(urllib2.HTTPRedirectHandler):
def http_error_301(self, req, fp, code, msg, headers):
result = urllib2.HTTPRedirectHandler.http_error_301(
self, req, fp, code, msg, headers)
result.status = code
raise Exception("Permanent Redirect: %s" % 301)
def http_error_302(self, req, fp, code, msg, headers):
result = urllib2.HTTPRedirectHandler.http_error_302(
self, req, fp, code, msg, headers)
result.status = code
raise Exception("Temporary Redirect: %s" % 302)
def main(script_name, url):
opener = urllib2.build_opener(RedirectHandler)
urllib2.install_opener(opener)
print urllib2.urlopen(url).read()
if __name__ == "__main__":
main(*sys.argv)
我想这会有所帮助
from httplib2 import Http def get_html(uri,num_redirections=0): # put it as 0 for not to follow redirects conn = Http() return conn.request(uri,redirections=num_redirections)

