python中 urllib, urllib2, httplib, httplib2 几个库的区别
摘要: 只用 python3, 只用 urllib
若只使用python3.X, 下面可以不看了, 记住有个urllib的库就行了
python2.X 有这些库名可用: urllib, urllib2, urllib3, httplib, httplib2, requests
python3.X 有这些库名可用: urllib, urllib3, httplib2, requests
两者都有的urllib3和requests, 它们不是标准库. urllib3 提供线程安全连接池和文件post支持,与urllib及urllib2的关系不大. requests 自称HTTP for Humans, 使用更简洁方便
对于python2.X:
urllib和urllib2的主要区别:
- urllib2可以接受Request对象为URL设置头信息,修改用户代理,设置cookie等, urllib只能接受一个普通的URL.
- urllib提供一些比较原始基础的方法而urllib2没有这些, 比如 urlencode
urllib官方文档的几个例子
使用带参数的GET方法取回URL
>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params)
>>> print f.read()
使用POST方法
>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
>>> print f.read()
使用HTTP代理,自动跟踪重定向
>>> import urllib
>>> proxies = {'http': 'http://proxy.example.com:8080/'}
>>> opener = urllib.FancyURLopener(proxies)
>>> f = opener.open("http://www.python.org")
>>> f.read()
不使用代理
>>> import urllib
>>> opener = urllib.FancyURLopener({})
>>> f = opener.open("http://www.python.org/")
>>> f.read()
urllib2的几个官方文档的例子:
GET一个URL
>>> import urllib2
>>> f = urllib2.urlopen('http://www.python.org/')
>>> print f.read()
使用基本的HTTP认证
import urllib2
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
uri='https://mahler:8092/site-updates.py',
user='klem',
passwd='kadidd!ehopper')
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.example.com/login.html')
build_opener() 默认提供很多处理程序, 包括代理处理程序, 代理默认会被设置为环境变量所提供的.
一个使用代理的例子
proxy_handler = urllib2.ProxyHandler({'http': 'http://www.example.com:3128/'})
proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
opener = urllib2.build_opener(proxy_handler, proxy_auth_handler)
opener.open('http://www.example.com/login.html')
添加HTTP请求头部
import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
r = urllib2.urlopen(req)
更改User-agent
import urllib2
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
opener.open('http://www.example.com/')
** httplib 和 httplib2 ** httplib 是http客户端协议的实现,通常不直接使用, urllib是以httplib为基础 httplib2 是第三方库, 比httplib有更多特性
对于python3.X:
这里urllib成了一个包, 此包分成了几个模块,
urllib.request 用于打开和读取URL,
urllib.error 用于处理前面request引起的异常,
urllib.parse 用于解析URL,
urllib.robotparser用于解析robots.txt文件
python2.X 中的 urllib.urlopen()被废弃, urllib2.urlopen()相当于python3.X中的urllib.request.urlopen()
几个官方例子:
GET一个URL
>>> import urllib.request
>>> with urllib.request.urlopen('http://www.python.org/') as f:
... print(f.read(300))
PUT一个请求
import urllib.request
DATA=b'some data'
req = urllib.request.Request(url='http://localhost:8080', data=DATA,method='PUT')
with urllib.request.urlopen(req) as f:
pass
print(f.status)
print(f.reason)
基本的HTTP认证
import urllib.request
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
uri='https://mahler:8092/site-updates.py',
user='klem',
passwd='kadidd!ehopper')
opener = urllib.request.build_opener(auth_handler)
urllib.request.install_opener(opener)
urllib.request.urlopen('http://www.example.com/login.html')
使用proxy
proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'})
proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
opener.open('http://www.example.com/login.html')
添加头部
import urllib.request
req = urllib.request.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
r = urllib.request.urlopen(req)
更改User-agent
import urllib.request
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
opener.open('http://www.example.com/')
使用GET时设置URL的参数
>>> import urllib.request
>>> import urllib.parse
>>> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> url = "http://www.musi-cal.com/cgi-bin/query?%s" % params
>>> with urllib.request.urlopen(url) as f:
... print(f.read().decode('utf-8'))
...
使用POST时设置参数
>>> import urllib.request
>>> import urllib.parse
>>> data = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> data = data.encode('ascii')
>>> with urllib.request.urlopen("http://requestb.in/xrbl82xr", data) as f:
... print(f.read().decode('utf-8'))
...
指定proxy
>>> import urllib.request
>>> proxies = {'http': 'http://proxy.example.com:8080/'}
>>> opener = urllib.request.FancyURLopener(proxies)
>>> with opener.open("http://www.python.org") as f:
... f.read().decode('utf-8')
...
不使用proxy, 覆盖环境变量的proxy
>>> import urllib.request
>>> opener = urllib.request.FancyURLopener({})
>>> with opener.open("http://www.python.org/") as f:
... f.read().decode('utf-8')
...
python2.X中的httplib被重命名为 http.client
使用 2to3 工具转换源码时, 会自动处理这几个库的导入
** 总的来说, 使用python3, 记住只有urllib, 想要更简洁好用就用requests, 但不够通用 **
参考: http://www.hacksparrow.com/python-difference-between-urllib-and-urllib2.html
http://blog.csdn.net/lxlzhn/article/details/10474281
http://www.cnblogs.com/wly923/archive/2013/05/07/3057122.html
http://stackoverflow.com/questions/2018026/should-i-use-urllib-urllib2-or-requests
http://stackoverflow.com/questions/3305250/python-urllib-vs-httplib
http://hustcalm.me/blog/2013/11/14/httplib-httplib2-urllib-urllib2-whats-the-difference/
python中 urllib, urllib2, httplib, httplib2 几个库的区别的更多相关文章
- python中urllib, urllib2,urllib3, httplib,httplib2, request的区别
permike原文python中urllib, urllib2,urllib3, httplib,httplib2, request的区别 若只使用python3.X, 下面可以不看了, 记住有个ur ...
- [转]Python中urllib与urllib2的区别与联系
引用文章1:http://my.oschina.net/u/558071/blog/144792 引用文章2:http://zhuoqiang.me/python-urllib2-usage.html ...
- Python中内置数据类型list,tuple,dict,set的区别和用法
Python中内置数据类型list,tuple,dict,set的区别和用法 Python语言简洁明了,可以用较少的代码实现同样的功能.这其中Python的四个内置数据类型功不可没,他们即是list, ...
- Python中第三方的用于解析HTML的库:BeautifulSoup
背景 在Python去写爬虫,网页解析等过程中,比如: 如何用Python,C#等语言去实现抓取静态网页+抓取动态网页+模拟登陆网站 常常需要涉及到HTML等网页的解析. 当然,对于简单的HTML中内 ...
- Python中列表,元组,字典,集合的区别
参考文档https://blog.csdn.net/Yeoman92/article/details/56289287 理解Python中列表,元组,字典,集合的区别 列表,元组,字典,集合的区别是p ...
- 人生苦短之Python的urllib urllib2 requests
在Python中涉及到URL请求相关的操作涉及到模块有urllib,urllib2,requests,其中urllib和urllib2是Python自带的HTTP访问标准库,requsets是第三方库 ...
- Python中的xxx+=xxx和xxx=xxx+xxx一些区别及执行过程
预知小知识: Python中的变量与其他语言稍有差异,如a = 10并不是直接在内存中创建一个变量a其值为10,而是在内存中创建一个a这个a指向这个10,在Python中所有牵扯到等号的均不是值赋值, ...
- Python中read()、readline()和readlines()三者间的区别和用法
2019-01-15 10:48:43 前言 众所周知在python中读取文件常用的三种方法:read(),readline(),readlines(),今天看项目是又忘记他们的区别了.以前看书的时候 ...
- Python中的None与Null(空字符)的区别
参考自 Python中的None与空字符(NULL)的区别 - CSDN博客 http://blog.csdn.net/crisschan/article/details/70312764 首先了解p ...
随机推荐
- alex 推荐的书
这两本书不错, 追风筝的人<白鹿原>~~~反天不错~~~可以看下.14:27:22AndyZhang 2018-1-29 14:27:22 改变人的东西 读书.看电影.旅行.经历各种事 ...
- html-body相关标签
一 字体标签 字体标签包含:h1~h6.<font>.<u>.<b>.<strong><em>.<sup>.<sub& ...
- [解读REST] 0.REST 相关参考资料
Web之父 Tim Berners Lee :https://en.wikipedia.org/wiki/Tim_Berners-Lee 世界上诞生的第一个网站:http://info.cern.ch ...
- C# 数组 之间转换
List<string> strLen = new List<string>(); if (!string.IsNullOrEmpty(group_id) ...
- GBDT 与 XGBoost
GBDT & XGBoost ### 回归树 单棵回归树可以表示成如下的数学形式 \[ f(x) = \sum_j^Tw_j\mathbf{I}(x\in R_j) \] 其中\(T\)为叶节 ...
- [Err] 1022 - Can't write; duplicate key in table '#sql-1500_26'
今天用powerdesigner修改了一些外键关系,有两个外键的名字取一样的,忘记改了.然后在用navicat运行sql文件时,报出[Err] 1022 - Can't write; dupl ...
- 飞行员配对方案问题(匈牙利算法+sort)
洛谷传送门 匈牙利算法+sort 没什么好说的. ——代码 #include <cstdio> #include <cstring> #include <algorith ...
- python - opencv 的一些小技巧备忘
python - opencv 的一些小技巧备忘 使用python-opencv来处理图像时,可以像matlab一样,将一幅图像看成一个矩阵,进行矢量操作,以加快代码运行速度. 下面记录几个常用的操作 ...
- Ubuntu12.04 64bit版本下载Android源码完整教程
首先去官网http://source.android.com/source/initializing.html可以看到完整的安装教程.不过一般情况下,按照这个教程是无法一步到位的,因为中途肯定会遇到很 ...
- java Logger 的使用与配置
原文来自:http://blog.csdn.net/nash603/article/details/6749914 Logger所对应的属性文件在安装jdk目录下的jre/lib/logging.pr ...