转载

摘要: 只用 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官方文档的几个例子

  1. 使用带参数的GET方法取回URL
  2. >>> import urllib
  3. >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
  4. >>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params)
  5. >>> print f.read()
  6. 使用POST方法
  7. >>> import urllib
  8. >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
  9. >>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
  10. >>> print f.read()
  11. 使用HTTP代理,自动跟踪重定向
  12. >>> import urllib
  13. >>> proxies = {'http': 'http://proxy.example.com:8080/'}
  14. >>> opener = urllib.FancyURLopener(proxies)
  15. >>> f = opener.open("http://www.python.org")
  16. >>> f.read()
  17. 不使用代理
  18. >>> import urllib
  19. >>> opener = urllib.FancyURLopener({})
  20. >>> f = opener.open("http://www.python.org/")
  21. >>> f.read()

urllib2的几个官方文档的例子:

  1. GET一个URL
  2. >>> import urllib2
  3. >>> f = urllib2.urlopen('http://www.python.org/')
  4. >>> print f.read()
  5. 使用基本的HTTP认证
  6. import urllib2
  7. auth_handler = urllib2.HTTPBasicAuthHandler()
  8. auth_handler.add_password(realm='PDQ Application',
  9. uri='https://mahler:8092/site-updates.py',
  10. user='klem',
  11. passwd='kadidd!ehopper')
  12. opener = urllib2.build_opener(auth_handler)
  13. urllib2.install_opener(opener)
  14. urllib2.urlopen('http://www.example.com/login.html')
  15. build_opener() 默认提供很多处理程序, 包括代理处理程序, 代理默认会被设置为环境变量所提供的.
  16. 一个使用代理的例子
  17. proxy_handler = urllib2.ProxyHandler({'http': 'http://www.example.com:3128/'})
  18. proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
  19. proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
  20. opener = urllib2.build_opener(proxy_handler, proxy_auth_handler)
  21. opener.open('http://www.example.com/login.html')
  22. 添加HTTP请求头部
  23. import urllib2
  24. req = urllib2.Request('http://www.example.com/')
  25. req.add_header('Referer', 'http://www.python.org/')
  26. r = urllib2.urlopen(req)
  27. 更改User-agent
  28. import urllib2
  29. opener = urllib2.build_opener()
  30. opener.addheaders = [('User-agent', 'Mozilla/5.0')]
  31. opener.open('http://www.example.com/')

** httplib 和 httplib2 ** httplib 是http客户端协议的实现,通常不直接使用, urllib是以httplib为基础 httplib2 是第三方库, 比httplib有更多特性

对于python3.X:

这里urllib成了一个包, 此包分成了几个模块,

  1. urllib.request 用于打开和读取URL,
  2. urllib.error 用于处理前面request引起的异常,
  3. urllib.parse 用于解析URL,
  4. urllib.robotparser用于解析robots.txt文件

python2.X 中的 urllib.urlopen()被废弃, urllib2.urlopen()相当于python3.X中的urllib.request.urlopen()

