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

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

问题描述

如果我执行

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




  1. 它不编码 / %2F (打破OAuth规范化)

  2. 它不处理Unicode(它抛出异常)

有更好的图书馆吗?

解决方案>

文档

  urllib.quote(string [,safe])




使用%xx转义替换字符串
中的特殊字符。字母,数字,
和字符_.-永远不会
引用。默认情况下,此函数是
,用于引用URL的路径部分
。可选的安全参数
指定不应引用
的其他字符 - 其默认值
值是'/'


这意味着传递为了安全可以解决你的第一个问题: / p>

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

关于第二个问题,有关于它的错误报告 here 。显然它已经在python 3中被修复了。你可以通过如下这样编码为utf8来解决它:

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

由看看 urlencode


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?

解决方案

From the docs:

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 here. Apparently it was fixed in python 3. You can workaround it by encoding as utf8 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中对URL参数进行百分比编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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