首页 > 编程笔记

Python urllib库使用详解

urllib 是 Python 的标准库模块,它可以处理客户端的请求和服务器端的响应,还可以解析 URL 地址。常用的模块为 request 和 parse。

request 模块是使用 socket 读取网络数据的接口,支持 HTTP、FTP 及 gopher 等连接。

1. request.urlopen()

要读取一个网页文件,可以使用 urlopen() 方法。其语法如下:

urllib.request.urlopen(url [, data])

其中,参数 url 是一个 URL 字符串;参数 data 用来指定一个 GET 请求。

urlopen() 方法返回一个 stream 对象(流式对选哪个),可以使用 file 对象的方法来操作此 stream 对象。

下面的示例是读取 http://www.baidu.com 的网页。
>>>import urllib
>>>from urllib import request
>>>htmlpage = urllib.request.urlopen ("http://www.baidu. com")
>>>htmlpage.read ()
urlopen() 方法返回的 stream 对象有两个属性,即 url 与 headers。url 属性是设置的 URL 字符串值;headers 属性是一个字典集,包含网页的表头。

下面的示例是显示刚才打开的 htmlpage 对象的 url 属性:
 >>>htmlpage.url
'http://www.baidu.com'
下面的示例是显示刚才打开的 htmlpage 对象的 headers 属性:
>>>for key, value in htmlpage.headers .items () :
print (key, "= ",value)
Server = Apache-Coyote/1.1
Cache-Control
Content-Type = text/html ; charset=UTF-8
Content-Encoding = gzip
Content-Length = 1284
Set-Cookie = ucloud=1; domain=. baidu . com;path=/ ;max-age=300
Pragma = no-cache

2. urllib.parse解析模块

parse 模块解析 URL 字符串并返回一个元组:(addressing scheme, netword location, path,parameters, query, fragment identifier)。parse 模块可以将 URL 分解成数个部分,并能组合回来,还可以将相对地址转换为绝对地址。

parse 模块的方法列表如下:

1) urlparse(urlstring [, default_scheme [, allow_fragments]])

将一个 URL 字符串分解成 6 个元素,即 addressing scheme、netword location、path、parameters、query、fragment identifier。若设置 default_scheme 数,则指定 addressing scheme;若设置参数 allow_fragments 为 0,则不允许 fragment identifier。例如:
>>> import urllib.parse
>>>url = "http: //home.netscape.com/ assist/extensions.html #topic1?x= 7&y= 2"
>>>urllib.parse. urlparse (url)
( 'http', 'home.netscape.com','/assist/extensions.html','','','topicl?x=7&y=2')
    ParseResult (scheme='http',netloc='home.netscape.com' ,
path='/assist/extensions.html' , params='', query='', fragment='topic1?x= 7&y= 2')

2) urlunparse(tuple)

使用 tuple 创建一个 URL 字符串。例如:
>>>import urllib. parse
>>>t = ("http", "www.python.org", "/News .html",'','','")
>>>urllib.parse.urlunparse (t)
'http://www.python.org/News.html '

3) urljoin(base, url [, allow_fragments])

使用 base 与 url 创建一个绝对 URL 地址。例如:
>>> import urllib.parse
>>>urllib.parse.urljoin ("http://www.python.org", "/News.html")
'http://www.python.org/News.html '

3. urllib库的其他方法

urllib 模块的方法列表如下:

1) urlretrieve(url [, filename [, reporthook [, data]]])

将一个网络对象 url 复制到本机文件 filename上。其中,参数 reporthook 是一个 hook 函数,在网络连接完成时,会调用此 hook 函数一次,在每读取一个区块后,也会调用此 hook 函数一次;参数 data 必须是 application/x-www-form-urlencoded 格式。例如:
>>>import urllib.request
>>>urllib.request.urlretrieve("http://www.python.org", "copy.html")
('copy.html', <http.client.HTTPMessage object at 0x02DE28B0>)

2) urlcleanup()

清除 urlretrieve() 方法所使用的高速缓存。

3) quote(string [, safe])

将字符串 string 中的特殊字符用 %xx 码取代。参数 safe 设置要引用的额外字符。例如:
>>>import urllib.request
>>>urllib.request.quote("This & that are all books\n")
'This%20%26%20that%20are%20all%20books%0A'

4) quote_plus(string [, safe])

与 quote() 方法相同,但是字符串中的空白将以加号(+)取代。

5) unquote(string)

返回原始字符串。例如:
>>>import urllib.request
>>>urllib.request.unquote("This%20%26%20that%20are%20all%20books%0A")
'This & that are all books\n'
下面的示例将读取 http://www.python.org 主页的内容。
>>>import urllib.request
>>>response = urllib.request.urlopen("http://www.python.org")
>>>html = response.read()
也可以使用以下代码实现上述功能:
>>>import urllib.request
>>>req = urllib.request.Request("http://www.python.org")
>>>response = urllib.request.urlopen(req)
>>>the_page = response.read()
下面的示例将 http://www.python.org 网页存储到本机的 url_test.html 文件中。
#使用urlopen方法抓取网页文件
import urllib. request
#打开网页文件
htmlhandler = urllib.request.urlopen ("http://www.python.org")
#在本机上创建一个新文件
file = open("D: \\python\\ch16\\url_test.html", "wb")
#将网页文件存储到本机文件上,每次读取512个字节
while 1 :
    data = htmlhandler. read(512)
    if not data:
        break
    file.write(data)
#关闭本机文件
file.close ()
保存并运行程序,即可将 http://www.python.org 网页存储到本机的 url_test.html 文件中。

优秀文章