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使用chardet判断字符串编码的方法
Mar 13 Python
在Django框架中伪造捕捉到的URLconf值的方法
Jul 18 Python
python实现JAVA源代码从ANSI到UTF-8的批量转换方法
Aug 10 Python
浅谈python import引入不同路径下的模块
Jul 11 Python
python向已存在的excel中新增表,不覆盖原数据的实例
May 02 Python
查看django版本的方法分享
May 14 Python
opencv 获取rtsp流媒体视频的实现方法
Aug 23 Python
Python爬虫实现使用beautifulSoup4爬取名言网功能案例
Sep 15 Python
python实现在多维数组中挑选符合条件的全部元素
Nov 26 Python
关于Pytorch的MNIST数据集的预处理详解
Jan 10 Python
Python中Selenium库使用教程详解
Jul 23 Python
Python爬虫入门案例之回车桌面壁纸网美女图片采集
Oct 16 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作为Shell脚本语言使用
2006/10/09 PHP
聊天室php&mysql(三)
2006/10/09 PHP
php expects parameter 1 to be resource, array given 错误
2011/03/23 PHP
php nginx 实时输出的简单实现方法
2018/01/21 PHP
仅用[]()+!等符号就足以实现几乎任意Javascript代码
2010/03/01 Javascript
jQuery探测位置的提示弹窗(toolTip box)详细解析
2013/11/14 Javascript
JS调试必备的5个debug技巧
2014/03/07 Javascript
简介AngularJS的视图功能应用
2015/06/17 Javascript
Bootstrap 源代码分析(未完待续)
2016/08/17 Javascript
Bootstrap如何创建表单
2016/10/21 Javascript
Vue+Element使用富文本编辑器的示例代码
2017/08/14 Javascript
vue使用drag与drop实现拖拽的示例代码
2017/09/07 Javascript
angular中不同的组件间传值与通信的方法
2017/11/04 Javascript
Vue入门之animate过渡动画效果
2018/04/08 Javascript
详解Vue Elementui中的Tag与页面其它元素相互交互的两三事
2018/09/25 Javascript
Vue移动端项目实现使用手机预览调试操作
2020/07/18 Javascript
NodeJS开发人员常见五个错误理解
2020/10/14 NodeJs
[02:19]2014DOTA2国际邀请赛 专访820少年们一起去追梦吧
2014/07/14 DOTA
[49:18]2018DOTA2亚洲邀请赛 3.31 小组赛 A组 OG vs TNC
2018/04/01 DOTA
Windows下Python3.6安装第三方模块的方法
2018/11/22 Python
通过python爬虫赚钱的方法
2019/01/29 Python
pycharm访问mysql数据库的方法步骤
2019/06/18 Python
python 判断linux进程,并杀死进程的实现方法
2019/07/01 Python
PyCharm配置anaconda环境的步骤详解
2020/07/31 Python
HTML5仿手机微信聊天界面
2016/03/18 HTML / CSS
HTML中fieldset标签概述及使用方法
2013/02/01 HTML / CSS
初中音乐教学反思
2014/01/12 职场文书
招聘专员岗位职责
2014/03/07 职场文书
超市中秋节促销方案
2014/03/21 职场文书
物流管理专业推荐信
2014/09/06 职场文书
2014年预备党员端正入党动机思想汇报
2014/09/13 职场文书
终止劳动合同协议书
2014/10/05 职场文书
工程质检员岗位职责
2015/04/08 职场文书
网络妈妈观后感
2015/06/08 职场文书
2016年党员创先争优公开承诺书
2016/03/25 职场文书
go xorm框架的使用
2021/05/22 Golang