urllib.request --- 用來開啟 URLs 的可擴充函式庫¶
urllib.request module(模組)定義了一些函式與 class(類別)用以開啟 URLs(大部分是 HTTP),並處理各式複雜情況如:basic 驗證與 digest 驗證、重新導向、cookies。
也參考
有關於更高階的 HTTP 用戶端介面,推薦使用 Requests 套件。
警告
On macOS it is unsafe to use this module in programs using
os.fork() because the getproxies() implementation for
macOS uses a higher-level system API. Set the environment variable
no_proxy to * to avoid this problem
(e.g. os.environ["no_proxy"] = "*").
可用性: not WASI.
此模組在 WebAssembly 平台上不起作用或無法使用。更多資訊請參閱 WebAssembly 平台。
urllib.request module 定義下列函式:
- urllib.request.urlopen(url, data=None, [timeout, ]*, context=None)¶
打開 url,其值可以是一個包含有效且適當編碼 URL 的字串或是一個
Request物件。data 必須是一個包含傳送給伺服器額外資料的物件,若不需要傳送額外資料則指定為
None。更多細節請見Request。urllib.request module 使用 HTTP/1.1 並包含
Connection:closeheader(標頭)在其 HTTP 請求中。透過選擇性參數 timeout 來指定 blocking operations(阻塞性操作,如:嘗試連接)的 timeout(超時時間),以秒為單位。若沒有指定值,則會使用全域預設超時時間設定。實際上,此參數僅作用於 HTTP、HTTPS 以及 FTP 的連接。
若 context 有被指定時,它必須是一個
ssl.SSLContext的實例並描述著各種 SSL 選項。更多細節請見HTTPSConnection。這個函式總是回傳一個可作為 context manager 使用的物件,並有著特性 (property) url、headers 與 status。欲知更多這些特性細節請參見
urllib.response.addinfourl。對於 HTTP 與 HTTPS 的 URLs,這個函式回傳一個稍有不同的
http.client.HTTPResponse物件。除了上述提到的三個方法外,另有 msg 屬性並有著與reason相同的資訊 --- 由伺服器回傳的原因敘述 (reason phrase),而不是在HTTPResponse文件中提到的回應 headers。對於 FTP、檔案及資料的 URLs,這個函式會回傳一個
urllib.response.addinfourl物件。當遇到協定上的錯誤時會引發
URLError。請注意若沒有 handler 處理請求時,
None值將會被回傳。(即使有預設的全域類別OpenerDirector使用UnknownHandler來確保這種情況不會發生)另外,若有偵測到代理服務的設定(例如當
*_proxy環境變數像是::envvar:!http_proxy` 有被設置時),ProxyHandler會被預設使用以確保請求有透過代理服務來處理。Python 2.6 或更早版本的遺留函式
urllib.urlopen已經不再被維護;新函式urllib.request.urlopen()對應到舊函式urllib2.urlopen。有關代理服務的處理,以往是透過傳遞 dictionary(字典)參數給urllib.urlopen來取得的,現在則可以透過ProxyHandler物件來取得。預設的 opener 會觸發一個 auditing event
urllib.Request與其從請求物件中所獲得的引數fullurl、data、headers、method。在 3.2 版的變更: 新增 cafile 與 capath。
HTTPS 虛擬主機 (virtual hosts) 現已支援,只要
ssl.HAS_SNI的值為 true。data 可以是一個可疊代物件。
在 3.3 版的變更: cadefault 被新增。
在 3.4.3 版的變更: context 被新增。
在 3.10 版的變更: 當 context 沒有被指定時,HTTPS 連線現在會傳送一個帶有協定指示器
http/1.1的 ALPN 擴充 (extension)。自訂的 context 應該利用set_alpn_protocols()來自行設定 ALPN 協定。在 3.13 版的變更: Remove cafile, capath and cadefault parameters: use the context parameter instead.
- urllib.request.install_opener(opener)¶
安裝一個
OpenerDirector實例作為預設的全域 opener。僅在當你想要讓 urlopen 使用該 opener 時安裝一個 opener,否則的話應直接呼叫OpenerDirector.open()而非urlopen()。程式碼不會檢查 class 是否真的為OpenerDirector,而是任何具有正確介面的 class 都能適用。
- urllib.request.build_opener([handler, ...])¶
回傳一個
OpenerDirector實例,以給定的順序把 handlers 串接起來。handlers 可以是BaseHandler的實例,亦或是BaseHandler的 subclasses(這個情況下必須有不帶參數的建構函式能夠被呼叫)。以下 classes 的實例順位會在 handlers 之前,除非 handlers 已經包含它們,是它們的實例,或是它們的 subclasses:ProxyHandler(如果代理服務設定被偵測到)、UnknownHandler、HTTPHandler、HTTPDefaultErrorHandler、HTTPRedirectHandler、FTPHandler、FileHandler、HTTPErrorProcessor。如果 Python 安裝時已帶有 SSL 支援(如果
sslmodule 能夠被 import),則HTTPSHandler也在上述 class 之中。一個
BaseHandler的 subclass 可能透過改變其handler_order屬性來調整它在 handlers list 中的位置。
- urllib.request.pathname2url(path, *, add_scheme=False)¶
Convert the given local path to a
file:URL. This function usesquote()function to encode the path.If add_scheme is false (the default), the return value omits the
file:scheme prefix. Set add_scheme to true to return a complete URL.This example shows the function being used on Windows:
>>> from urllib.request import pathname2url >>> path = 'C:\\Program Files' >>> pathname2url(path, add_scheme=True) 'file:///C:/Program%20Files'
在 3.14 版的變更: Windows drive letters are no longer converted to uppercase, and
:characters not following a drive letter no longer cause anOSErrorexception to be raised on Windows.在 3.14 版的變更: Paths beginning with a slash are converted to URLs with authority sections. For example, the path
/etc/hostsis converted to the URL///etc/hosts.在 3.14 版的變更: 新增 add_scheme 參數。
- urllib.request.url2pathname(url, *, require_scheme=False, resolve_host=