几个官方例子:

  1. GET一个URL
  2. >>> import urllib.request
  3. >>> with urllib.request.urlopen('http://www.python.org/') as f:
  4. ... print(f.read(300))
  5. PUT一个请求
  6. import urllib.request
  7. DATA=b'some data'
  8. req = urllib.request.Request(url='http://localhost:8080', data=DATA,method='PUT')
  9. with urllib.request.urlopen(req) as f:
  10. pass
  11. print(f.status)
  12. print(f.reason)
  13. 基本的HTTP认证
  14. import urllib.request
  15. auth_handler = urllib.request.HTTPBasicAuthHandler()
  16. auth_handler.add_password(realm='PDQ Application',
  17. uri='https://mahler:8092/site-updates.py',
  18. user='klem',
  19. passwd='kadidd!ehopper')
  20. opener = urllib.request.build_opener(auth_handler)
  21. urllib.request.install_opener(opener)
  22. urllib.request.urlopen('http://www.example.com/login.html')
  23. 使用proxy
  24. proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'})
  25. proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()
  26. proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
  27. opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)
  28. opener.open('http://www.example.com/login.html')
  29. 添加头部
  30. import urllib.request
  31. req = urllib.request.Request('http://www.example.com/')
  32. req.add_header('Referer', 'http://www.python.org/')
  33. r = urllib.request.urlopen(req)
  34. 更改User-agent
  35. import urllib.request
  36. opener = urllib.request.build_opener()
  37. opener.addheaders = [('User-agent', 'Mozilla/5.0')]
  38. opener.open('http://www.example.com/')
  39. 使用GET时设置URL的参数
  40. >>> import urllib.request
  41. >>> import urllib.parse
  42. >>> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
  43. >>> url = "http://www.musi-cal.com/cgi-bin/query?%s" % params
  44. >>> with urllib.request.urlopen(url) as f:
  45. ... print(f.read().decode('utf-8'))
  46. ...
  47. 使用POST时设置参数
  48. >>> import urllib.request
  49. >>> import urllib.parse
  50. >>> data = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
  51. >>> data = data.encode('ascii')
  52. >>> with urllib.request.urlopen("http://requestb.in/xrbl82xr", data) as f:
  53. ... print(f.read().decode('utf-8'))
  54. ...
  55. 指定proxy
  56. >>> import urllib.request
  57. >>> proxies = {'http': 'http://proxy.example.com:8080/'}
  58. >>> opener = urllib.request.FancyURLopener(proxies)
  59. >>> with opener.open("http://www.python.org") as f:
  60. ... f.read().decode('utf-8')
  61. ...
  62. 不使用proxy, 覆盖环境变量的proxy
  63. >>> import urllib.request
  64. >>> opener = urllib.request.FancyURLopener({})
  65. >>> with opener.open("http://www.python.org/") as f:
  66. ... f.read().decode('utf-8')
  67. ...

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. alex 推荐的书

     这两本书不错, 追风筝的人<白鹿原>~~~反天不错~~~可以看下.14:27:22AndyZhang 2018-1-29 14:27:22 改变人的东西  读书.看电影.旅行.经历各种事 ...

  2. html-body相关标签

    一 字体标签   字体标签包含:h1~h6.<font>.<u>.<b>.<strong><em>.<sup>.<sub& ...

  3. [解读REST] 0.REST 相关参考资料

    Web之父 Tim Berners Lee :https://en.wikipedia.org/wiki/Tim_Berners-Lee 世界上诞生的第一个网站:http://info.cern.ch ...

  4. C# 数组 之间转换

    List<string> strLen = new List<string>();            if (!string.IsNullOrEmpty(group_id) ...

  5. GBDT 与 XGBoost

    GBDT & XGBoost ### 回归树 单棵回归树可以表示成如下的数学形式 \[ f(x) = \sum_j^Tw_j\mathbf{I}(x\in R_j) \] 其中\(T\)为叶节 ...

  6. [Err] 1022 - Can't write; duplicate key in table '#sql-1500_26'

        今天用powerdesigner修改了一些外键关系,有两个外键的名字取一样的,忘记改了.然后在用navicat运行sql文件时,报出[Err] 1022 - Can't write; dupl ...

  7. 飞行员配对方案问题(匈牙利算法+sort)

    洛谷传送门 匈牙利算法+sort 没什么好说的. ——代码 #include <cstdio> #include <cstring> #include <algorith ...

  8. python - opencv 的一些小技巧备忘

    python - opencv 的一些小技巧备忘 使用python-opencv来处理图像时,可以像matlab一样,将一幅图像看成一个矩阵,进行矢量操作,以加快代码运行速度. 下面记录几个常用的操作 ...

  9. Ubuntu12.04 64bit版本下载Android源码完整教程

    首先去官网http://source.android.com/source/initializing.html可以看到完整的安装教程.不过一般情况下,按照这个教程是无法一步到位的,因为中途肯定会遇到很 ...

  10. java Logger 的使用与配置

    原文来自:http://blog.csdn.net/nash603/article/details/6749914 Logger所对应的属性文件在安装jdk目录下的jre/lib/logging.pr ...