25

假设我有以下字符串:

"http://earth.google.com/gallery/kmz/women_for_women.kmz?a=large"

是否有一些函数或模块能够将上面的字符串转换为下面的字符串,其中所有字符都被更改为与 url 兼容:

"http%3A%2F%2Fearth.google.com%2Fgallery%2Fkmz%2Fwomen_for_women.kmz%3Fa%3Dlarge"

在 python 中执行此操作的最佳方法是什么?

4

3 回答 3

32

Python 2 的urllib.quote_plus和 Python 3 的urllib.parse.quote_plus

url = "http://earth.google.com/gallery/kmz/women_for_women.kmz?a=large"
# Python 2
urllib.quote_plus(url)
# Python 3
urllib.parse.quote_plus(url)

输出:

'http%3A%2F%2Fearth.google.com%2Fgallery%2Fkmz%2Fwomen_for_women.kmz%3Fa%3Dlarge'
于 2012-08-22T22:37:37.110 回答
8

在 Windows 平台上可用

#! python3.6
from urllib.parse import quote


# result: http://www.oschina.net/search?scope=bbs&q=C%E8%AF%AD%E8%A8%80
quote('http://www.oschina.net/search?scope=bbs&q=C语言',safe='/:?=&')
于 2018-01-03T12:32:57.740 回答
2

您在寻找urllib.quote还是urllib.quote_plus?请注意,您没有引用问题中提到的整个 url 字符串。您通常引用路径中或查询字符串之后的部分。无论您要在应用程序中使用哪个。

于 2012-08-22T22:39:23.170 回答