如何在 Python 中对 URL 参数进行百分比编码? [英] How can I percent-encode URL parameters in Python?

查看:50
本文介绍了如何在 Python 中对 URL 参数进行百分比编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我这样做

url = http://example.com?p=";+ urllib.quote(查询)

  1. 它不会将 / 编码为 %2F(破坏 OAuth 规范化)
  2. 它不处理 Unicode(它会引发异常)

有更好的图书馆吗?

解决方案

Python 2

来自文档:

urllib.quote(string[, safe])

<块引用>

替换字符串中的特殊字符使用 %xx 转义.字母、数字、并且字符 '_.-' 永远不会引.默认情况下,此功能是用于引用路径部分的 URL.可选的安全参数指定附加字符不应该被引用——它的默认值值为'/'

这意味着为 safe 传递 '' 将解决您的第一个问题:

<预><代码>>>>urllib.quote('/test')'/测试'>>>urllib.quote('/test', safe='')'%2Ftest'

关于第二个问题,有关于它的错误报告.显然它已在 Python 3 中修复.您可以通过编码为 UTF-8 来解决它像这样:

<预><代码>>>>查询 = urllib.quote(u"Müller".encode('utf8'))>>>打印 urllib.unquote(query).decode('utf8')米勒

顺便说一下,看看urlencode.

Python 3

相同,除了将 urllib.quote 替换为 urllib.parse.quote.

If I do

url = "http://example.com?p=" + urllib.quote(query)

  1. It doesn't encode / to %2F (breaks OAuth normalization)
  2. It doesn't handle Unicode (it throws an exception)

Is there a better library?

解决方案

Python 2

From the documentation:

urllib.quote(string[, safe])

Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-' are never quoted. By default, this function is intended for quoting the path section of the URL.The optional safe parameter specifies additional characters that should not be quoted — its default value is '/'

That means passing '' for safe will solve your first issue:

>>> urllib.quote('/test')
'/test'
>>> urllib.quote('/test', safe='')
'%2Ftest'

About the second issue, there is a bug report about it. Apparently it was fixed in Python 3. You can workaround it by encoding as UTF-8 like this:

>>> query = urllib.quote(u"Müller".encode('utf8'))
>>> print urllib.unquote(query).decode('utf8')
Müller

By the way, have a look at urlencode.

Python 3

The same, except replace urllib.quote with urllib.parse.quote.

这篇关于如何在 Python 中对 URL 参数进行百分比编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