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


相关文章

Django为窗体加上防机器人的验证码功能过程解析

Django为窗体加上防机器人的验证码功能过程解析

这里我们使用 django-simple-captcha 模块,官方介绍如下:https://github.com/mbi/django-simple-captcha 一键安装: p...

Python中SOAP项目的介绍及其在web开发中的应用

SOAP.py 客户机和服务器 SOAP.py 包含的是一些基本的东西。没有 Web 服务描述语言(Web Services Description Language,WSDL)或者任何...

基于DataFrame改变列类型的方法

今天用numpy 的linalg.det()求矩阵的逆的过程中出现了一个错误: TypeError: No loop matching the specified signature...

Django中login_required装饰器的深入介绍

前言 Django提供了多种装饰器, 其中login_required可能是经常会使用到的。 这里介绍下四种使用此装饰器的办法。 当然, 在使用前, 记得在工程目录的settings.p...

浅谈python中列表、字符串、字典的常用操作

列表操作如此下: a = ["haha","xixi","baba"] 增:a.append[gg] a.insert[1,gg] 在下标为1的地方,新增 gg 删:a.rem...