如何URL对汉字进行编码?

How to URL encode Chinese characters?

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

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)

我该如何解决?

您似乎正在研究 Python 2+。

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

这里有两个修复它的建议:

  • 在你的文件前添加# encoding: utf-8
  • 调用前将汉字编码为utf-8 quote

示例如下:

 # 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)