urllib.request --- 用來開啟 URLs 的可擴充函式庫

原始碼:Lib/urllib/request.py


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:close header(標頭)在其 HTTP 請求中。

透過選擇性參數 timeout 來指定 blocking operations(阻塞性操作,如:嘗試連接)的 timeout(超時時間),以秒為單位。若沒有指定值,則會使用全域預設超時時間設定。實際上,此參數僅作用於 HTTP、HTTPS 以及 FTP 的連接。

context 有被指定時,它必須是一個 ssl.SSLContext 的實例並描述著各種 SSL 選項。更多細節請見 HTTPSConnection

這個函式總是回傳一個可作為 context manager 使用的物件,並有著特性 (property) urlheadersstatus。欲知更多這些特性細節請參見 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 與其從請求物件中所獲得的引數 fullurldataheadersmethod

在 3.2 版的變更: 新增 cafilecapath

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(如果代理服務設定被偵測到)、UnknownHandlerHTTPHandlerHTTPDefaultErrorHandlerHTTPRedirectHandlerFTPHandlerFileHandlerHTTPErrorProcessor

如果 Python 安裝時已帶有 SSL 支援(如果 ssl module 能夠被 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 uses quote() 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 an OSError exception to be raised on Windows.

在 3.14 版的變更: Paths beginning with a slash are converted to URLs with authority sections. For example, the path /etc/hosts is converted to the URL ///etc/hosts.

在 3.14 版的變更: 新增 add_scheme 參數。

urllib.request.url2pathname(url, *, require_scheme=False, resolve_host=False)

Convert the given file: URL to a local path. This function uses unquote() to decode the URL.

If require_scheme is false (the default), the given value should omit a file: scheme prefix. If require_scheme is set to true, the given value should include the prefix; a URLError is raised if it doesn't.

The URL authority is discarded if it is empty, localhost, or the local hostname. Otherwise, if resolve_host is set to true, the authority is resolved using socket.gethostbyname() and discarded if it matches a local IP address (as per RFC 8089 §3). If the authority is still unhandled, then on Windows a UNC path is returned, and on other platforms a URLError is raised.

This example shows the function being used on Windows:

>>> from urllib.request import url2pathname
>>> url = 'file:///C:/Program%20Files'
>>> url2pathname(url, require_scheme=True)
'C:\\Program Files'

在 3.14 版的變更: Windows drive letters are no longer converted to uppercase, and : characters not following a drive letter no longer cause an OSError exception to be raised on Windows.

在 3.14 版的變更: The URL authority is discarded if it matches the local hostname. Otherwise, if the authority isn't empty or localhost, then on Windows a UNC path is returned (as before), and on other platforms a URLError is raised.

在 3.14 版的變更: The URL query and fragment components are discarded if present.

在 3.14 版的變更: The require_scheme and resolve_host parameters were added.

urllib.request.getproxies()

這個輔助函式 (helper function) 回傳一個代理伺服器 URL mappings(對映)的 dictionary。在所有的作業系統中,它首先掃描環境中有著 <scheme>_proxy 名稱的變數(忽略大小寫的),如果找不到的話就會在 macOS 中的系統設定 (System Configuration) 或是 Windows 系統中的 Windows Systems Registry 尋找代理服務設定。如果大小寫的環境變數同時存在且值有不同,小寫的環境變數會被選用。

備註

如果環境變數 REQUEST_METHOD 有被設置(通常這代表著你的 script 是運行在一個共用閘道介面 (CGI) 環境中),那麼環境變數 HTTP_PROXY (大寫的 _PROXY)將被忽略。這是因為變數可以透過使用 "Proxy:" HTTP header 被注入。如果需要在共用閘道介面環境中使用 HTTP 代理服務,可以明確使用 ProxyHandler,亦或是確認變數名稱是小寫的(或至少 _proxy 後綴是小寫的)。

提供了以下的 classes:

class urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)

這個 class 是一個 URL 請求的抽象 class。

url 是一個包含有效且適當編碼的 URL 字串。

