在Python3中合并了 urllib 和 urllib2, 统一命名为 urllib 了,我觉得这样更加合理了。让我们可以像读取本地文件一样读取WEB上的数据。封装了一个类,供以后方便使用吧!并附带有许多的应用实例。

一、封装的类

#!/usr/bin/env python3
# -*- coding: utf-8 -*- import time
import sys
import gzip
import socket
import urllib.request, urllib.parse, urllib.error
import http.cookiejar class HttpTester:
def __init__(self, timeout=10, addHeaders=True):
socket.setdefaulttimeout(timeout) # 设置超时时间 self.__opener = urllib.request.build_opener()
urllib.request.install_opener(self.__opener) if addHeaders: self.__addHeaders() def __error(self, e):
'''''错误处理'''
print(e) def __addHeaders(self):
'''''添加默认的 headers.'''
self.__opener.addheaders = [('User-Agent', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'),
('Connection', 'keep-alive'),
('Cache-Control', 'no-cache'),
('Accept-Language:', 'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3'),
('Accept-Encoding', 'gzip, deflate'),
('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')] def __decode(self, webPage, charset):
'''''gzip解压,并根据指定的编码解码网页'''
if webPage.startswith(b'\x1f\x8b'):
return gzip.decompress(webPage).decode(charset)
else:
return webPage.decode(charset) def addCookiejar(self):
'''''为 self.__opener 添加 cookiejar handler。'''
cj = http.cookiejar.CookieJar()
self.__opener.add_handler(urllib.request.HTTPCookieProcessor(cj)) def addProxy(self, host, type='http'):
'''''设置代理'''
proxy = urllib.request.ProxyHandler({type: host})
self.__opener.add_handler(proxy) def addAuth(self, url, user, pwd):
'''''添加认证'''
pwdMsg = urllib.request.HTTPPasswordMgrWithDefaultRealm()
pwdMsg.add_password(None, url, user, pwd)
auth = urllib.request.HTTPBasicAuthHandler(pwdMsg)
self.__opener.add_handler(auth) def get(self, url, params={}, headers={}, charset='UTF-8'):
'''''HTTP GET 方法'''
if params: url += '?' + urllib.parse.urlencode(params)
request = urllib.request.Request(url)
for k,v in headers.items(): request.add_header(k, v) # 为特定的 request 添加指定的 headers try:
response = urllib.request.urlopen(request)
except urllib.error.HTTPError as e:
self.__error(e)
else:
return self.__decode(response.read(), charset) def post(self, url, params={}, headers={}, charset='UTF-8'):
'''''HTTP POST 方法'''
params = urllib.parse.urlencode(params)
request = urllib.request.Request(url, data=params.encode(charset)) # 带 data 参数的 request 被认为是 POST 方法。
for k,v in headers.items(): request.add_header(k, v) try:
response = urllib.request.urlopen(request)
except urllib.error.HTTPError as e:
self.__error(e)
else:
return self.__decode(response.read(), charset) def download(self, url, savefile):
'''''下载文件或网页'''
header_gzip = None for header in self.__opener.addheaders: # 移除支持 gzip 压缩的 header
if 'Accept-Encoding' in header:
header_gzip = header
self.__opener.addheaders.remove(header) __perLen = 0
def reporthook(a, b, c): # a:已经下载的数据大小; b:数据大小; c:远程文件大小;
if c > 1000000:
nonlocal __perLen
per = (100.0 * a * b) / c
if per>100: per=100
per = '{:.2f}%'.format(per)
print('\b'*__perLen, per, end='') # 打印下载进度百分比
sys.stdout.flush()
__perLen = len(per)+1 print('--> {}\t'.format(url), end='')
try:
urllib.request.urlretrieve(url, savefile, reporthook) # reporthook 为回调钩子函数,用于显示下载进度
except urllib.error.HTTPError as e:
self.__error(e)
finally:
self.__opener.addheaders.append(header_gzip)
print()

二、应用实例

  1. 在OSC上动弹一下

Python3 的urllib实例的更多相关文章

  1. python3: 爬虫---- urllib, beautifulsoup

    最近晚上学习爬虫,首先从基本的开始: python3 将urllib,urllib2集成到urllib中了, urllib可以对指定的网页进行请求下载,  beautifulsoup 可以从杂乱的ht ...

  2. python3中urllib库的request模块详解

    刚刚接触爬虫,基础的东西得时时回顾才行,这么全面的帖子无论如何也得厚着脸皮转过来啊! 原帖地址:https://www.2cto.com/kf/201801/714859.html 什么是 Urlli ...

  3. Python3中urllib详细使用方法(header,代理,超时,认证,异常处理)

    urllib是python的一个获取url(Uniform Resource Locators,统一资源定址器)了,我们可以利用它来抓取远程的数据进行保存哦,下面整理了一些关于urllib使用中的一些 ...

  4. Python3中urllib详细使用方法(header,代理,超时,认证,异常处理) 转

    urllib是python的一个获取url(Uniform Resource Locators,统一资源定址器)了,我们可以利用它来抓取远程的数据进行保存哦,下面整理了一些关于urllib使用中的一些 ...

  5. Python2和Python3中urllib库中urlencode的使用注意事项

    前言 在Python中,我们通常使用urllib中的urlencode方法将字典编码,用于提交数据给url等操作,但是在Python2和Python3中urllib模块中所提供的urlencode的包 ...

  6. 常见的爬虫分析库(1)-Python3中Urllib库基本使用

    原文来自:https://www.cnblogs.com/0bug/p/8893677.html 什么是Urllib? Python内置的HTTP请求库 urllib.request          ...

  7. Python3中Urllib库基本使用

    什么是Urllib? Python内置的HTTP请求库 urllib.request          请求模块 urllib.error              异常处理模块 urllib.par ...

  8. Python -- 网络编程 -- 认识Python3的urllib库

    Python3的urllib包含5个模块 urllib error parse request response robotparser 各个模块的主要成员: error ['ContentTooSh ...

  9. Python3 使用 urllib 编写爬虫

    什么是爬虫 爬虫,也叫蜘蛛(Spider),如果把互联网比喻成一个蜘蛛网,Spider就是一只在网上爬来爬去的蜘蛛.网络爬虫就是根据网页的地址来寻找网页的,也就是URL.举一个简单的例子,我们在浏览器 ...

随机推荐

  1. 选择使用Spring框架的原因(Spring框架为企业级开发带来的好处有哪些)

  2. 有关写log的思考

    前言 在软件开发过程中,log往往是不太引人注意的环节,大部分的log都只是开发人员为了调试bug临时加上的.这样出来的软件,最后的log往往杂乱无章没有系统性.我们判断一个软件系统的log写的好不好 ...

  3. hibernate——第一次简单的使用

    提前有jdk.mysql.hibernate必须jar包.mysql连接jar包 mysql中的表 Java中的bean,User类 package com.xiaostudy.demo; publi ...

  4. Git如何进行分支管理?

    Git如何进行分支管理?     1.创建分支     创建分支很简单:git branch <分支名>     2.切换分支     git checkout <分支名>   ...

  5. Appium 自动化测试(2)--环境安装:安装Android模拟器

    一.安装java 环境-JDK 略,自行百度安装. 二.安装Android SDK Android SDK提供给我们API库和开发工具构建,测试和调试应用程序,Android.简单来讲,Android ...

  6. lightoj1138

    二分 #include<map> #include<set> #include<cmath> #include<queue> #include<s ...

  7. hash路由(哈希路由)

    1.https://www.cnblogs.com/huanying2015/p/8047376.html (js 哈希路由原理实现) 2.https://www.cnblogs.com/yeer/a ...

  8. Linux下Python安装(脚本全)

    在linux下安装Python: # 下载最新版本 cd /usr/local/src/ sudo wget http://www.python.org/ftp/python/3.3.2/Python ...

  9. socket http read

    import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.i ...

  10. 内存保护机制及绕过方案——从堆中绕过safeSEH

    1.1    SafeSEH内存保护机制 1.1.1    Windows异常处理机制 Windows中主要两种异常处理机制,Windows异常处理(VEH.SEH)和C++异常处理.Windows异 ...