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

LA_*_*LA_ 3 python urlencode chinese-locale

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

params['username'] = user
params['q'] = q
params = urllib.quote(params)
Run Code Online (Sandbox Code Playgroud)

但是当q它等于时它不起作用??.返回以下错误:

'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

我该如何解决?

Kix*_*oms 5

看来你正在研究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)
Run Code Online (Sandbox Code Playgroud)