urlliburllib2都是接受URL请求的相关模块,但是提供了不同的功能。

urllib提供urlencode方法用来GET查询字符串的产生,而urllib2没有。

urllib:

网页基础:

 
  1. import urllib

  2. #打开51cto

  3. cto = urllib.urlopen('http://www.51cto.com')

  4. #打开本地文件:cto = urllib.urlopen(url='file:/root/python/ulib')

  5. #打开ftp:cto = = urllib.urlopen(url='ftp://用户名:密码@ftp地址/')

  6. #读取51cto首页的代码

  7. print cto.read()

  8. #获取远程服务器返回的头信息,跟curl -I www,51cto.com差不多

  9. print cto.info()

  10. #返回http状态码,200表示成功,404表示网址未找到

  11. print cto.getcode()

  12. #返回请求的URL

  13. print cto.geturl()

  14. #运行结果

  15. [root@localhost python]#python ctourl

  16. 。。。。。。。省略cto.read()函数,输出太多啦。。。。。

  17. Server: Tengine #cto.info()返回信息

  18. Date: Wed, 27 Feb 201315:05:46 GMT

  19. Content-Type: text/html

  20. Connection: close

  21. Vary: Accept-Encoding

  22. Load-Balancing: web48

  23. 200#cto.getcode()返回信息

  24. http://www.51cto.com #cto.geturl()返回信息

  25. #urlopen返回的是一个类文件对象,而这个对象的使用方法和文件对象的

  26. #使用方法完全一样。

字符的编码和解码:

 
  1. import urllib,os

  2. #对字符串进行编码

  3. stra = urllib.quote('this is python')

  4. print stra

  5. #对字符串进行解码

  6. print urllib.unquote(stra)

  7. #这个方法用‘+’代替了%20 和urllib.quote类似,

  8. strb = urllib.quote_plus('this is python')

  9. print strb

  10. #解码

  11. print urllib.unquote_plus(strb)

  12. dicta = {

    'name':'zeping','passwd':'123456'}

  13. #urlencode将字典转换成url参数

  14. print urllib.urlencode(dicta)

  15. #将本地路径转换成url路径

  16. filename = urllib.pathname2url('/python/test.py')

  17. print filename

  18. #将url路径转换成本地路径

  19. print urllib.url2pathname(filename)

  20. ##########运行结果##########

  21. [root@localhost python]# python quote

  22. this%20is%20python

  23. this is python

  24. this+is+python

  25. this is python

  26. passwd=123456&name=zeping

  27. /python/test.py

  28. /python/test.py

urllib.urlretrieve():下载

 
  1. import urllib

  2. def Schedule(a,b,c):

  3. '''''

  4. a:已经下载的数据块

  5. b:数据块的大小

  6. c:远程文件的大小

  7. '''

  8. per = 100.0 * a * b / c

  9. if per > 100 :

  10. per = 100

  11. print'%.2f%%' % per

  12. #这里以下载缓存插件为例

  13. url = 'http://fastlnmp.googlecode.com/files/eaccelerator-0.9.6.tar.bz2'

  14. #获取文件名,这里是下载到当前目录下,若果要下载到别的目录必

  15. #须输入绝对路径和文件名字:/root/tools/eaccelerator-0.9.6.tar.bz2

  16. local = url.split('/')[-1]

  17. urllib.urlretrieve(url,local,Schedule)

  18. #########运行结果##########

  19. [root@localhost urllib]# python down

  20. 0.00%

  21. 7.74%

  22. 15.48%

  23. 23.22%

  24. 30.96%

  25. 38.70%

  26. 46.44%

  27. 54.18%

  28. 61.92%

  29. 69.66%

  30. 77.40%

  31. 85.15%

  32. 92.89%

  33. 100.00%

  34. [root@localhost urllib]# ls

  35. down eaccelerator-0.9.6.tar.bz2 ulib2

urllib2:

urllib2可以接受一个Request类的实例来设置URL请求的headers,urllib仅可以接受URL。

本文出自 “” 博客,请务必保留此出处