发布于 2014-11-09 12:54:09 | 601 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Python3 官方中文指南,程序狗速度看过来!

Python编程语言

Python 是一种面向对象、解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。Python语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是C/C++)很轻松地联结在一起。


本文主要为大家讲解了Python中如何使用urllib2防止302跳转的方法,即避免302跳转的实现,需要的朋友可以参考下

说明: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://phperz.com')
print html

 



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务