您的位置:首页 > 编程语言 > Python开发

Python笔记:urllib模块

2015-06-30 23:48 591 查看

urllib模块中的方法

1.urllib.urlopen(url[,data[,proxies]])

打开一个url的方法,返回一个文件对象,然后可以进行类似文件对象的操作。本例试着打开google

>>> import urllib
>>> f = urllib.urlopen('http://www.google.com.hk/')
>>> firstLine = f.readline()   #读取html页面的第一行
>>> firstLine
'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"><head><meta content="/images/google_favicon_128.png" itemprop="image"><title>Google</title><script>(function(){\n'


urlopen返回对象提供方法:

- read() , readline() ,readlines() , fileno() , close() :这些方法的使用方式与文件对象完全一样

- info():返回一个httplib.HTTPMessage对象,表示远程服务器返回的头信息

- getcode():返回Http状态码。如果是http请求,200请求成功完成;404网址未找到

- geturl():返回请求的url

2.urllib.urlretrieve(url[,filename[,reporthook[,data]]])

urlretrieve方法将url定位到的html文件下载到你本地的硬盘中。如果不指定filename,则会存为临时文件。

urlretrieve()返回一个二元组(filename,mine_hdrs)

临时存放:

>>> filename = urllib.urlretrieve('http://www.google.com.hk/')
>>> type(filename)
<type 'tuple'>
>>> filename[0]
'/tmp/tmp8eVLjq'
>>> filename[1]
<httplib.HTTPMessage instance at 0xb6a363ec>


存为本地文件:

>>> filename = urllib.urlretrieve('http://www.google.com.hk/',filename='/home/dzhwen/python文件/Homework/urllib/google.html')
>>> type(filename)
<type 'tuple'>
>>> filename[0]
'/home/dzhwen/python\xe6\x96\x87\xe4\xbb\xb6/Homework/urllib/google.html'
>>> filename[1]
<httplib.HTTPMessage instance at 0xb6e2c38c>


3.urllib.urlcleanup()

清除由于urllib.urlretrieve()所产生的缓存

4.urllib.quote(url)和urllib.quote_plus(url)

将url数据获取之后,并将其编码,从而适用与URL字符串中,使其能被打印和被web服务器接受。quote中'/'斜杠默认不替换,而quote_plus是用空格替换掉quote得斜杠,再将结果的空格用'+'替换,具体可查看urllib源码:

always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
'abcdefghijklmnopqrstuvwxyz'
'0123456789' '_.-')
_safe_map = {}
for i, c in zip(xrange(256), str(bytearray(xrange(256)))):
_safe_map[c] = c if (i < 128 and c in always_safe) else '%{:02X}'.format(i)
_safe_quoters = {}

def quote(s, safe='/'):
if not s:
if s is None:
raise TypeError('None object cannot be quoted')
return s
cachekey = (safe, always_safe)
try:
(quoter, safe) = _safe_quoters[cachekey]
except KeyError:
safe_map = _safe_map.copy()
safe_map.update([(c, c) for c in safe])
quoter = safe_map.__getitem__
safe = always_safe + safe
_safe_quoters[cachekey] = (quoter, safe)
if not s.rstrip(safe):
return s
return ''.join(map(quoter, s))

def quote_plus(s, safe=''):
if ' ' in s:
s = quote(s, safe + ' ')
return s.replace(' ', '+')
return quote(s, safe)


>>> urllib.quote('http://www.baidu.com')
'http%3A//www.baidu.com'
>>> urllib.quote_plus('http://www.baidu.com')
'http%3A%2F%2Fwww.baidu.com'


5.urllib.unquote(url)和urllib.unquote_plus(url)

与4的函数相反。

6.urllib.urlencode(query)

将URL中的键值对以连接符&划分

这里可以与urlopen结合以实现post方法和get方法:

GET方法:

>>> import urllib
>>> params=urllib.urlencode({'spam':1,'eggs':2,'bacon':0})
>>> params
'eggs=2&bacon=0&spam=1'
>>> f=urllib.urlopen("http://python.org/query?%s" % params)
>>> print f.read()


POST方法:

>>> import urllib
>>> parmas = urllib.urlencode({'spam':1,'eggs':2,'bacon':0})
>>> f=urllib.urlopen("http://python.org/query",parmas)
>>> f.read()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: