'ascii'编解码器无法编码字符:序数不在范围内(128) [英] 'ascii' codec can't encode character : ordinal not in range (128)

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

问题描述

我正在使用硒和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)

当我访问此链接时:代码中断,出现以下错误:

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 ,然后在外壳中运行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)

在外壳中将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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