data 必須是一個包含要送到伺服器的附加資料的物件,若不需帶附加資料則其值應為 None。目前 HTTP 請求是唯一有使用 data 參數的,其支援的物件型別包含位元組、類檔案物件 (file-like objects)、以及可疊代的類位元組串物件 (bytes-like objects)。如果沒有提供 Content-LengthTransfer-Encoding headers 欄位,HTTPHandler 將會根據 data 的型別設置這些 header。Content-Length 會被用來傳送位元組串物件,而 RFC 7230 章節 3.3.1 所定義的 Transfer-Encoding: chunked 則會被用來傳送檔案或是其它可疊代物件 (iterables)。

對於一個 HTTP POST 請求方法,data 應為一個標準 application/x-www-form-urlencoded 格式的 buffer。urllib.parse.urlencode() 方法接受一個 mapping 或是 sequence(序列)的 2-tuples,並回傳一個對應格式的 ASCII 字串。在被作為 data 參數前它應該被編碼成位元組串。

headers 必須是一個 dictionary,並會被視為如同每對 key 和 value 作為引數來呼叫 add_header()。經常用於「偽裝」 User-Agent header 的值,這個 header 是用來讓一個瀏覽器向伺服器表明自己的身分 --- 有些 HTTP 伺服器僅允許來自普通瀏覽器的請求,而不接受來自程式腳本的請求。例如,Mozilla Firefox 會將 header 的值設為 "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11",而 urllib 的值則是 "Python-urllib/2.6"(在 Python 2.6 上)。所有 header 的鍵都會以 camel case(駝峰式大小寫)來傳送。

當有給定 data 引數時,一個適當的 Content-Type header 應該被設置。如果這個 header 沒有被提供且 data 也不為 None 時,預設值 Content-Type: application/x-www-form-urlencoded 會被新增至請求中。

接下來的兩個引數的介紹提供給那些有興趣正確處理第三方 HTTP cookies 的使用者:

origin_req_host 應為原始傳輸互動的請求主機 (request-host),如同在 RFC 2965 中的定義。預設值為 http.cookiejar.request_host(self)。這是使用者發起的原始請求的主機名稱或是 IP 位址。例如當請求是要求一個 HTML 文件中的一個影像,則這個屬性應為請求包含影像頁面的請求主機。

unverifiable 應該標示一個請求是否是無法驗證的,如同在 RFC 2965 中的定義。其預設值為 False。一個無法驗證的請求是指使用者沒有機會去批准請求的 URL,例如一個對於 HTML 文件中的影像所做的請求,而使用者沒有機會去批准是否能自動擷取影像,則這個值應該為 true。

method 應為一個標示 HTTP 請求方法的字串(例如:'HEAD')。如果有提供值,則會被存在 method 屬性中且被 get_method() 所使用。當 dataNone 時,其預設值為 'GET',否則預設值為 'POST'。Subclasses 可以透過設置其 method 屬性來設定不一樣的預設請求方法。

備註

如果資料物件無法重複提供其內容(例如一個檔案或是只能產生一次內容的可疊代物件)且請求因為 HTTP 重導向 (redirects) 或是 HTTP 驗證 (authentication) 而被重新嘗試傳送,則該請求不會正常運作。data 會接在 headers 之後被送至 HTTP 伺服器。此函式庫沒有支援 100-continue expectation。

在 3.3 版的變更: 新增 Request.method 引數到 Request class。

在 3.4 版的變更: 能夠在 class 中設置預設的 Request.method

在 3.6 版的變更: 如果 Content-Length 尚未被提供且 data 既不是 None 也不是一個位元組串物件,則不會觸發錯誤,並 fall back(後備)使用分塊傳輸編碼 (chunked transfer encoding)。

class urllib.request.OpenerDirector

The OpenerDirector class opens URLs via BaseHandlers chained together. It manages the chaining of handlers, and recovery from errors.

class urllib.request.BaseHandler

This is the base class for all registered handlers --- and handles only the simple mechanics of registration.

class urllib.request.HTTPDefaultErrorHandler

A class which defines a default handler for HTTP error responses; all responses are turned into HTTPError exceptions.

class