Python基本庫使用(二)
解析鏈接
urlparse()
urllib內置了parse,parse里面又有urlparse解析url,如下:
from urllib.parse import urlparse
result = urlparse('http://pro.kaikeba.com/course/java/?ss=topj')
print(type(result), result)
# scheme 協(xié)議 netloc 域名 path路徑 params參數(shù)(分號后面的參數(shù)) query查詢條件 fragment錨點后面的東西
urlparse還有其他的參數(shù)urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True),假如urlstring有帶協(xié)議頭則取url的,沒有則取我們的第二個參數(shù);
result還是一個元組,可以通過索引來獲取urlparse解析出來的參數(shù);
allow_fragments:即是否忽略fragment。如果它被設置為 False,F(xiàn)ragment部分就會被忽略, 它會被解析為 path、parameters 或者query的一部分,而 fragment 部分為空。
urlunparse()
對立于樓上的方法,需要傳六個參數(shù)
from urllib.parse import urlunparse
data =['http','www.baidu.com','index.html','user','a=6','comment']
print(urlunparse(data))
# http://www.baidu.com/index.html;user?a=6#comment
urlsplit()
from urllib.parse import urlsplit
data ='http://www.baidu.com/index.html;user?a=6#comment'
print(urlsplit(data).scheme,urlsplit(data)[0])
# SplitResult(scheme='http', netloc='www.baidu.com', path='/index.html;user', query='a=6', fragment='comment')
# 元組的方式,可用key的方式獲取,也可以用索引的方式
urlunsplit()
必傳為五個參數(shù)
from urllib.parse import urlunsplit
data =['http','www.baidu.com','index.html','user','a=6','comment']
print(urlunsplit(data));
未完待續(xù)。。。