python网页请求urllib2模块简单封装代码
这篇文章主要分享一个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模块简单封装代码的更多相关文章
- python中的sockeserver模块简单实用
1. socketserver模块简介 在python的socket编程中,实用socket模块的时候,是不能实现多个连接的,当然如果加入其它的模块是可以的,例如select模块,在这里见到的介绍下s ...
- Python 中 对logging 模块进行封装,记录bug日志、日志等级
是程序产生的日志 程序员自定义设置的 收集器和渠道级别那个高就以那个级别输出 日志和报告的作用: 报告的重点在于执行结果(执行成功失败,多少用例覆盖),返回结果 日志的重点在执行过程当中,异常点,哪里 ...
- MongoDB Python官方驱动 PyMongo 的简单封装
最近,需要使用 Python 对 MongodB 做一些简单的操作,不想使用各种繁重的框架.出于可重用性的考虑,想对 MongoDB Python 官方驱动 PyMongo 做下简单封装,百度一如既往 ...
- Python urllib和urllib2模块学习(二)
一.urllib其它函数 前面介绍了 urllib 模块,以及它常用的 urlopen() 和 urlretrieve()函数的使用介绍.当然 urllib 还有一些其它很有用的辅助方法,比如对 ur ...
- Python中的urllib2模块解析
Name urllib2 - An extensible library for opening URLs using a variety of protocols 1. Description Th ...
- Extjs读取更改或者发送ajax返回请求的结果简单封装
Extjs的submit()方法提交的数据:如下: this.formPanel.getForm().submit({ url:this.saveUrl, ...
- Python urllib和urllib2模块学习(一)
(参考资料:现代魔法学院 http://www.nowamagic.net/academy/detail/1302803) Python标准库中有许多实用的工具类,但是在具体使用时,标准库文档上对使用 ...
- nodejs mysql模块简单封装
nodejs 简单的封装一些mysql模块 实现一个方法根据不同传参进行增删改查 首先要 npm install mysql 代码如下 function data(objHost,sql,callba ...
- React Native中的网络请求fetch和简单封装
React Native中的网络请求fetch使用方法最为简单,但却可以实现大多数的网络请求,需要了解更多的可以访问: https://segmentfault.com/a/1190000003810 ...
随机推荐
- jquery.cookie.js 配置
一定要写入cookies路径 一个轻量级的cookie 插件,可以读取.写入.删除 cookie. jquery.cookie.js 的配置 首先包含jQuery的库文件,在后面包含 jquery.c ...
- 【原】Nginx添加Content-MD5头部压测分析
如需转载,必须注明原文地址,请尊重作者劳动成果. http://www.cnblogs.com/lyongerr/p/5048464.html 本文介绍了webbenck安装,但是最后使用的是ab工具 ...
- 【转】三种不同类型的ssh隧道
转自:http://blog.creke.net/722.html 大家都知道SSH是一种安全的传输协议,用在连接服务器上比较多.不过其实除了这个功能,它的隧道转发功能更是吸引人.下面是个人根据自己的 ...
- php 深入理解addslashes函数
php addslashes函数对于很多人来说并不陌生,但很大部分人只是了解皮毛,只知道addslashes函数是在特定字符前面加上反斜杠,本文章将带大家深入理解php addslashes函数的使用 ...
- 使用csc命令进行编译
①如果csc不是内外部变量的情况下需要在计算机高级系统设置的环境变量里面下面的Path中将值的后面用分号隔开增加.net framework 4.0的文件路径 ②重新以“管理员身份运行cmd” ③将路 ...
- 链表:删除链表中重复的结点(java实现)
题目描述 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针. 例如,链表1->2->3->3->4->4->5 处理后 ...
- Orchard官方文档翻译(一) 总览
原文地址:http://docs.orchardproject.net/ 最近想要学习了解orchard,但却没有找到相关的中文文档,只有英文文档.于是决定自行翻译,以便日后方便翻阅. 转载请注明原作 ...
- 百度富文本编辑器UEditor安装配置全过程
网站开发时富文本编辑器是必不可少的,他可以让用户自行编辑内容的样式然后上传到后台!下面我们来介绍如何安装使用百度富文本编辑器 一.下载并且设置百度富文本编辑器的样式 你可以去百度UEditor ...
- 学习记录 java泛型资料
java泛型资料: 1. 概述在引入范型之前,Java类型分为原始类型.复杂类型,其中复杂类型分为数组和类.引入范型后,一个复杂类型就可以在细分成更多的类型.例如原先的类型List,现在在细分成Lis ...
- ASPxTreeList控件去根节点的新增修改操作(写在onCommandColumnButtonInitialize()事件中)
treelist去掉根节点按钮效果图: //去掉父节点及子节点旁的新增.修改.删除操作(写在onCommandColumnButtonInitialize事件中) protected void Tre ...