轉自:http://zeping.blog.51cto.com/6140112/1143722html
urllib 和urllib2都是接受URL請求的相關模塊,可是提供了不一樣的功能。python
urllib提供urlencode方法用來GET查詢字符串的產生,而urllib2沒有。web
urllib:緩存
網頁基礎:服務器
- import urllib
- cto = urllib.urlopen('http://www.51cto.com')
- #打開本地文件:cto = urllib.urlopen(url='file:/root/python/ulib')
- #打開ftp:cto = = urllib.urlopen(url='ftp://用戶名:密碼@ftp地址/')
- print cto.read()
- print cto.info()
- print cto.getcode()
- print cto.geturl()
- [root@localhost python]
- 。。。。。。。省略cto.read()函數,輸出太多啦。。。。。
- Server: Tengine
- Date: Wed, 27 Feb 2013 15:05:46 GMT
- Content-Type: text/html
- Connection: close
- Vary: Accept-Encoding
- Load-Balancing: web48
-
- 200
- http://www.51cto.com
字符的編碼和解碼:curl
- import urllib,os
- stra = urllib.quote('this is python')
- print stra
- print urllib.unquote(stra)
- strb = urllib.quote_plus('this is python')
- print strb
- print urllib.unquote_plus(strb)
-
- dicta = {'name':'zeping','passwd':'123456'}
- print urllib.urlencode(dicta)
-
- filename = urllib.pathname2url('/python/test.py')
- print filename
- print urllib.url2pathname(filename)
-
- [root@localhost python]
- this%20is%20python
- this is python
- this+is+python
- this is python
- passwd=123456&name=zeping
- /python/test.py
- /python/test.py
urllib.urlretrieve():下載函數
- import urllib
- def Schedule(a,b,c):
- ''
- per = 100.0 * a * b / c
- if per > 100 :
- per = 100
- print '%.2f%%' % per
-
- url = 'http://fastlnmp.googlecode.com/files/eaccelerator-0.9.6.tar.bz2'
- local = url.split('/')[-1]
- urllib.urlretrieve(url,local,Schedule)
- [root@localhost urllib]
- 0.00%
- 7.74%
- 15.48%
- 23.22%
- 30.96%
- 38.70%
- 46.44%
- 54.18%
- 61.92%
- 69.66%
- 77.40%
- 85.15%
- 92.89%
- 100.00%
- [root@localhost urllib]
- down eaccelerator-0.9.6.tar.bz2 ulib2
urllib2:this
urllib2能夠接受一個Request類的實例來設置URL請求的headers,urllib僅能夠接受URL。google
以上轉自:http://zeping.blog.51cto.com/6140112/1143722編碼