1. 程式人生 > >Python3模組詳解--老司機工具urllib模組詳解之urllib.parse子模組

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解析成六個部分,返回一個元組

,URL的格式為:scheme://netloc/path;parameters?query#fragment;包含六個部分,元組中每一個元素都是一個字串,可以為空,這六個部分均不能再被分割成更小的部分;

以下為返回的元組元素:

元素
編號

值不存在時預設值
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(qskeep_blank_values=Falsestrict_parsing=False

encoding=’utf-8’errors=’replace’)

這個函式主要用於分析URL中query元件的引數,返回一個key-value對應的字典格式;

示例如下:

import urllib.parse
print(urllib.parse.parse_qs("FuncNo=9009001&username=1"))
輸出結果:
{'FuncNo': ['9009001'], 'username': ['1']}

urllib.parse.parse_qsl(qskeep_blank_values=Falsestrict_parsing=Falseencoding=’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(urlstringscheme=”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)

與urlunparse()相似,切與urlsplit()相對應;

示例如下:

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(baseurlallow_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(stringsafe=’/’encoding=Noneerrors=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(stringsafe=”encoding=Noneerrors=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(bytessafe=’/’)
和quote()相似,但是接收的是位元組而不是字元;

urllib.parse.unquote(stringencoding=’utf-8’errors=’replace’)、urllib.parse.unquote_plus(stringencoding=’utf-8’errors=’replace’)、urllib.parse.unquote_to_bytes(string)

這三個函式分別與上面的quote()、quote_plus()、quote_from_bytes()相對應,解析相應函式處理過的URL;

urllib.parse.urlencode(querydoseq=Falsesafe=”encoding=Noneerrors=Nonequote_via=quote_plus)

這個函式主要用於接收map型別或兩個序列元素的元組,從而將資料拼接成引數,結果返回的是key=value形式,並且多個引數用&分離,即key1=value1&key2=value2...格式