这篇文章主要分享一个python网页请求模块urllib2模块的简单封装代码。

原文转自:http://www.jbxue.com/article/16585.html

对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':''}
data = urllib.urlencode(value)
url = 'http://10.75.0.103:8850/2/photos/square/type.json'
user = 'wz_0001'
password = ''
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网页请求urllib2模块简单封装代码的更多相关文章

  1. python中的sockeserver模块简单实用

    1. socketserver模块简介 在python的socket编程中,实用socket模块的时候,是不能实现多个连接的,当然如果加入其它的模块是可以的,例如select模块,在这里见到的介绍下s ...

  2. Python 中 对logging 模块进行封装,记录bug日志、日志等级

    是程序产生的日志 程序员自定义设置的 收集器和渠道级别那个高就以那个级别输出 日志和报告的作用: 报告的重点在于执行结果(执行成功失败,多少用例覆盖),返回结果 日志的重点在执行过程当中,异常点,哪里 ...

  3. MongoDB Python官方驱动 PyMongo 的简单封装

    最近,需要使用 Python 对 MongodB 做一些简单的操作,不想使用各种繁重的框架.出于可重用性的考虑,想对 MongoDB Python 官方驱动 PyMongo 做下简单封装,百度一如既往 ...

  4. Python urllib和urllib2模块学习(二)

    一.urllib其它函数 前面介绍了 urllib 模块,以及它常用的 urlopen() 和 urlretrieve()函数的使用介绍.当然 urllib 还有一些其它很有用的辅助方法,比如对 ur ...

  5. Python中的urllib2模块解析

    Name urllib2 - An extensible library for opening URLs using a variety of protocols 1. Description Th ...

  6. Extjs读取更改或者发送ajax返回请求的结果简单封装

    Extjs的submit()方法提交的数据:如下: this.formPanel.getForm().submit({                url:this.saveUrl,         ...

  7. Python urllib和urllib2模块学习(一)

    (参考资料:现代魔法学院 http://www.nowamagic.net/academy/detail/1302803) Python标准库中有许多实用的工具类,但是在具体使用时,标准库文档上对使用 ...

  8. nodejs mysql模块简单封装

    nodejs 简单的封装一些mysql模块 实现一个方法根据不同传参进行增删改查 首先要 npm install mysql 代码如下 function data(objHost,sql,callba ...

  9. React Native中的网络请求fetch和简单封装

    React Native中的网络请求fetch使用方法最为简单,但却可以实现大多数的网络请求,需要了解更多的可以访问: https://segmentfault.com/a/1190000003810 ...

随机推荐

  1. 使用jaxp对比xml进行DOM解析

    /*DOM解析编程 •遍历所有节点 •查找某一个节点 •删除结点 •更新结点 •添加节点 /* package cn.itcast.jaxp; import java.io.File; import ...

  2. Tools之FindBugs

    我们先来看FindBugs.(因为我们的错误通常分为两种,静态错误和动态错误也就是运行时的,而FindBugs是一个Java代码静态错误分析工具.) 1) 安装 Help->SoftWare U ...

  3. null 之AddAll、Add和Boolean

    @Test //failed public void TestListAddAll(){ List<TravelerInfo> travelerInfoSummary=new ArrayL ...

  4. HDU 1856

    http://acm.split.hdu.edu.cn/showproblem.php?pid=1856 对于这道题,主要就是让你求出有最多结点的树的树叶: 我们只要利用并查集的知识吧所输入的数据连接 ...

  5. [Java] 我的Coding Style 总结

    1. 缩进 采用4个空格的缩进方式 2. tab 不采用"hard" tab. 需要更改编辑器的默认配置.将tab值改成4个空格. 3. 换行 3.1 一行不超过75个字符 3.2 ...

  6. C语言学习笔记(1):Hello World!

    #include <stdio.h> void main() { printf("Hello World!\n"); } 几乎学习任何语言接触到的第一个语言都是Hell ...

  7. Leveldb 实现原理

    原文地址:http://www.cnblogs.com/haippy/archive/2011/12/04/2276064.html LevelDb日知录之一:LevelDb 101 说起LevelD ...

  8. AudioPlayer.js,一个响应式且支持触摸操作的jquery音频插件

    AudioPlayer.js是一个响应式.支持触摸操作的HTML5 的音乐播放器.本文是对其官网的说用说明文档得翻译,博主第一次翻译外文.不到之处还请谅解.之处. JS文件地址:http://osva ...

  9. Java虚拟机内存模型及垃圾回收监控调优

    Java虚拟机内存模型及垃圾回收监控调优 如果你想理解Java垃圾回收如果工作,那么理解JVM的内存模型就显的非常重要.今天我们就来看看JVM内存的各不同部分及如果监控和实现垃圾回收调优. JVM内存 ...

  10. 未在本地计算机上注册“Microsoft.Jet.OLEDB.4.0”提供程序的处理方式

    今天客户向我反映一个问题,当他们在用我们的系统导出excel表格时,报错:未在本地计算机上注册“Microsoft.Jet.OLEDB.4.0”提供程序 经过找资料终于得到解决方法,记录一下. 在对应 ...