【发布时间】:2019-09-29 22:38:51
【问题描述】:
我正在使用 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)
代码中断,我收到以下错误:
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')
没有成功。我相信这是导致此失败的链接上的 ï 字符。谁能简要介绍一下正在发生的事情、编码/解码的含义以及如何解决这个问题?提前致谢。
【问题讨论】:
-
这个错误可能意味着数据不是UTF-8,而是其他编码——即
Latin1、CP1250。 -
Python 将文本保存为 unicode - 这意味着每个字符甚至可以使用 8 个字节。为了发送或保存在文件中,它被转换(编码)为
utf-8、latin1等以使用更少的空间。编码字符可能使用 1 个字节,其他 2 个或更多字节 - 并且它使用更少的空间然后 8 个字节用于每个字符。当你得到它时,你必须将它转换(解码)回 unicode,以便 Python 可以使用它。 -
您没有显示完整的错误(Traceback),但我认为问题不在于这部分代码,而在于从网页获取数据的代码。也许您可能必须从页面解码数据。或者您可能需要在
open(..., encode='utf-8')中设置编码
标签: python json selenium utf-8 beautifulsoup