溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python中怎么利用urlliib.parse庫解析URL

發(fā)布時間:2021-07-05 17:24:08 來源:億速云 閱讀:247 作者:Leah 欄目:編程語言

今天就跟大家聊聊有關(guān)Python中怎么利用urlliib.parse庫解析URL,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

解析url

urlparse() 函數(shù)可以將 URL 解析成 ParseResult 對象。對象中包含了六個元素,分別為:

  • 協(xié)議(scheme)

  • 域名(netloc)

  • 路徑(path)

  • 路徑參數(shù)(params)

  • 查詢參數(shù)(query)

  • 片段(fragment)

from urllib.parse import urlparse url='http://user:pwd@domain:80/path;params?query=queryarg#fragment' parsed_result=urlparse(url) print('parsed_result 包含了',len(parsed_result),'個元素')print(parsed_result)

結(jié)果為:

parsed_result 包含了 6 個元素ParseResult(scheme='http', netloc='user:pwd@domain:80', path='/path', params='params', query='query=queryarg', fragment='fragment')

ParseResult 繼承于 namedtuple,因此可以同時通過索引和命名屬性來獲取 URL 中各部分的值。

為了方便起見, ParseResult 還提供了 username、 password、 hostname、 port 對 netloc 進一步進行拆分。

print('scheme  :', parsed_result.scheme)print('netloc  :', parsed_result.netloc)print('path    :', parsed_result.path)print('params  :', parsed_result.params)print('query   :', parsed_result.query)print('fragment:', parsed_result.fragment)print('username:', parsed_result.username)print('password:', parsed_result.password)print('hostname:', parsed_result.hostname)print('port    :', parsed_result.port)

結(jié)果為:

scheme  : httpnetloc  : user:pwd@domain:80path    : /pathparams  : paramsquery   : query=queryargfragment: fragmentusername: userpassword: pwdhostname: domainport    : 80

除了 urlparse() 之外,還有一個類似的 urlsplit() 函數(shù)也能對 URL 進行拆分,所不同的是, urlsplit() 并不會把 路徑參數(shù)(params) 從 路徑(path) 中分離出來。

當(dāng) URL 中路徑部分包含多個參數(shù)時,使用 urlparse() 解析是有問題的:

url='http://user:pwd@domain:80/path2;params1/path3;params2?query=queryarg#fragment' parsed_result=urlparse(url) print(parsed_result)print('parsed.path    :', parsed_result.path)print('parsed.params  :', parsed_result.params)

結(jié)果為:

ParseResult(scheme='http', netloc='user:pwd@domain:80', path='/path2;params1/path3', params='params2', query='query=queryarg', fragment='fragment')parsed.path    : /path2;params1/path3parsed.params  : params2

這時可以使用 urlsplit() 來解析:

from urllib.parse import urlsplitsplit_result=urlsplit(url) print(split_result)print('split.path    :', split_result.path)# SplitResult 沒有 params 屬性

結(jié)果為:

SplitResult(scheme='http', netloc='user:pwd@domain:80', path='/path2;params1/path3;params2', query='query=queryarg', fragment='fragment')split.path    : /path2;params1/path3;params2

若只是要將 URL 后的 fragment 標(biāo)識拆分出來,可以使用 urldefrag() 函數(shù):

from urllib.parse import urldefrag url = 'http://user:pwd@domain:80/path2;params1/path3;params2?query=queryarg#fragment' d = urldefrag(url)print(d)print('url     :', d.url)print('fragment:', d.fragment)

結(jié)果為:

DefragResult(url='http://user:pwd@domain:80/path2;params1/path3;params2?query=queryarg', fragment='fragment')url     : http://user:pwd@domain:80/path2;params1/path3;params2?query=queryargfragment: fragment

組建URL

ParsedResult 對象和 SplitResult 對象都有一個 geturl() 方法,可以返回一個完整的 URL 字符串。

print(parsed_result.geturl())print(split_result.geturl())

結(jié)果為:

http://user:pwd@domain:80/path2;params1/path3;params2?query=queryarg#fragmenthttp://user:pwd@domain:80/path2;params1/path3;params2?query=queryarg#fragment

但是 geturl() 只在 ParsedResultSplitResult 對象中有,若想將一個普通的元組組成 URL,則需要使用 urlunparse() 函數(shù):

from urllib.parse import urlunparseurl_compos = ('http', 'user:pwd@domain:80', '/path2;params1/path3', 'params2', 'query=queryarg', 'fragment')print(urlunparse(url_compos))

結(jié)果為:

http://user:pwd@domain:80/path2;params1/path3;params2?query=queryarg#fragment

相對路徑轉(zhuǎn)換絕對路徑

除此之外,urllib.parse 還提供了一個 urljoin() 函數(shù),來將相對路徑轉(zhuǎn)換成絕對路徑的 URL。

from urllib.parse import urljoin print(urljoin('http://www.example.com/path/file.html', 'anotherfile.html'))print(urljoin('http://www.example.com/path/', 'anotherfile.html'))print(urljoin('http://www.example.com/path/file.html', '../anotherfile.html'))print(urljoin('http://www.example.com/path/file.html', '/anotherfile.html'))

結(jié)果為:

http://www.example.com/path/anotherfile.htmlhttp://www.example.com/path/anotherfile.htmlhttp://www.example.com/anotherfile.htmlhttp://www.example.com/anotherfile.html

查詢參數(shù)的構(gòu)造和解析

使用 urlencode() 函數(shù)可以將一個 dict 轉(zhuǎn)換成合法的查詢參數(shù):

from urllib.parse import urlencode query_args = {    'name': 'dark sun',    'country': '中國'} query_args = urlencode(query_args)print(query_args)

結(jié)果為:

name=dark+sun&country=%E4%B8%AD%E5%9B%BD

可以看到特殊字符也被正確地轉(zhuǎn)義了。

相對的,可以使用 parse_qs() 來將查詢參數(shù)解析成 dict。

from urllib.parse import parse_qsprint(parse_qs(query_args))

結(jié)果為:

{'name': ['dark sun'], 'country': ['中國']}

如果只是希望對特殊字符進行轉(zhuǎn)義,那么可以使用 quote 或 quote_plus 函數(shù),其中 quote_plus 比 quote 更激進一些,會把 :、/ 一類的符號也給轉(zhuǎn)義了。

from urllib.parse import quote, quote_plus, urlencode url = 'http://localhost:1080/~hello!/'print('urlencode :', urlencode({'url': url}))print('quote     :', quote(url))print('quote_plus:', quote_plus(url))

結(jié)果為:

urlencode : url=http%3A%2F%2Flocalhost%3A1080%2F%7Ehello%21%2Fquote     : http%3A//localhost%3A1080/%7Ehello%21/quote_plus: http%3A%2F%2Flocalhost%3A1080%2F%7Ehello%21%2F

可以看到 urlencode 中應(yīng)該是調(diào)用 quote_plus 來進行轉(zhuǎn)義的。

逆向操作則使用 unquote 或 unquote_plus 函數(shù):

from urllib.parse import unquote, unquote_plus encoded_url = 'http%3A%2F%2Flocalhost%3A1080%2F%7Ehello%21%2F'print(unquote(encoded_url))print(unquote_plus(encoded_url))

結(jié)果為:

http://localhost:1080/~hello!/http://localhost:1080/~hello!/

你會發(fā)現(xiàn) unquote 函數(shù)居然能正確地將 quote_plus 的結(jié)果轉(zhuǎn)換回來。

看完上述內(nèi)容,你們對Python中怎么利用urlliib.parse庫解析URL有進一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI