urlparse---分解URL
解析
作用:将URL分解为其组成部分。urlparse()函数返回一个对象,相当于包含6个元素的tuple.
>>>from urlparse import urlparse
>>> url = "http://netloc/path;param?query=arg#frag"
>>> parsed = urlparse(url)#分别获得机制、网络位置、路径、路径段参数、查询以及分片。
>>> print parsed
ParseResult(scheme='http', netloc='netloc', path='/path', params='param', query='query=arg', fragment='frag')
>>> print parsed.hostname#除了可以基于索引的访问以外,还支持通过命名属性访问URL的各部分。属性API不仅易于编程,还允许访问tuple API未提供的很多值。
netloc
>>> print parsed.port
None
urlsplit()函数可以替代urlparse()函数,但是表现稍有不同。因为它不会从URL中分解参数。因为不分解参数,tuple API会显示五个元素而不是6个。没有params属性。
>>> from urlparse import urlsplit
>>> parsed = urlsplit(url)
>>> print parsed
SplitResult(scheme='http', netloc='netloc', path='/path;param', query='query=arg', fragment='frag')
要想从一个URL分离出片段标志符,如从一个URL查找基页面名,可以使用urldegrag()。返回值是一个元组,包括URL和片段。>>> from urlparse import urldefrag
>>> url,fragment = urldefrag(url)
>>> print url
http://netloc/path;param?query=arg
>>> print fragment
frag
可以把分解的URL各部分重新组装在一起,形成一个串。解析的URL对象有一个geturl()方法。它只适用于urlparse()和urlsplit()返回的对象。
>>> type(parsed)
<class 'urlparse.SplitResult'>
>>> from urlparse import urlunparsed
>>> print urlunparse(parsed)
http://netloc/path;param?query=arg
如果输入的 URL包含多余的部分,重新构造的URL会删除多余的部分。连接
除了解析URL之外,urlparse还包含一个urljoin()方法,可以由相对片段构造绝对URL。
>>> from urlparse import urljoin
>>> print urljoin("http://www.example.com/path/file.html","anotherfile.html")
http://www.example.com/path/anotherfile.html
>>> print urljoin("http://www.example.com/path/file.html","../anotherfile.html")
http://www.example.com/anotherfile.html
在这个例子中,计算第二个时要考虑路径的相对部分。非相对路径的处理与os.path.join()处理方式相同。
>>> print urljoin("http://www.example.com/path/file.html","/subpath/anotherfile.html")
http://www.example.com/subpath/anotherfile.html
>>> print urljoin("http://www.example.com/path/file.html","subpath/anotherfile.html")
http://www.example.com/path/subpath/anotherfile.html
如果连接到URL的路径以一个斜线开头,这会将路径重置为顶级路径,否则,将追加的当前路径的末尾。