Python中使用urllib2防止302跳转的代码例子

yipeiwu_com5年前Python基础

说明: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, req, fp, code, msg, 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


相关文章

详解如何在cmd命令窗口中搭建简单的python开发环境

详解如何在cmd命令窗口中搭建简单的python开发环境

1、快捷键win+r输入cmd回车调出cmd界面,在命令行输入python回车,显示python命令无法识别 2、登陆python官网https://www.python.org/,...

python防止随意修改类属性的实现方法

如果不想允许随意修改一个类的某个属性,常用的方法是使用property装饰器以及在属性前加下划线。 class V: def __init__(self, x): se...

python开发中range()函数用法实例分析

本文实例讲述了python开发中range()函数用法。分享给大家供大家参考,具体如下: python中的range()函数的功能很强大,所以我觉得很有必要和大家分享一下 就好像其API...

numpy添加新的维度:newaxis的方法

numpy添加新的维度:newaxis的方法

numpy中包含的newaxis可以给原数组增加一个维度 np.newaxis放的位置不同,产生的新数组也不同 一维数组 x = np.random.randint(1, 8, si...

Python 加密的实例详解

 Python 加密的实例详解 hashlib支持md5,sha1,sha256,sha384,sha512,用法和md5一样  import hashlib...