【问题标题】:UnicodeEncodeError: 'ascii' codec can't encode characters in position 90-96: ordinal not in range(128)UnicodeEncodeError:“ascii”编解码器无法对位置 90-96 中的字符进行编码:序数不在范围内(128)
【发布时间】:2023-03-27 05:49:01
【问题描述】:

我有这个代码:

url= 'https://yandex.ru/search/xml?user=uid-2h3232xfhboy&key=03.292922330523:6b4c80ghghghhghgdsfdsfds4c4b4a7872fb7d2bb04bfdgbb02b76c3d&query='
key = "абс"
 url = url + key
        print(url)
        xml = urllib.request.urlopen(url).read()

但我得到一个错误:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 90-96: ordinal not in range(128)

我该怎么办?

我试着做url= url.encode("utf-8") 但没有帮助。收到此错误:

AttributeError: 'bytes' 对象没有属性 'timeout'

我尝试这样做: url = u''.join((self.ya_url, key)).encode('utf-8') 如此处建议:UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

但遇到同样的错误

AttributeError: 'bytes' 对象没有属性 'timeout'

我该怎么办?

【问题讨论】:

  • 您是否经历过与此非常相似的其他问答? (请参阅“相关”侧边栏。)
  • @glibdud 是的,我已经完成了一些与此非常相似的问答(请参阅问题的最后 3 段)
  • 有关AttributeError 的说明,请参阅this question

标签: python python-3.x


【解决方案1】:

您不能在 URL 中使用非 ASCII 字符。您需要适当地引用您的 key 值:

import urllib.parse

url= 'https://yandex.ru/search/xml?user=uid-2h3232xfhboy&key=03.292922330523:6b4c80ghghghhghgdsfdsfds4c4b4a7872fb7d2bb04bfdgbb02b76c3d&query='
key = "абс"
quoted = urllib.parse.quote(key)
url = url + quoted

【讨论】:

    【解决方案2】:

    这种方法对我有用(我使用 Pycharm ide)。你去 client.py ,然后将 request.encode('ascii') 更改为 request.encode('utf-8) 或任何你想要的编码器。现在应该没问题了

    编辑:您需要更改源文件才能在 url 中使用 utf 字符。在 request.encode 中,一直是硬编码 ascii

    【讨论】:

      猜你喜欢
      • 2012-08-05
      • 2020-07-27
      • 2012-07-17
      • 2018-04-28
      • 2014-03-08
      • 2015-09-26
      • 2017-02-28
      • 1970-01-01
      相关资源
      最近更新 更多