urllib.parse — 在 Python 中将 URL 解析为组件

pythonserver side programmingprogramming更新于 2025/5/4 3:24:17

此模块提供了一个标准接口,用于拆分组件中的统一资源定位符 (URL) 字符串或将组件重新组合为 URL 字符串。它还具有将给定"基本 URL"的"相对 URL"转换为绝对 URL 的功能。

此模块支持以下 URL 方案 -

  • file
  • ftp
  • gopher
  • hdl
  • http
  • https
  • imap
  • mailto
  • mms
  • news
  • nntp
  • prospero
  • rsync
  • rts p
  • rtspu
  • sftp
  • shttp
  • sip
  • sips
  • snews
  • svn
  • svn+ssh
  • telnet
  • wais
  • ws
  • wss

urlparse()

此函数将 URL 解析为六个组件,返回一个 6 元组。这对应于 URL 的一般结构。每个元组项都是一个字符串。组件不会分解成更小的部分(例如,网络位置是单个字符串),并且 % 转义不会展开。返回值是元组子类的实例,该元组由以下属性组成:

AttributeIndexValueValue if not present
scheme0URL scheme specifierscheme parameter
netloc1Network location partscheme parameter
path2Hierarchical pathempty string
params3Parameters for last path elementempty string
query4Query componentempty string
fragment5Fragment identifierempty string
username
User nameNone
password
PasswordNone
hostname
Host name (lower case)None
port
Port number as integer, if presentNone

示例

>>> from urllib.parse import urlparse
>>> url = 'https://mail.google.com/mail/u/0/?tab = rm#inbox'
>>> t = urlparse(url)
ParseResult(scheme = 'https', netloc = 'mail.google.com', path = '/mail/u/0/', params = '', query = 'tab = rm', fragment = 'inbox')

urlunparse(parts)

此函数根据 urlparse() 返回的元组构造 URL。parts 参数可以是任何六项可迭代对象。

>>> from urllib.parse import urlunparse
>>> urlunparse(t)
'https://mail.google.com/mail/u/0/?tab = rm#inbox'

urlsplit(urlstring, scheme = '', allow_fragments = True):

这与 urlparse() 类似,但不会将参数从 URL 中拆分出来。此函数返回一个 5 元组:(寻址方案、网络位置、路径、查询、片段标识符)。

>>> from urllib.parse import urlsplit
>>> urlsplit(url)
SplitResult(scheme = 'https', netloc = 'mail.google.com', path = '/mail/u/0/', query = 'tab = rm', fragment = 'inbox')

urlunsplit(parts)

此函数将 urlsplit() 返回的元组元素组合成一个完整的 URL 字符串。

URL 引用函数专注于获取程序数据,并通过引用特殊字符和适当编码非 ASCII 文本使其可以安全地用作 URL 组件。

quote()

此函数使用 %xx 转义替换字符串中的特殊字符。字母、数字和字符 '_.-~'永远不会被引用。

>>> from urllib.parse import quote
>>> q = quote(url)
'https%3A//mail.google.com/mail/u/0/%3Ftab%3Drm%23inbox'
quote_plus():

与 quote() 类似,但也用加号替换空格,这是在构建查询字符串以进入 URL 时引用 HTML 表单值所必需的。

unquote()

此函数将 %xx 转义替换为其单字符等效项。

>>> from urllib.parse import unquote
>>> unquote(q)
'https://mail.google.com/mail/u/0/?tab = rm#inbox'

urlencode()

此函数将映射对象或二元素元组序列转换为百分比编码的 ASCII 文本字符串。生成的字符串是一系列由 '&' 字符分隔的键 = 值对。

>>> from urllib.parse import urlencode
>>> qry = {"name":"Rajeev", "salary":20000}
>>> urlencode(qry)
'name = Rajeev&salary = 20000'

相关文章


有用资源