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


相关文章

selenium + python 获取table数据的示例讲解

方法一: <code class="language-python">""" 根据table的id属性和table中的某一个元素定位其在table中的位置 table...

举例讲解Linux系统下Python调用系统Shell的方法

时候难免需要直接调用Shell命令来完成一些比较简单的操作,比如mount一个文件系统之类的。那么我们使用Python如何调用Linux的Shell命令?下面来介绍几种常用的方法: 1....

Python代码块及缓存机制原理详解

这篇文章主要介绍了Python代码块及缓存机制原理详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.相同的字符串在Python中...

python找出一个列表中相同元素的多个索引实例

定义:X=[1,2,3,1,4] 任务:找出元素为1的索引 Solution: # 如果直接用X.index(1),只能得到0这一个索引,而我们需要所有索引. l = len(X)...

Python中decorator使用实例

在我以前介绍 Python 2.4 特性的Blog中已经介绍过了decorator了,不过,那时是照猫画虎,现在再仔细描述一下它的使用。 关于decorator的详细介绍在 Python...