'ascii'编解码器无法编码字符:序数不在范围内(128)

Dia*_*e12 0 python selenium json beautifulsoup utf-8

我正在使用硒和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)
Run Code Online (Sandbox Code Playgroud)

当我到达此链接时: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)
Run Code Online (Sandbox Code Playgroud)

我尝试使用:

json.dump(item, writeJSON, ensure_ascii=False).decode('utf-8')
Run Code Online (Sandbox Code Playgroud)

和:

json.dump(item, writeJSON, ensure_ascii=False).encode('utf-8')
Run Code Online (Sandbox Code Playgroud)

没有成功。我相信是链接的ï字符导致此操作失败。谁能简要介绍一下正在发生的事情,编码/解码的含义以及如何解决此问题?提前致谢。

Noa*_*nos 10

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

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

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

$ export PYTHONIOENCODING=utf8

$ your_python_script > output.log
Run Code Online (Sandbox Code Playgroud)


dus*_*uff 5

您的问题是,在Python 2中,一个file对象(由返回open())只能写入str对象,而不能写入unicode对象。传递ensure_ascii=Falsejson.dump()会尝试将Unicode字符串直接作为unicode对象写入文件,这将失败。

json.dump(item, writeJSON, ensure_ascii=False).encode('utf-8')
Run Code Online (Sandbox Code Playgroud)

此尝试的修复不起作用,因为json.dump()它不返回任何内容。而是直接将内容写入文件。(如果中没有Unicode文本item,则在json.dump()完成后会崩溃- json.dump()返回None,无法对其进行.encode()调用。)

解决此问题的方法有三种:

  1. 使用Python3。str和Python 3的统一unicode使您现有的代码保持原样运行。无需更改代码。

  2. ensure_ascii=False从您的通话中删除json.dump。非ASCII字符将以转义的形式写入文件-例如,ï将写入\u00ef。这是表示Unicode字符的一种完全有效的方法,大多数JSON库都可以很好地处理它。

  3. file对象包装为UTF-8 StreamWriter

    import codecs
    with codecs.getwriter("utf8")(open("testScrape.json", "w")) as writeJSON:
        json.dump(item, writeJSON, ensure_ascii=False)
    
    Run Code Online (Sandbox Code Playgroud)