如何使用python将url字符串转换为安全字符



假设我有以下字符串:

"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中,最好的方法是什么?

Python 2的urlib.quote_plus和Python 3的urlib.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'

在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='/:?=&')

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

最新更新