【问题标题】:UnicodeEncodeError Converting Requests Text to JSON in PythonUnicodeEncodeError 在 Python 中将请求文本转换为 JSON
【发布时间】:2020-05-20 10:12:53
【问题描述】:

我正在尝试抓取网站,但在某些搜索中它给了我错误:

File "C:\Users\user\AppData\Local\Programs\Python\Python37\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 5399-5400: character maps to <undefined>

我的 Python 脚本是:

import requests
import json

url = 'https://www.protocols.io/api/v3/protocols?filter=%20public%20&order_field=relevance&key=%20gel%22electrophoresis%20'

r = requests.get(url)
text = r.text 
jason = json.loads(text)
print (jason) 

我已尝试按照

建议的 here 更改编码
text = text.encode('utf-8') 

但仍然收到相同的错误。似乎使用的是 cp1252 编码而不是 utf-8?

任何建议将不胜感激!

更新: 这似乎是 git bash 或 atom 中的一个问题,因为在 Spyder 或 windows cmd 中没有错误

【问题讨论】:

    标签: python json web-scraping python-requests


    【解决方案1】:

    可能是因为你没有导入sys,

    像这样:

    import sys
    import codecs
    
    import requests
    import json
    
    url = 'https://www.protocols.io/api/v3/protocols?filter=%20public%20&order_field=relevance&key=%20gel%22electrophoresis%20'
    
    r = requests.get(url)
    text = r.text 
    text = text.encode('utf-8') 
    jason = json.loads(text)
    print (jason) 
    

    【讨论】:

    • 谢谢,但这似乎对我不起作用。我仍然得到同样的错误。你用的是什么版本的python(我是3.7.4)
    • python 3.6.4 我不认为是干扰的版本你如何运行代码?
    • 我使用这个在终端上运行我的:python3 pytest.py
    • 我刚刚更新到 3.8.3。我在 atom 文本编辑器中运行
    • 我在终端上运行,但仍然有同样的错误!你介意分享你的输出吗?
    【解决方案2】:

    我的输出: 如您所见,这是一个 json 项目

    【讨论】:

    • 谢谢。这很奇怪。我在 atom 和终端中运行我得到这个错误。我在 Spyder (python 3.7) 中运行,它可以工作,有什么想法吗?
    • 我将让它保持打开状态,因为我认为原始代码无需导入 sys 或编解码器即可工作,我需要一个适用于终端或 atom 的解决方案。感谢您的帮助
    猜你喜欢
    • 2021-08-19
    • 1970-01-01
    • 2020-11-01
    • 2013-05-17
    • 2020-06-12
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多