如何对中文字符进行URL编码?

时间:2016-07-26 21:48:42

标签: python urlencode chinese-locale

我使用以下代码对参数列表进行编码:

params['username'] = user
params['q'] = q
params = urllib.quote(params)

但当q等于香港时,它无法正常工作。返回以下错误:

'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

我该如何解决?

1 个答案:

答案 0 :(得分:5)

您似乎正在使用Python 2 +。

因为你的问题不够明确,我提供了解决问题的正常方法。

以下是修复它的两个建议:

  • 在文件
  • 之前添加# encoding: utf-8
  • 在致电quote
  • 之前将中文字符编码为utf-8

以下是示例:

 # encoding: utf-8

import urllib


def to_utf8(text):
    if isinstance(text, unicode):
        # unicode to utf-8
        return text.encode('utf-8')
    try:
        # maybe utf-8
        return text.decode('utf-8').encode('utf-8')
    except UnicodeError:
        # gbk to utf-8
        return text.decode('gbk').encode('utf-8')


if __name__ == '__main__':
                # utf-8       # utf-8                   # unicode         # gdk
    for _text in ('香港', b'\xe9\xa6\x99\xe6\xb8\xaf', u'\u9999\u6e2f', b'\xcf\xe3\xb8\xdb'):
        _text = to_utf8(_text)
        print urllib.quote(_text)
相关问题