urllib.request — 用于打开 URL 的可扩展库

源代码: Lib/urllib/request.py


The urllib.request 模块定义有助于在复杂环境打开 URL (主要是 HTTP) 的函数和类 — 基本和摘要身份验证、重定向、Cookie 等。

另请参阅

The Requests 包 推荐为更高级别的 HTTP 客户端接口。

警告

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"] = "*" ).

可用性 :非 WASI。

This module does not work or is not available on WebAssembly. See WebAssembly 平台 了解更多信息。

The urllib.request 模块定义了下列函数:

urllib.request. urlopen ( url , data=None , [ timeout , ] * , context=None )

打开 url , which can be either a string containing a valid, properly encoded URL, or a Request 对象。

data 必须是指定要被发送给服务器的额外数据的对象,或 None 若不需要这样的数据。见 Request 了解细节。

urllib.request 模块使用 HTTP/1.1 并包括 Connection:close HTTP 头在其 HTTP 请求中。

可选 timeout 参数指定超时 (以秒为单位) 为阻塞像连接尝试操作 (若未指定,将使用全局默认超时设置)。这实际仅工作于 HTTP HTTPS 及 FTP 连接。

context 被指定,它必须是 ssl.SSLContext 实例 (描述各种 SSL 选项)。见 HTTPSConnection 了解更多细节。

该函数总是返回对象,其能作为 上下文管理器 and has the properties url , headers ,和 status 。见 urllib.response.addinfourl 了解这些特性的更多细节。

对于 HTTP 和 HTTPS URL,此函数返回 http.client.HTTPResponse 稍微修改对象。除上述 3 新方法外,msg 属性包含的信息如同 reason 属性 — 由服务器返回的原因短语 — 而不是在文档编制中指定的响应 Header 头为 HTTPResponse .

对于 FTP、文件、数据 URL 及请求明确被处理通过传统 URLopener and FancyURLopener 类,此函数返回 urllib.response.addinfourl 对象。

引发 URLError 在协议错误时。

注意, None 可能被返回,若没有处理程序处理请求 (虽然默认安装了全局 OpenerDirector 使用 UnknownHandler 以确保这从不发生)。

此外,若检测到代理设置 (例如,当 *_proxy 环境变量像 http_proxy 有设置), ProxyHandler ProxyHandler 是默认安装的,并确保透过代理处理请求。

传统 urllib.urlopen 函数从 Python 2.6 及更早版本起已被放弃; urllib.request.urlopen() 相当于旧 urllib2.urlopen 。处理代理是把字典参数传递给 urllib.urlopen ,可以获得通过使用 ProxyHandler 对象。

默认开启器引发 审计事件 urllib.Request 采用自变量 fullurl , data , headers , method taken from the request object.

3.2 版改变: cafile and capath 被添加。

现在支持 HTTPS 虚拟主机,若可能的话 (也就是说,若 ssl.HAS_SNI 为 True)。

data 可以是可迭代对象。

3.3 版改变: cadefault 被添加。

3.4.3 版改变: context 被添加。

3.10 版改变: HTTPS connection now send an ALPN extension with protocol indicator http/1.1 when no context is given. Custom context should set ALPN protocols with set_alpn_protocols() .

Changed in version 3.13: 移除 cafile , capath and cadefault parameters: use the context parameter instead.

urllib.request. install_opener ( opener )

安装 OpenerDirector instance as the default global opener. Installing an opener is only necessary if you want urlopen to use that opener; otherwise, simply call OpenerDirector.open() 而不是 urlopen() . The code does not check for a real OpenerDirector , and any class with the appropriate interface will work.

urllib.request. build_opener ( [ handler , ... ] )

返回 OpenerDirector instance, which chains the handlers in the order given. handler s can be either instances of BaseHandler , or subclasses of BaseHandler (in which case it must be possible to call the constructor without any parameters). Instances of the following classes will be in front of the handler s, unless the handler s contain them, instances of them or subclasses of them: ProxyHandler (if proxy settings are detected), UnknownHandler , HTTPHandler , HTTPDefaultErrorHandler , HTTPRedirectHandler , FTPHandler , FileHandler , HTTPErrorProcessor .

若 Python 安装有 SSL 支持 (即:若 ssl 模块可以被导入), HTTPSHandler will also be added.

A BaseHandler 子类还可以改变其 handler_order attribute to modify its position in the handlers list.

urllib.request. pathname2url ( path )

Convert the given local path to a file: URL. This function uses quote() function to encode the path. For historical reasons, the return value omits the file: scheme prefix. This example shows the function being used on Windows:

>>> from urllib.request import pathname2url
>>> path = 'C:\\Program Files'
>>> 'file:' + pathname2url(path)
'file:///C:/Program%20Files'