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实现按行切分文本文件的方法
Apr 18 Python
python正则表达式的使用
Jun 12 Python
pygame 精灵的行走及二段跳的实现方法(必看篇)
Jul 10 Python
python实现图片处理和特征提取详解
Nov 13 Python
Python设计模式之MVC模式简单示例
Jan 10 Python
Python实现抢购IPhone手机
Feb 07 Python
Python利用ORM控制MongoDB(MongoEngine)的步骤全纪录
Sep 13 Python
Python3内置模块之json编解码方法小结【推荐】
Dec 09 Python
Python通过Tesseract库实现文字识别
Mar 05 Python
基于Django OneToOneField和ForeignKey的区别详解
Mar 30 Python
python是怎么被发明的
Jun 15 Python
python实现简单的五子棋游戏
Sep 01 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内核探索之变量
2015/12/22 PHP
PHP实现将base64编码字符串转换成图片示例
2018/06/22 PHP
js中数组Array的一些常用方法总结
2013/08/12 Javascript
使用js画图之画切线
2015/01/12 Javascript
在JavaScript中处理时间之getHours()方法的使用
2015/06/10 Javascript
Jquery easyui开启行编辑模式增删改操作
2016/01/14 Javascript
jQuery循环遍历子节点并获取值的方法
2016/04/14 Javascript
jQuery 3.0中存在问题及解决办法
2016/07/15 Javascript
Bootstrap 3的box-sizing样式导致UEditor控件的图片无法正常缩放的解决方案
2016/09/15 Javascript
javascript中获取元素标签中间的内容的实现方法
2016/10/08 Javascript
ES6新特性之变量和字符串用法示例
2017/04/01 Javascript
angular $watch 一个变量的变化(实例讲解)
2017/08/02 Javascript
vue.js实现的绑定class操作示例
2018/07/06 Javascript
vue路由跳转传参数的方法
2019/05/06 Javascript
layui操作列按钮个数和文字颜色的判断实例
2019/09/11 Javascript
[01:02:20]Mineski vs TNC 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/16 DOTA
python写的ARP攻击代码实例
2014/06/04 Python
浅析Python中的多进程与多线程的使用
2015/04/07 Python
python递归计算N!的方法
2015/05/05 Python
Python for Informatics 第11章之正则表达式(四)
2016/04/21 Python
python队列queue模块详解
2018/04/27 Python
python异常触发及自定义异常类解析
2019/08/06 Python
用python拟合等角螺线的实现示例
2019/12/27 Python
使用python实现CGI环境搭建过程解析
2020/04/28 Python
Python 实现一个计时器
2020/07/28 Python
德国骆驼商店:ActiveFashionWorld
2017/11/18 全球购物
LODI女鞋在线商店:阿利坎特的鞋类品牌
2019/02/15 全球购物
俄罗斯GamePark游戏商店网站:购买游戏、游戏机和配件
2020/03/13 全球购物
应届优秀本科大学毕业生自我鉴定
2014/01/21 职场文书
经理管理专业毕业自荐书范文
2014/02/12 职场文书
最新优秀教师个人先进事迹材料
2014/05/06 职场文书
2014年教育工作总结
2014/11/26 职场文书
2015年读书月活动总结
2015/03/26 职场文书
天那边观后感
2015/06/09 职场文书
导游词之西递宏村
2019/12/10 职场文书
JS数组方法some、every和find的使用详情
2021/10/05 Javascript