“ascii”编解码器无法编码字符:序号不在范围内 (128)

新手上路,请多包涵

我正在使用 selenium 和 beautifulsoup 抓取一些网页。我正在遍历一堆链接,获取信息,然后将其转储到 JSON 中:

 for event in events:

    case = {'Artist': item['Artist'], 'Date': item['Date'], 'Time': item['Time'], 'Venue': item['Venue'],
        'Address': item['Address'], 'Coordinates': item['Coordinates']}
    item[event] = case

with open("testScrape.json", "w") as writeJSON:
json.dump(item, writeJSON, ensure_ascii=False)

当我到达此链接时: https ://www.bandsintown.com/e/100778334-jean-deaux-music-at-rickshaw-stop?came_from=257&utm_medium=web&utm_source=home&utm_campaign=event

代码中断,我收到以下错误:

  Traceback (most recent call last):
  File "/Users/s/PycharmProjects/hi/BandsintownWebScraper.py", line 126, in <module>
    json.dump(item, writeJSON, ensure_ascii=False)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 190, in dump
    fp.write(chunk)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe6' in position 7: ordinal not in range(128)

我试过使用:

 json.dump(item, writeJSON, ensure_ascii=False).decode('utf-8')

和:

 json.dump(item, writeJSON, ensure_ascii=False).encode('utf-8')

没有成功。我相信是链接上的 ï 字符导致失败。任何人都可以简要介绍正在发生的事情、编码/解码的含义以及如何解决此问题吗?提前致谢。

原文由 DiamondJoe12 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 598
1 个回答

在 shell 中运行 python 脚本之前,您可能需要设置 PYTHONIOENCODING 。例如,我在将 python 脚本输出重定向到日志文件时遇到了同样的错误:

 $ your_python_script > output.log
'ascii' codec can't encode characters in position xxxxx-xxxxx: ordinal not in range(128)

在 shell 中将 PYTHONIOENCODING 更改为 UTF8 后,执行的脚本没有出现 ASCII 编解码器错误:

 $ export PYTHONIOENCODING=utf8

$ your_python_script > output.log

原文由 Noam Manos 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题