python网页请求urllib2模块简单封装代码


Posted in Python onFebruary 07, 2014

对python网页请求模块urllib2进行简单的封装。

例子:

#!/usr/bin/python
#coding: utf-8
import base64
import urllib
import urllib2
import time
class SendRequest:
  '''
  This class use to set and request the http, and get the info of response.
  e.g. set Authorization Type, request tyep..
  e.g. get html content, state code, cookie..
  SendRequest('http://10.75.0.103:8850/2/photos/square/type.json', 
              data='source=216274069', type='POST', auth='base',
     user='zl2010', password='111111')
  '''
  def __init__(self, url, data=None, type='GET', auth=None, user=None, password=None, cookie = None, **header):
    '''
    url:request, raise error if none
    date: data for post or get, must be dict type
    type: GET, POST
    auth: option, if has the value must be 'base' or 'cookie'
    user: user for auth
    password: password for auth
    cookie: if request with cookie 
    other header info: 
    e.g. referer='www.sina.com.cn'    
    '''
    self.url = url
    self.data = data
    self.type = type
    self.auth = auth
    self.user = user
    self.password = password 
    self.cookie = cookie 
    if 'referer' in header:
      self.referer = header[referer]
    else:
      self.referer = None
    if 'user-agent' in header:
      self.user_agent = header[user-agent]
    else:
      self.user_agent = None
    self.setup_request()
    self.send_request() 
  def setup_request(self):
    '''
    setup a request 
    '''
    if self.url == None or self.url == '':
      raise 'The url should not empty!'
    # set request type 
    #print self.url
    #print self.type
    #print self.data
    #print self.auth
    #print self.user
    #print self.password  
    if self.type == 'POST': 
      self.Req = urllib2.Request(self.url, self.data)
    elif self.type == 'GET':
      if self.data == None:
          self.Req = urllib2.Request(self.url)
      else:
        self.Req = urllib2.Request(self.url + '?' + self.data)
    else:
      print 'The http request type NOT support now!'
    ##set auth type 
    if self.auth == 'base':
      if self.user == None or self.password == None:
        raise 'The user or password was not given!'
      else:
        auth_info = base64.encodestring(self.user + ':' + self.password).replace('\n','')
        auth_info = 'Basic ' + auth_info 
        #print auth_info  
        self.Req.add_header("Authorization", auth_info)
    elif self.auth == 'cookie':
      if self.cookie == None:
        raise 'The cookie was not given!'
      else:
        self.Req.add_header("Cookie", self.cookie) 
    else:
      pass    ##add other auth type here 
    ##set other header info 
    if self.referer:
      self.Req.add_header('referer', self.referer)
    if self.user_agent:
      self.Req.add_header('user-agent', self.user_agent)
      
  def send_request(self):  
    '''
    send a request 
    '''
    # get a response object 
    try:
      self.Res = urllib2.urlopen(self.Req)
      self.source = self.Res.read()
      self.goal_url = self.Res.geturl()
      self.code = self.Res.getcode()
      self.head_dict = self.Res.info().dict
      self.Res.close()
    except urllib2.HTTPError, e:
      self.code = e.code
      print e
        
  def get_code(self):
    return self.code
  def get_url(self):
    return self.goal_url
  def get_source(self):        
    return self.source
  def get_header_info(self):
    return self.head_dict
  def get_cookie(self):
    if 'set-cookie' in self.head_dict:
      return self.head_dict['set-cookie']
    else:
      return None    
  def get_content_type(self):
    if 'content-type' in self.head_dict:
      return self.head_dict['content-type']
    else:
      return None
  def get_expires_time(self):
    if 'expires' in self.head_dict:
      return self.head_dict['expires']
    else:
      return None    
  def get_server_name(self):
    if 'server' in self.head_dict:
      return self.head_dict['server']
    else:
      return None   
  def __del__(self):
    pass   
__all__ = [SendRequest,]
if __name__ == '__main__':
  '''
  The example for using the SendRequest class 
  '''
  value = {'source':'216274069'}
  data = urllib.urlencode(value)
  url = 'http://10.75.0.103:8850/2/photos/square/type.json'
  user = 'wz_0001'
  password = '111111'
  auth = 'base'
  type = 'POST'
  t2 = time.time()
  rs = SendRequest('http://www.google.com')
  #rs = SendRequest(url, data=data, type=type, auth=auth, user=user, password=password)
  print 't2: ' + str(time.time() - t2)
  print '---------------get_code()---------------'
  print rs.get_code()
  print '---------------get_url()---------------'
  print rs.get_url()
  print '---------------get_source()---------------'
  print rs.get_source()
  print '---------------get_cookie()---------------'
  print rs.get_cookie()
  rs = None
