转载

摘要: 只用 python3, 只用 urllib

若只使用python3.X, 下面可以不看了, 记住有个urllib的库就行了

python2.X 有这些库名可用: urlliburllib2, urllib3, httplib, httplib2, requests

python3.X 有这些库名可用: urllib, urllib3, httplib2, requests

两者都有的urllib3和requests, 它们不是标准库. urllib3 提供线程安全连接池和文件post支持,与urllib及urllib2的关系不大. requests 自称HTTP for Humans, 使用更简洁方便

对于python2.X:

urllib和urllib2的主要区别:

  1. urllib2可以接受Request对象为URL设置头信息,修改用户代理,设置cookie等, urllib只能接受一个普通的URL.
  2. 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.codefrom.com/paper/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3urllib%E3%80%81urllib2%E5%8F%8Arequests

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 几个库的区别的更多相关文章

  1. python中urllib, urllib2,urllib3, httplib,httplib2, request的区别

    permike原文python中urllib, urllib2,urllib3, httplib,httplib2, request的区别 若只使用python3.X, 下面可以不看了, 记住有个ur ...

  2. [转]Python中urllib与urllib2的区别与联系

    引用文章1:http://my.oschina.net/u/558071/blog/144792 引用文章2:http://zhuoqiang.me/python-urllib2-usage.html ...

  3. Python中内置数据类型list,tuple,dict,set的区别和用法

    Python中内置数据类型list,tuple,dict,set的区别和用法 Python语言简洁明了,可以用较少的代码实现同样的功能.这其中Python的四个内置数据类型功不可没,他们即是list, ...

  4. Python中第三方的用于解析HTML的库:BeautifulSoup

    背景 在Python去写爬虫,网页解析等过程中,比如: 如何用Python,C#等语言去实现抓取静态网页+抓取动态网页+模拟登陆网站 常常需要涉及到HTML等网页的解析. 当然,对于简单的HTML中内 ...

  5. Python中列表,元组,字典,集合的区别

    参考文档https://blog.csdn.net/Yeoman92/article/details/56289287 理解Python中列表,元组,字典,集合的区别 列表,元组,字典,集合的区别是p ...

  6. 人生苦短之Python的urllib urllib2 requests

    在Python中涉及到URL请求相关的操作涉及到模块有urllib,urllib2,requests,其中urllib和urllib2是Python自带的HTTP访问标准库,requsets是第三方库 ...

  7. Python中的xxx+=xxx和xxx=xxx+xxx一些区别及执行过程

    预知小知识: Python中的变量与其他语言稍有差异,如a = 10并不是直接在内存中创建一个变量a其值为10,而是在内存中创建一个a这个a指向这个10,在Python中所有牵扯到等号的均不是值赋值, ...

  8. Python中read()、readline()和readlines()三者间的区别和用法

    2019-01-15 10:48:43 前言 众所周知在python中读取文件常用的三种方法:read(),readline(),readlines(),今天看项目是又忘记他们的区别了.以前看书的时候 ...

  9. Python中的None与Null(空字符)的区别

    参考自 Python中的None与空字符(NULL)的区别 - CSDN博客 http://blog.csdn.net/crisschan/article/details/70312764 首先了解p ...

随机推荐

  1. python学习--同目录下调用 (*.py)及不同目录下调(*.py)

    注:__init__.py 内容为空 1. 同目录下调用 (Contract_Statelog.py)  如图: temp1.py 调用 Contract_Statelog.py中的方法 2. 不同目 ...

  2. 理解 PHP output buffer

    在需要使用输出缓存区的时候,一般会在代码中加上ob_start()这个函数. 这是因为php.ini中output_buffering设置为off时,则缓存区处于关闭状态,需要用ob_start()打 ...

  3. isinstance 和 type 的区别

    class A: pass class B(A): pass isinstance(A(), A) # returns True type(A()) == A # returns True isins ...

  4. 高并发下的HashMap,ConcurrentHashMap

    参照: http://mp.weixin.qq.com/s/dzNq50zBQ4iDrOAhM4a70A http://mp.weixin.qq.com/s/1yWSfdz0j-PprGkDgOomh ...

  5. python多进程(multiprocessing)

    最近有个小课题,需要用到双进程,翻了些资料,还算圆满完成任务.记录一下~ 1.简单地双进程启动 同时的调用print1()和print2()两个打印函数,代码如下: #/usr/bin/python ...

  6. Github与Eclipse连接(方法2成功:Pleiades)

    2018-3-7 第1次尝试 主要参考这位大神的笔记:http://blog.csdn.net/zhangdaiscott/article/details/16939165 方法非常简单,从官网htt ...

  7. 学习的一些mybatis

    MyBatis入门基础(一) 阅读目录 一:对原生态JDBC问题的总结 二:MyBatis框架 三:mybatis入门程序 四:mybatis和Hibernate的本质区别与应用场景 五:小结 回到顶 ...

  8. linux maven安装(三)

    1.下载maven http://maven.apache.org/download.cgi 我下载的是:apache-maven-3.3.9-bin.tar.gz 解压:tar -zxvf apac ...

  9. bzoj 4009 接水果 整体二分

    Description 先给出一些盘子, 用路径x-y表示, 有权值 再有Q个询问, 表示水果, 用路径x-y表示 如果盘子是水果的子路径, 可以接住 对于每个水果, 输出可以接住它的盘子的第k小权 ...

  10. 【POJ3352】Road Construction(边双联通分量)

    题意:给一个无向图,问最少添加多少条边后能使整个图变成双连通分量. 思路:双连通分量缩点,缩点后给度为1的分量两两之间连边,要连(ans+1) div 2条 low[u]即为u所在的分量编号,flag ...