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 ...
随机推荐
- 解决PHP生成校验码时“图像因其本身有错无法显示”的错误
今天使用http://crazymud.iteye.com/blog/452293给出的代码进行PHP生成校验码功能的实现,发现firefox一直提示“图像.......因其本身有错无法显示”的问题, ...
- 剑指Offer:面试题17——合并两个排序的链表
题目描述 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则. 思路1: 分别用p1,p2两个指针扫描两个有序链表,p3指针去构建新链表h3. p1.val & ...
- 测试一个域名DNS查询时间的shell脚本
脚本内容: #!/bin/bash #目标域名 site=${site:-www.ptesting.com} for((i=1;i<=10000;i++)) do #COUNTER='e ...
- 测试方法---"SFDIPOT"
SFDIPOT方法是快速测试的一种方法,可以帮助你快速理清测试点. 我粗略地想了一下,凡是面试时我遇到过的奇葩的让我测一个电梯.雨伞.电话.水杯.测一个奇怪的东西的面试题上都能用. 然后嘛,日常工作中 ...
- 在Ubuntu Server14.04上编译Android6.0源码
此前编译过Android4.4的源码,但是现在Android都到了7.0的版本,不禁让我感叹Google的步伐真心难跟上,趁这周周末时间比较充裕,于是在过去的24小时里,毅然花了9个小时编译了一把An ...
- C语言学习笔记(1):Hello World!
#include <stdio.h> void main() { printf("Hello World!\n"); } 几乎学习任何语言接触到的第一个语言都是Hell ...
- 手游设备ID
android: imei: IMEI(International Mobile Equipment Identity)是国际移动设备标识的缩写,IMEI由15位数字(英文字母)组成. mac: 是指 ...
- Could not find action or result
[WARN ] 2013-11-21 14:08:16 :Could not find action or resultThere is no Action mapped for namespace ...
- POJ2001-Shortest Prefixes-Trie树应用
沉迷WOW又颓了两天orz,暴雪爸爸要在国服出月卡了...这是要我好好学习吗?赶紧来刷题了... OJ:http://poj.org/problem?id=2001 题目大意是求所有字符串里每一个字符 ...
- 使用ngin的静态文件下载
1,主配置文件nginx.xml #user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error. ...