Python 相关文章推荐
python实现的二叉树算法和kmp算法实例
Apr 25 Python
跟老齐学Python之不要红头文件(2)
Sep 28 Python
用Python制作检测Linux运行信息的工具的教程
Apr 01 Python
Pyhthon中使用compileall模块编译源文件为pyc文件
Apr 28 Python
python实现计算倒数的方法
Jul 11 Python
用python的requests第三方模块抓取王者荣耀所有英雄的皮肤实例
Dec 14 Python
Python装饰器限制函数运行时间超时则退出执行
Apr 09 Python
Python 进程之间共享数据(全局变量)的方法
Jul 16 Python
python性能测量工具cProfile使用解析
Sep 26 Python
Python基于pygame实现单机版五子棋对战
Dec 26 Python
使用keras根据层名称来初始化网络
May 21 Python
浅谈python出错时traceback的解读
Jul 15 Python
python解析xml模块封装代码
Feb 07 #Python
python 解析XML python模块xml.dom解析xml实例代码
Feb 07 #Python
python合并文本文件示例
Feb 07 #Python
python实现哈希表
Feb 07 #Python
python处理cookie详解
Feb 07 #Python
urllib2自定义opener详解
Feb 07 #Python
python解析html开发库pyquery使用方法
Feb 07 #Python
You might like
PHP命名空间(namespace)的使用基础及示例
2014/08/18 PHP
Laravel实现构造函数自动依赖注入的方法
2016/03/16 PHP
PHP页面静态化――纯静态与伪静态用法详解
2020/06/05 PHP
js渐变显示渐变消失示例代码
2013/08/01 Javascript
开发中可能会用到的jQuery小技巧
2014/03/07 Javascript
javascript中兼容主流浏览器的动态生成iframe方法
2014/05/05 Javascript
jQuery实现自动调整字体大小的方法
2015/06/15 Javascript
举例讲解JavaScript中将数组元素转换为字符串的方法
2015/10/25 Javascript
JavaScript设计模式初探
2016/01/07 Javascript
BootStrap中Datetimepicker和uploadify插件应用实例小结
2016/05/26 Javascript
AngularJs bootstrap搭载前台框架——js控制部分
2016/09/01 Javascript
jQuery中ztree 点击文本框弹出下拉框的实例代码
2017/02/05 Javascript
jquery ui sortable拖拽后保存位置
2017/04/27 jQuery
如何使用JS在HTML中自定义字符串格式化
2017/07/20 Javascript
Jquery实现无缝向上循环滚动列表的特效
2019/02/13 jQuery
详解vue中axios的使用与封装
2019/03/20 Javascript
小程序使用watch监听数据变化的方法详解
2019/09/20 Javascript
[43:36]Liquid vs Mineski 2018国际邀请赛小组赛BO2 第一场 8.18
2018/08/19 DOTA
利用Python中的输入和输出功能进行读取和写入的教程
2015/04/14 Python
python3 实现的人人影视网站自动签到
2016/06/19 Python
详谈Python2.6和Python3.0中对除法操作的异同
2017/04/28 Python
Python 实现引用其他.py文件中的类和类的方法
2018/04/29 Python
Python简单获取网卡名称及其IP地址的方法【基于psutil模块】
2018/05/24 Python
python  文件的基本操作 菜中菜功能的实例代码
2019/07/17 Python
django 通过url实现简单的权限控制的例子
2019/08/16 Python
python进阶之自定义可迭代的类
2019/08/20 Python
python+Django实现防止SQL注入的办法
2019/10/31 Python
Python操作多维数组输出和矩阵运算示例
2019/11/28 Python
Pandas的数据过滤实现
2021/01/15 Python
CSS3控制HTML元素动画效果
2014/02/08 HTML / CSS
Finishline官网:美国一家领先的运动品牌鞋类、服装零售商
2016/07/20 全球购物
写给女生的道歉信
2014/01/08 职场文书
夜不归宿检讨书
2014/02/25 职场文书
初中生操行评语大全
2014/04/24 职场文书
服务整改报告
2014/11/06 职场文书
交通安全月活动总结
2015/05/08 职场文书