python/urllib/ target=_blank class=infotextkey>python urllib模块与python urllib2模块用法
urllib 和urllib2都是接受URL请求的相关模块,但是提供了不同的功能。
urllib提供urlencode方法用来GET查询字符串的产生,而urllib2没有。
1、python urllib模块
 
复制代码 代码示例:
import urllib 
#打开jbxue 
cto = urllib.urlopen('http://www.jb200.com') 
#打开本地文件:cto = urllib.urlopen(url='file:/root/python/ulib')
#打开ftp:cto = = urllib.urlopen(url='ftp://用户名:密码@ftp地址/')
#读取jbxue首页的代码 
print cto.read() 
#获取远程
服务器返回的头信息,跟curl -I www,jb200.com差不多 
print cto.info() 
#返回http状态码,200表示成功,404表示网址未找到 
print cto.getcode() 
#返回请求的URL 
print cto.geturl() 
#运行结果 
[root@localhost python]#python ctourl 
省略cto.read()函数,输出太多... 
Server: Tengine  #cto.info()返回信息 
Date: Wed, 27 Feb 2013 15:05:46 GMT 
Content-Type: text/html 
Connection: close 
Vary: Accept-Encoding 
Load-Balancing: web48 
 
 
200   #cto.getcode()返回信息 
http://www.jb200.com   #cto.geturl()返回信息 
#urlopen返回的是一个类文件对象,而这个对象的使用方法和文件对象的 
#使用方法完全一样。
2、字符编码和解码:
 
复制代码 代码示例:
import urllib,os 
#对字符串进行编码 
stra = urllib.quote('this is python') 
print stra 
#对字符串进行解码 
print urllib.unquote(stra) 
#这个方法用‘+’代替了%20 和urllib.quote类似, 
strb = urllib.quote_plus('this is python') 
print strb 
#解码 
print urllib.unquote_plus(strb) 
 
dicta = {'name':'zeping','passwd':'123456'} 
#urlencode将字典转换成url参数 
print urllib.urlencode(dicta) 
 
#将本地路径转换成url路径 
filename = urllib.pathname2url('/python/test.py') 
print filename 
#将url路径转换成本地路径 
print urllib.url2pathname(filename) 
 
运行结果: 
 
[root@localhost python]# python quote 
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): 
    ''''' 
    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' 
#获取文件名,下载到当前目录下,若果要下载到别的目录必 
#须输入
绝对路径和文件名字:/root/tools/eaccelerator-0.9.6.tar.bz2 
local = url.split('/')[-1] 
urllib.urlretrieve(url,local,Schedule)
运行结果: 
 
[root@localhost urllib]# python down 
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]# ls 
down  eaccelerator-0.9.6.tar.bz2  ulib2
urllib2:
urllib2可以接受一个Request类的实例来设置URL请求的headers,urllib仅可以接受URL。
有关python中urllib模块与urllib2模块的用法,请点这里查看更多内容。