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正则表达式去掉数字中的逗号(python正则匹配逗号)
Dec 25 Python
使用Python的内建模块collections的教程
Apr 28 Python
python里使用正则的findall函数的实例详解
Oct 19 Python
Python使用Selenium+BeautifulSoup爬取淘宝搜索页
Feb 24 Python
详谈python3中用for循环删除列表中元素的坑
Apr 19 Python
Python实现的求解最小公倍数算法示例
May 03 Python
python绘制简单彩虹图
Nov 19 Python
11个Python3字典内置方法大全与示例汇总
May 13 Python
Python 使用PyQt5 完成选择文件或目录的对话框方法
Jun 27 Python
python 扩展print打印文件路径和当前时间信息的实例代码
Oct 11 Python
python传到前端的数据,双引号被转义的问题
Apr 03 Python
Python enumerate() 函数如何实现索引功能
Jun 29 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
构建简单的Webmail系统
2006/10/09 PHP
PHP程序员基本要求和必备技能
2014/05/09 PHP
在Mac OS上搭建PHP的Yii框架及相关测试环境
2016/02/14 PHP
PHP使用PhpSpreadsheet操作Excel实例详解
2020/03/26 PHP
JS 页面内容搜索,类似于 Ctrl+F功能的实现代码
2007/08/13 Javascript
jquery控制listbox中项的移动并排序的实现代码
2010/09/28 Javascript
jQuery 源码分析笔记(7) Queue
2011/06/19 Javascript
基于jquery自定义图片热区效果
2012/07/21 Javascript
JavaScript实现将UPC转换成ISBN的方法
2015/05/26 Javascript
JAVASCRIPT代码编写俄罗斯方块网页版
2015/11/26 Javascript
jQuery基于ajax()使用serialize()提交form数据的方法
2015/12/08 Javascript
Vue.js 表单校验插件
2016/08/14 Javascript
Actionscript与javascript交互实例程序(修改)
2016/09/22 Javascript
js return返回多个值,通过对象的属性访问方法
2017/02/21 Javascript
Servlet3.0与纯javascript通过Ajax交互的实例详解
2018/03/18 Javascript
Webpack中SplitChunksPlugin 配置参数详解
2020/03/24 Javascript
Vue proxyTable配置多个接口地址,解决跨域的问题
2020/09/11 Javascript
[06:13]DOTA2进化论(修改版)
2013/10/08 DOTA
pycharm 使用心得(四)显示行号
2014/06/05 Python
Python基于动态规划算法计算单词距离
2015/07/25 Python
Django中cookie的基本使用方法示例
2018/02/03 Python
Python实现判断一行代码是否为注释的方法
2018/05/23 Python
python3编写ThinkPHP命令执行Getshell的方法
2019/02/26 Python
浅析Python 实现一个自动化翻译和替换的工具
2019/04/14 Python
Python多进程multiprocessing、进程池用法实例分析
2020/03/24 Python
Jupyter Notebook折叠输出的内容实例
2020/04/22 Python
浅谈TensorFlow中读取图像数据的三种方式
2020/06/30 Python
python3 googletrans超时报错问题及翻译工具优化方案 附源码
2020/12/23 Python
python学习之使用Matplotlib画实时的动态折线图的示例代码
2021/02/25 Python
Antler英国官网:购买安特丽行李箱、拉杆箱
2019/08/25 全球购物
Agoda中文官网:安可达(低价预订全球酒店)
2021/01/18 全球购物
资深生产主管自我评价
2013/09/22 职场文书
2014个人年度工作总结范文
2014/12/24 职场文书
500字小学生检讨书
2015/02/19 职场文书
第二次离婚起诉书
2015/05/18 职场文书
辩护意见书
2015/06/04 职场文书