概述

urllib.parse 是 Python 标准库中用于处理 URL 的库。它提供了一系列函数和类,用于在 Python 程序中与网络交互。urllib.parse 库的功能包括:

解析 URL 字符串构造 URL 字符串对 URL 进行编码和解码处理 URL 的组成部分(如协议、主机、路径等)标准化 URL 格式

常用函数

urllib.parse 库中提供了以下常用函数:

urlparse():解析 URL 字符串,并返回一个包含各个组成部分的元组。urlunparse():将 URL 的各个组成部分构造为字符串。urlencode():对 URL 参数进行编码。urldecode():对 URL 参数进行解码。quote():对字符串进行 URL 编码。unquote():对字符串进行 URL 解码。parse_qs():解析 URL 查询字符串,并返回一个包含参数键值对的字典。urljoin():将两个 URL 连接起来。

示例

以下是一些使用 urllib.parse 库的示例:

解析 URL 字符串

Python

import urllib.parse

url = 'https://www.example.com/path/to/resource?key=value¶m=another_value'

parsed_url = urllib.parse.urlparse(url)

print(parsed_url.scheme) # 输出:https

print(parsed_url.netloc) # 输出:www.example.com

print(parsed_url.path) # 输出:/path/to/resource

print(parsed_url.params) # 输出:?key=value¶m=another_value

print(parsed_url.query) # 输出:key=value¶m=another_value

print(parsed_url.fragment) # 输出:

构造 URL 字符串

Python

import urllib.parse

scheme = 'https'

netloc = 'www.example.com'

path = '/path/to/resource'

params = {'key': 'value', 'param': 'another_value'}

constructed_url = urllib.parse.urlunparse((scheme, netloc, path, params, '', ''))

print(constructed_url) # 输出:https://www.example.com/path/to/resource?key=value¶m=another_value

对 URL 参数进行编码

Python

import urllib.parse

params = {'key': 'This is a value with spaces & special characters', 'param2': 'another value'}

encoded_params = urllib.parse.urlencode(params)

print(encoded_params) # 输出:key=This+is+a+value+with+spaces+%26+special+characters¶m2=another+value

对 URL 参数进行解码

Python

import urllib.parse

encoded_params = 'key=This+is+a+value+with+spaces+%26+special+characters¶m2=another+value'

decoded_params = urllib.parse.urldecode(encoded_params)

print(decoded_params) # 输出:{'key': 'This is a value with spaces & special characters', 'param2': 'another value'}

对字符串进行 URL 编码

Python

import urllib.parse

string = 'This is a string with spaces & special characters'

encoded_string = urllib.parse.quote(string)

print(encoded_string) # 输出:This+is+a+string+with+spaces+%26+special+characters

对字符串进行 URL 解码

Python

import urllib.parse

encoded_string = 'This+is+a+string+with+spaces+%26+special+characters'

decoded_string = urllib.parse.unquote(encoded_string)

print(decoded_string) # 输出:This is a string with spaces & special characters

解析 URL 查询字符串

Python

import urllib.parse

url = 'https://www.example.com/path/to/resource?key=value¶m=another_value'

query_params = urllib.parse.parse_qs(url.split('?')[1])

print(query_params) # 输出:{'key': ['value'], 'param': ['another_value']}

将两个 URL 连接起来

Python

import urllib.parse

base_url = 'https://www.example.com

推荐文章

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。