UnicodeDecode Error: decoding when writing to xls(x) related to non-english characters
UnicodeDecode Error: decoding when writing to xls(x) related to non-english characters
我已经用尽了我的搜索来试图弄清楚从这里去哪里,所以希望得到一些关于可能的后续步骤的建议,甚至是更好的选择。
概要:我正在使用 python 从网站抓取结果,然后将该数据写入 xls(x) 文档。我选择 xls(x) 而不是 csv,因为我的 csv 在保存时一直在处理非英语字符。
我已经成功地 运行 在英文页面上编写了这段代码,但是一旦我遇到非英文字符,它就会在 write() 上抛出以下错误。
请注意,我也尝试过 string.decode('utf-8')
,但会引发“'ascii' 编解码器无法编码字符”错误。
问题:我需要做什么才能将这些正确写入 xls(x)?我已经能够在没有 CSV 问题的情况下执行此操作,但正如我所提到的,保存它会破坏格式。我是否需要对其进行不同的编码以便 write() 函数正确传输它?
对于下面的代码,我导入了 scrapy、codecs、xlsxwriter (Workbook) 和其他一些代码。
# set xpaths:
item_1 = 'xpath'
item_2 = 'xpath'
item_3 = 'xpath'
item_4 = 'xpath'
pagination_lookup = {}
results = []
def write_to_excel(list_of_dicts,filename):
filename = filename + '.xlsx'
ordered_list = list(set().union(*(d.keys() for d in list_of_dicts))) # OR set up as actual list of keys (e.g. ['Listing Title','Item Price', etc.])
wb=Workbook(filename)
ws=wb.add_worksheet("Sheet 1") #or leave it blank, default name is "Sheet 1"
first_row=0
for header in ordered_list:
col=ordered_list.index(header) # to keep order
ws.write(first_row,col,header) # to write first row/header
row=1
for each_dict in list_of_dicts:
for _key,_value in each_dict.items():
col=ordered_list.index(_key)
ws.write(row,col,_value)
row+=1 #enter the next row
wb.close()
name = 'Scraper'
# AREA FOR CODE TO GATHER AND SCRAPE URLS (taken out for brevity)
driver.get(clean_url)
time.sleep(2)
selectable_page = Selector(text=driver.page_source)
ResultsDict = {}
ResultsDict['item_1'] = selectable_page.xpath(item_1).extract_first().encode('utf-8')
ResultsDict['item_2'] = selectable_page.xpath(item_2).extract_first().encode('utf-8')
ResultsDict['item_3'] = selectable_page.xpath(item_3).extract_first().encode('utf-8')
ResultsDict['item_4'] = selectable_page.xpath(item_4).extract_first().encode('utf-8')
results.append(ResultsDict)
print ResultsDict
write_to_excel(results,'Scraped_results')
代码 运行 因该错误而搁浅,该错误由具有任何非英语字符(例如 ñ、ô、ä 等)的值触发
Traceback (most recent call last): File
"/Users/name/scraper1/scraper1/spiders/scraped_results.py", line 128,
in
write_to_excel(results,'Scraped_results')
[...]
File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/codecs.py",
line 369, in write
data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 39: ordinal not in range(128)
问题:我需要做什么才能将这些正确写入 xls(x)?我已经能够在没有 CSV 问题的情况下执行此操作,但正如我所提到的,保存它会破坏格式。我是否需要对其进行不同的编码以便 write() 函数正确传输它?
我猜你正在使用 Python 2.x,当你将字节字符串传递给需要 Unicode 字符串的东西时,它会尝试为你做一个 decode
.不幸的是,这几乎没有做正确的事情,这就是为什么他们在 Python 3.
中删除了该功能
您正在通过在抓取中使用 .encode('utf-8')
创建字节字符串。将其关闭并将 Unicode 字符串传递给 write_to_excel
。
简单的解决方案:
switch to python 3.6+
我已经用尽了我的搜索来试图弄清楚从这里去哪里,所以希望得到一些关于可能的后续步骤的建议,甚至是更好的选择。
概要:我正在使用 python 从网站抓取结果,然后将该数据写入 xls(x) 文档。我选择 xls(x) 而不是 csv,因为我的 csv 在保存时一直在处理非英语字符。
我已经成功地 运行 在英文页面上编写了这段代码,但是一旦我遇到非英文字符,它就会在 write() 上抛出以下错误。
请注意,我也尝试过 string.decode('utf-8')
,但会引发“'ascii' 编解码器无法编码字符”错误。
问题:我需要做什么才能将这些正确写入 xls(x)?我已经能够在没有 CSV 问题的情况下执行此操作,但正如我所提到的,保存它会破坏格式。我是否需要对其进行不同的编码以便 write() 函数正确传输它?
对于下面的代码,我导入了 scrapy、codecs、xlsxwriter (Workbook) 和其他一些代码。
# set xpaths:
item_1 = 'xpath'
item_2 = 'xpath'
item_3 = 'xpath'
item_4 = 'xpath'
pagination_lookup = {}
results = []
def write_to_excel(list_of_dicts,filename):
filename = filename + '.xlsx'
ordered_list = list(set().union(*(d.keys() for d in list_of_dicts))) # OR set up as actual list of keys (e.g. ['Listing Title','Item Price', etc.])
wb=Workbook(filename)
ws=wb.add_worksheet("Sheet 1") #or leave it blank, default name is "Sheet 1"
first_row=0
for header in ordered_list:
col=ordered_list.index(header) # to keep order
ws.write(first_row,col,header) # to write first row/header
row=1
for each_dict in list_of_dicts:
for _key,_value in each_dict.items():
col=ordered_list.index(_key)
ws.write(row,col,_value)
row+=1 #enter the next row
wb.close()
name = 'Scraper'
# AREA FOR CODE TO GATHER AND SCRAPE URLS (taken out for brevity)
driver.get(clean_url)
time.sleep(2)
selectable_page = Selector(text=driver.page_source)
ResultsDict = {}
ResultsDict['item_1'] = selectable_page.xpath(item_1).extract_first().encode('utf-8')
ResultsDict['item_2'] = selectable_page.xpath(item_2).extract_first().encode('utf-8')
ResultsDict['item_3'] = selectable_page.xpath(item_3).extract_first().encode('utf-8')
ResultsDict['item_4'] = selectable_page.xpath(item_4).extract_first().encode('utf-8')
results.append(ResultsDict)
print ResultsDict
write_to_excel(results,'Scraped_results')
代码 运行 因该错误而搁浅,该错误由具有任何非英语字符(例如 ñ、ô、ä 等)的值触发
Traceback (most recent call last): File "/Users/name/scraper1/scraper1/spiders/scraped_results.py", line 128, in write_to_excel(results,'Scraped_results') [...] File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/codecs.py", line 369, in write data, consumed = self.encode(object, self.errors) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 39: ordinal not in range(128)
问题:我需要做什么才能将这些正确写入 xls(x)?我已经能够在没有 CSV 问题的情况下执行此操作,但正如我所提到的,保存它会破坏格式。我是否需要对其进行不同的编码以便 write() 函数正确传输它?
我猜你正在使用 Python 2.x,当你将字节字符串传递给需要 Unicode 字符串的东西时,它会尝试为你做一个 decode
.不幸的是,这几乎没有做正确的事情,这就是为什么他们在 Python 3.
您正在通过在抓取中使用 .encode('utf-8')
创建字节字符串。将其关闭并将 Unicode 字符串传递给 write_to_excel
。
简单的解决方案:
switch to python 3.6+