urllib.request
— 用于打开 URL 的可扩展库
¶
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:closeHTTP 头在其 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 及请求明确被处理通过传统
URLopenerandFancyURLopener类,此函数返回urllib.response.addinfourl对象。引发
URLError在协议错误时。注意,
None可能被返回,若没有处理程序处理请求 (虽然默认安装了全局OpenerDirector使用UnknownHandler以确保这从不发生)。此外,若检测到代理设置 (例如,当
*_proxy环境变量像http_proxy有设置),ProxyHandlerProxyHandler 是默认安装的,并确保透过代理处理请求。传统
urllib.urlopen函数从 Python 2.6 及更早版本起已被放弃;urllib.request.urlopen()相当于旧urllib2.urlopen。处理代理是把字典参数传递给urllib.urlopen,可以获得通过使用ProxyHandler对象。默认开启器引发 审计事件
urllib.Request采用自变量fullurl,data,headers,methodtaken 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.1when no context is given. Custom context should set ALPN protocols withset_alpn_protocols().Changed in version 3.13: 移除 cafile , capath and cadefault parameters: use the context parameter instead.
- urllib.request. install_opener ( opener ) ¶
-
安装
OpenerDirectorinstance as the default global opener. Installing an opener is only necessary if you want urlopen to use that opener; otherwise, simply callOpenerDirector.open()而不是urlopen(). The code does not check for a realOpenerDirector, and any class with the appropriate interface will work.
- urllib.request. build_opener ( [ handler , ... ] ) ¶
-
返回
OpenerDirectorinstance, which chains the handlers in the order given. handler s can be either instances ofBaseHandler, or subclasses ofBaseHandler(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模块可以被导入),HTTPSHandlerwill also be added.A
BaseHandler子类还可以改变其handler_orderattribute to modify its position in the handlers list.
- urllib.request. pathname2url ( path ) ¶
-
Convert the given local path to a
file:URL. This function usesquote()function to encode the path. For historical reasons, the return value omits thefile: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'