说明:python的urllib2获取网页(urlopen)会自动重定向(301,302)。但是,有时候我们需要获取302,301页面的状态信息。就必须获取到转向前的调试信息。
下面代码将可以做到避免302重定向到新的网页
#!/usr/bin/python# -*- Coding: utf-8 -*-#enCoding=utf-8#filename:states_code.py import urllib2 class RedirctHandler(urllib2.httpRedirectHandler): """docstring for RedirctHandler""" def http_error_301(self,req,fp,code,msg,headers): pass def http_error_302(self,headers): pass def getUnRedirectUrl(url,timeout=10): req = urllib2.Request(url) deBUG_handler = urllib2.httpHandler(deBUGlevel = 1) opener = urllib2.build_opener(deBUG_handler,RedirctHandler) HTML = None response = None try: response = opener.open(url,timeout=timeout) HTML = response.read() except urllib2.URLError as e: if hasattr(e,'code'): error_info = e.code elif hasattr(e,'reason'): error_info = e.reason finally: if response: response.close() if HTML: return HTML else: return error_info HTML = getUnRedirectUrl('http://jb51.net')print HTML
以上是内存溢出为你收集整理的Python中使用urllib2防止302跳转的代码例子全部内容,希望文章能够帮你解决Python中使用urllib2防止302跳转的代码例子所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)