本文介绍了“ascii"编解码器无法编码字符:序号不在范围内 (128)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm scraping some webpages using selenium and beautifulsoup. I'm iterating through a bunch of links, grabbing info, and then dumping it into a 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

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

The code breaks and I get the following error:

 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')

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

With no success. I believe it is the ï character on the link that is causing this to fail. Can anyone give a brief run-down of what's happening, what encode/decode means, and how to fix this issue? Thanks in advance.

推荐答案

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

You might need to set PYTHONIOENCODING before running your python script in the shell.For example, I got the same error while redirecting the python script output into a log file:

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

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

After changing PYTHONIOENCODING to UTF8 in the shell, script executed with no ASCII codec error:

$ export PYTHONIOENCODING=utf8

$ your_python_script > output.log

这篇关于“ascii"编解码器无法编码字符:序号不在范围内 (128)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 19:01