【问题标题】:non 'ascii' characters in requests response请求响应中的非“ascii”字符
【发布时间】:2017-10-19 04:26:27
【问题描述】:

我使用请求从 API 源获取 json 数据

req = requests.get('url')
context = json.loads(req.text)
print(context)

返回错误

UnicodeEncodeError at /view/
'ascii' codec can't encode characters in position 26018-26019: ordinal not in range(128)
Unicode error hint

The string that could not be encoded/decoded was: OLYURÉTHANE

我检查了req.text 并没有找到非ascii 字符。出现在json.loads(..)之后

【问题讨论】:

  • 符号 É 不是 ascii sysmbol。 Acii character list
  • 我知道。如何忽略它或某种
  • 您可以捕获异常并忽略它或检查字符串的每个字符的ord()是否小于128,如果您仍然需要处理文本,则忽略这些字符。

标签: python python-3.x unicode python-requests


【解决方案1】:

试试这个:

request_txt = req.text.encode('utf-8')
context = json.loads(request_txt)

您需要将.encode('utf-8') 应用于引发此错误的字符串。

【讨论】:

    【解决方案2】:

    尝试类似@Maninder 写的,但不是encode() 使用decode()

    context = json.loads(req.text.decode("utf8"))
    

    【讨论】:

      猜你喜欢
      • 2019-04-29
      • 2014-06-20
      • 1970-01-01
      • 2011-02-18
      • 1970-01-01
      • 2018-10-13
      • 2014-06-12
      • 2012-01-23
      • 2010-10-18
      相关资源
      最近更新 更多