urllib 和urllib2都是接受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 2013 15:05:46 GMT 
  19. Content-Type: text/html 
  20. Connection: close 
  21. Vary: Accept-Encoding 
  22. Load-Balancing: web48 
  23.  
  24. 200              #cto.getcode()返回信息 
  25. http://www.51cto.com   #cto.geturl()返回信息 
  26. #urlopen返回的是一个类文件对象,而这个对象的使用方法和文件对象的 
  27. #使用方法完全一样。 

 字符的编码和解码:

 

  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.  
  13. dicta = {'name':'zeping','passwd':'123456'
  14. #urlencode将字典转换成url参数 
  15. print urllib.urlencode(dicta) 
  16.  
  17. #将本地路径转换成url路径 
  18. filename = urllib.pathname2url('/python/test.py'
  19. print filename 
  20. #将url路径转换成本地路径 
  21. print urllib.url2pathname(filename) 
  22.  
  23. ##########运行结果########## 
  24. [root@localhost python]# python quote 
  25. this%20is%20python 
  26. this is python 
  27. this+is+python 
  28. this is python 
  29. passwd=123456&name=zeping 
  30. /python/test.py 
  31. /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. #这里以下载缓存插件为例 
  14. url = 'http://fastlnmp.googlecode.com/files/eaccelerator-0.9.6.tar.bz2' 
  15. #获取文件名,这里是下载到当前目录下,若果要下载到别的目录必 
  16. #须输入绝对路径和文件名字:/root/tools/eaccelerator-0.9.6.tar.bz2 
  17. local = url.split('/')[-1
  18. urllib.urlretrieve(url,local,Schedule) 
  19. #########运行结果########## 
  20. [root@localhost urllib]# python down 
  21. 0.00
  22. 7.74
  23. 15.48
  24. 23.22
  25. 30.96
  26. 38.70
  27. 46.44
  28. 54.18
  29. 61.92
  30. 69.66
  31. 77.40
  32. 85.15
  33. 92.89
  34. 100.00
  35. [root@localhost urllib]# ls 
  36. down  eaccelerator-0.9.6.tar.bz2  ulib2 

urllib2:

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