Python:防止urllib2 302自动跳转

例子

importurllib2

classRedirctHandler(urllib2.HTTPRedirectHandler):

"""docstring for RedirctHandler"""

defhttp_error_301(self, req, fp, code, msg, headers):

pass

defhttp_error_302(self, req, fp, code, msg, headers):

pass

defgetUnRedirectUrl(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()

excepturllib2.URLError as e:

ifhasattr(e,'code'):

error_info=e.code

elifhasattr(e,'reason'):

error_info=e.reason

finally:

ifresponse:

response.close()

ifhtml:

returnhtml

else:

returnerror_info

html=getUnRedirectUrl('http://phpno.com')

printhtml