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

yipeiwu_com6年前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


相关文章

Python批量修改文本文件内容的方法

Python批量替换文件内容,支持嵌套文件夹 import os path="./" for root,dirs,files in os.walk(path): for name...

详解python持久化文件读写

持久化文件读写: f=open('info.txt','a+') f.seek(0) str1=f.read() if len(str1)==0: f1 = open('info...

Python linecache.getline()读取文件中特定一行的脚本

Python linecache.getline()读取文件中特定一行的脚本

比如: ˂!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHig...

用Python编写一个国际象棋AI程序

用Python编写一个国际象棋AI程序

最近我用Python做了一个国际象棋程序并把代码发布在Github上了。这个代码不到1000行,大概20%用来实现AI。在这篇文章中我会介绍这个AI如何工作,每一个部分做什么,它为什么能...

python实现批量改文件名称的方法

本文实例讲述了python实现批量改文件名称的方法。分享给大家供大家参考。具体分析如下: 发现python中提供了大量的模块函数,有时候一些系统操作在python中非常简单 下面的文件关...