• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > Python中使用urllib2防止302跳转的代码例子

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

作者:junjie 字体:[增加 减小] 来源:互联网

junjie 通过本文主要向大家介绍了python urllib2,python3安装urllib2,python3 urllib2,python urllib2下载,python3中urllib2等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

说明: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
</div>


</div>

您可能想查找下面的文章:

  • 【Python】Python的urllib模块、urllib2模块批量进行网页下载文件
  • Python网络编程中urllib2模块的用法总结
  • Python使用urllib2模块抓取HTML页面资源的实例分享
  • Python使用urllib2模块抓取HTML页面资源的实例分享
  • 使用Python的urllib2模块处理url和图片的技巧两则
  • 使用Python的urllib2模块处理url和图片的技巧两则
  • Python中的urllib模块使用详解
  • python使用urllib2提交http post请求的方法
  • python使用urllib2提交http post请求的方法
  • python基于urllib实现按照百度音乐分类下载mp3的方法

相关文章

  • 简介二分查找算法与相关的Python实现示例
  • python实现从ftp服务器下载文件的方法
  • 举例讲解Python中装饰器的用法
  • Python中的yield浅析
  • python操作字典类型的常用方法(推荐)
  • python抓取网页图片示例(python爬虫)
  • Python新手实现2048小游戏
  • 图文讲解选择排序算法的原理及在Python中的实现
  • Python实现TCP协议下的端口映射功能的脚本程序示例
  • python PIL模块与随机生成中文验证码

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • python连接mongodb操作数据示例(mongodb数据库配置类)
    • 利用matplotlib+numpy绘制多种绘图的方法实例
    • Python编程实现输入某年某月某日计算出这一天是该年第几天的方法
    • 用Python和MD5实现网站挂马检测程序
    • 利用python爬取软考试题之ip自动代理
    • python实现二维码扫码自动登录淘宝
    • Python3读取文件常用方法实例分析
    • python自定义解析简单xml格式文件的方法
    • 浅谈Python数据类型之间的转换
    • Python中列表、字典、元组数据结构的简单学习笔记

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有