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 使用os.remove删除文件夹时报错的解决方法

Python 使用os.remove删除文件夹时报错的解决方法

os.remove不能用来删除文件夹,否则拒绝访问。 # -*- coding:utf-8 -*-import osif __name__ == "__main__": os.remov...

Python实现k-means算法

Python实现k-means算法

本文实例为大家分享了Python实现k-means算法的具体代码,供大家参考,具体内容如下 这也是周志华《机器学习》的习题9.4。 数据集是西瓜数据集4.0,如下 编号,密度,含糖率...

python3 mmh3安装及使用方法

python3 mmh3安装及使用方法

mmh3安装方法 哈希方法主要有MD、SHA、Murmur、CityHash、MAC等几种方法。mmh3全程murmurhash3,是一种非加密的哈希算法,常用于hadoop等分布式存储...

python3实现带多张图片、附件的邮件发送

本文实例为大家分享了python3实现多张图片附件邮件发送的具体代码,供大家参考,具体内容如下 直接上代码,没有注释! from email.mime.text import MIM...

pymongo中聚合查询的使用方法

pymongo中聚合查询的使用方法

前言 在使用mongo数据库时,简单的查询基本上可以满足大多数的业务场景,但是试想一下,如果要统计某一荐在指定的数据中出现了多少次该怎么查询呢?笨的方法是使用find 将数据查询出来,再...