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 ...
随机推荐
- log4net 日志写入MongoDB 实现分布式日志
本人在.net framework 4.5下测试成功,首先需要安装log4mongo-net组件,见https://www.nuget.org/packages/log4mongo-net/ vs20 ...
- 配置IISExpress允许外部访问
1.找到IISExpress的配置文件,位于 <文档>/IISExpress/config文件夹下,打开applicationhost.config,找到如下代码: <site na ...
- 搭建hive1.2.1图形界面
下载:apache-hive-1.2.1-src.tar apache-hive-1.2.1-src.tar 解压,cd apache-hive-1.2.1-src/hwi 命令:jar cfM hi ...
- 交易Txt文件导出
private void writeFYFileToTxt(List list, HttpServletRequest request, String drxh, FileOutputStream f ...
- 《Head First 设计模式》ch.2 观察者(Observer)模式
观察者模式 定义了对象之间一对多以来,这样一来,当一个对象改变状态时,它所有的依赖者都会收到通知并自动更新 设计原则-松耦合 松耦合将对象之间的互相依赖降到了最低——只要他们之间的接口仍被遵守 观察者 ...
- sqlserver 批量删除存储过程和批量修改存储过程的语句
sqlserver 批量删除存储过程和批量修改存储过程的语句- sqlserver 批量删除存储过程和批量修改存储过程的语句,需要的朋友可以参考下. - 修改: 复制代码 代码如下: declare ...
- Epic - Desirable Number
A number is called 'desirable' if all thedigits are strictly ascending eg: 159 as 1<5<9. You k ...
- Android开发-API指南-<meta-data>
<meta-data> 英文原文:http://developer.android.com/guide/topics/manifest/meta-data-element.html 采集( ...
- php get传递数据
url:?goods[]=924&goods[]=967&goods[]=993 <?php if($_GET){ print_r($_GET); } ...
- php curl 提交 总结
1.post https提交 方法 function curl_post2($url='', $postdata='', $options=array()){ $ch = curl_init($url ...