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


相关文章

使用rpclib进行Python网络编程时的注释问题

rpclib 是一个非常好用的 python webservice 库,可以动态的生成 wsdl, 不过这个项目已经基本停止,并被一个新的项目取代 spyne,由于旧的项目 工作已经比较...

更新修改后的Python模块方法

更新修改后的Python模块方法

python如何更新修改后的Python模块 1.利用python的MySQLdb模块利用原生的sql语句进行更新的方法代码 配置方法代码 2.使用execute方法执行SQL语句方法...

Python实现导出数据生成excel报表的方法示例

本文实例讲述了Python实现导出数据生成excel报表的方法。分享给大家供大家参考,具体如下: #_*_coding:utf-8_*_ import MySQLdb import...

批量将ppt转换为pdf的Python代码 只要27行!

这是一个Python脚本,能够批量地将微软Powerpoint文件(.ppt或者.pptx)转换为pdf格式。 使用说明 1、将这个脚本跟PPT文件放置在同一个文件夹下。 2、运行这个脚...

深入浅析python3中的unicode和bytes问题

最近写了一些python3程序,四处能看到bytes类型,而它并不存在于python2中,这也是python3和python2显著区别之一。 以前在写python2代码的时候,经常会遇到...