Python3模組詳解--老司機工具urllib模組詳解之urllib.parse子模組
This module defines a standard interface to break Uniform Resource Locator (URL) strings up in components (addressing scheme, network location, path etc.), to combine the components back into a URL string, and to convert a “relative
URL” to an absolute URL given a “base URL.”
這是官方API上對這個模組的解釋:這個模組是一個能把URL字串拆分成元件,能把元件合併成URL和將一個相對的URL轉成一個抽象的URL,從而的到一個基本的URL標準格式。
簡單的說就是可以拆分URL,也可以拼接URL,他支援的URL格式為:file、ftp、gopher、hdl、http、https、imap、mailto,mms、news、nntp、prospero、rsync、rtsp、rtspu、sftp、shttp、sip、sips、snews、svn、svn+ssh、telnet、wais、ws、wss。
這個模組預設分為兩個類別,URL parsing(URL解析) 和 URL quoting(URL引用)
(一)、URL parsing(URL解析)
The URL parsing functions focus on splitting a URL string into its components, or on combining URL components into a URL string.
URL parsing函式注重將URL字串分成元件,或者將元件合併成一個URL
urllib.parse.urlparse(urlstring, scheme=”, allow_fragments=True)
函式用於將一個URL解析成六個部分,返回一個元組
以下為返回的元組元素:
元素 |
編號 |
值 |
值不存在時預設值 |
scheme |
0 | 請求 | 一定存在 |
netloc |
1 | 網址 | 空字串 |
path |
2 | 分層路徑 | 空字串 |
params |
3 | 引數 | 空字串 |
query |
4 | 查詢元件 | 空字串 |
fragment |
5 | 識別符號 | 空字串 |
username |
使用者名稱 | None | |
password |
密碼 | None | |
hostname |
主機名 | None | |
port |
埠號 | None |
import urllib.parse
print(urllib.parse.urlparse("https://www.zhihu.com/question/50056807/answer/223566912"))
輸出結果:
ParseResult(scheme='https', netloc='www.zhihu.com', path='/question/50056807/answer/223566912', params='', query='', fragment='')
urllib.parse.
parse_qs
(qs, keep_blank_values=False, strict_parsing=False
這個函式主要用於分析URL中query元件的引數,返回一個key-value對應的字典格式;
示例如下:
import urllib.parse
print(urllib.parse.parse_qs("FuncNo=9009001&username=1"))
輸出結果:
{'FuncNo': ['9009001'], 'username': ['1']}
urllib.parse.
parse_qsl
(qs, keep_blank_values=False, strict_parsing=False, encoding=’utf-8’, errors=’replace’)
urllib.parse.
parse_qs()
作用一樣,唯一的區別就是這個函式返回值是list形式;
示例如下:
import urllib.parse
print(urllib.parse.parse_qsl("FuncNo=9009001&username=1"))
輸出結果[('FuncNo', '9009001'), ('username', '1')]
urllib.parse.urlunparse
(parts)
這個函式可以將urlparse()分解出來的元組組裝成URL;
示例如下:
import urllib.parse
# print(urllib.parse.parse_qsl("FuncNo=9009001&username=1"))
parsed=urllib.parse.urlparse("https://www.zhihu.com/question/50056807/answer/223566912")
print(parsed)
# print(urllib.parse.parse_qs("https://www.zhihu.com/question/50056807/answer/223566912"))
# print(urllib.parse.parse_qs("FuncNo=9009001&username=1"))
t=parsed[:]
print(urllib.parse.urlunparse(t))
輸出結果:
ParseResult(scheme='https', netloc='www.zhihu.com', path='/question/50056807/answer/223566912', params='', query='', fragment='')
https://www.zhihu.com/question/50056807/answer/223566912
urllib.parse.
urlsplit
(urlstring, scheme=”, allow_fragments=True)這個函式和urlparse()功能類似,唯一的區別是這個函式不會將url中的param分離出來;就是說相比urlparse()少一個param元素,返回的元組元素參照urlparse()的元組表,少了一個param元素;
示例如下:
import urllib.parse
print(urllib.parse.urlsplit("https://www.zhihu.com/question/50056807/answer/223566912"))
輸出結果:
SplitResult(scheme='https', netloc='www.zhihu.com', path='/question/50056807/answer/223566912', query='', fragment='')
urllib.parse.
urlunsplit
(parts)
示例如下:
import urllib.parse
parsed=urllib.parse.urlsplit("https://www.zhihu.com/question/50056807/answer/223566912")
t=parsed[:]
print(urllib.parse.urlunsplit(t))
輸出結果:
https://www.zhihu.com/question/50056807/answer/223566912
urllib.parse.
urljoin
(base, url, allow_fragments=True)
這個函式用於講一個基本的URL和其他的URL組裝成成一個完成的URL;
示例如下:
import urllib.parse
print(urllib.parse.urljoin("https://www.baidu.com/Python.html","Java.html"))
輸出結果:
https://www.baidu.com/Java.html
注意:如果URL是一個抽象的URL(例如以“//”或“scheme://”開頭),這個URL的主機名或請求標識會自動返回;
示例如下:
import urllib.parse
print(urllib.parse.urljoin("https://www.baidu.com/Python.html","//www.zhihu.com/Java.html"))
輸出結果:
https://www.zhihu.com/Java.html
urllib.parse.urldefrag
(url)
如果URL中包含fragment標識,就會返回一個不帶fragment標識的URL,fragment標識會被當成一個分離的字串返回;如果URL中不包含fragment標識,就會返回一個URL和一個空字串;
示例如下:
import urllib.parse
print(urllib.parse.urldefrag("http://user123:[email protected]:80/path;param?query=arg#frag"))
print(urllib.parse.urldefrag("http://user123:[email protected]:80/path;param?query=arg"))
輸出結果:
DefragResult(url='http://user123:[email protected]:80/path;param?query=arg', fragment='frag')
DefragResult(url='http://user123:[email protected]:80/path;param?query=arg', fragment='')
(二)、URL quoting(URL引用)
The URL quoting functions focus on taking program data and making it safe for use as URL components by quoting special characters and appropriately encoding non-ASCII text. They also support reversing these operations to recreate the original data from the contents of a URL component if that task isn’t already covered by the URL parsing functions above
這個模組的主要作用就是通過引入合適編碼和特殊字元對URL進行安全重構,並且可以反向解析。
urllib.parse.
quote
(string, safe=’/’, encoding=None, errors=None)
第一個引數是URL,第二個引數是安全的字串,即在加密的過程中,該類字元不變。預設為“/”;
示例如下:
import urllib.parse
url="https://www.zhihu.com/question/50056807/answer/223566912"
print(urllib.parse.quote(url))
print(urllib.parse.quote(url,safe=":"))
輸出結果:
https%3A//www.zhihu.com/question/50056807/answer/223566912
https:%2F%2Fwww.zhihu.com%2Fquestion%2F50056807%2Fanswer%2F223566912
urllib.parse.
quote_plus
(string, safe=”, encoding=None, errors=None)這個函式和quote()相似,但是這個函式能把空格轉成加號,並且safe的預設值為空
示例如下:
import urllib.parse
url="https://www.zhihu.com/ question/50056807/answer/223566912"
print(urllib.parse.quote_plus(url))
輸出結果:
https%3A%2F%2Fwww.zhihu.com%2F+question%2F50056807%2Fanswer%2F223566912
urllib.parse.
quote_from_bytes
(bytes, safe=’/’)和quote()相似,但是接收的是位元組而不是字元;
urllib.parse.
unquote
(string, encoding=’utf-8’, errors=’replace’)、urllib.parse.
unquote_plus
(string, encoding=’utf-8’, errors=’replace’)、urllib.parse.
unquote_to_bytes
(string)
這三個函式分別與上面的quote()、quote_plus()、quote_from_bytes()相對應,解析相應函式處理過的URL;
urllib.parse.
urlencode
(query, doseq=False, safe=”, encoding=None, errors=None, quote_via=quote_plus)
這個函式主要用於接收map型別或兩個序列元素的元組,從而將資料拼接成引數,結果返回的是key=value形式,並且多個引數用&分離,即key1=value1&key2=value2...格式