我不完全确定我需要对这个错误做些什么。我认为这与需要添加.encode('utf-8')有关。但我不完全确定这是否是我需要做的,也不知道我应该在哪里应用。
错误是:
line 40, in <module>
writer.writerows(list_of_rows)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 1
7: ordinal not in range(128)
这是我的python脚本的基础。
import csv
from BeautifulSoup import BeautifulSoup
url = \
'https://dummysite'
response = requests.get(url)
html = response.content
soup = BeautifulSoup(html)
table = soup.find('table', {'class': 'table'})
list_of_rows = []
for row in table.findAll('tr')[1:]:
list_of_cells = []
for cell in row.findAll('td'):
text = cell.text.replace('[','').replace(']','')
list_of_cells.append(text)
list_of_rows.append(list_of_cells)
outfile = open("./test.csv", "wb")
writer = csv.writer(outfile)
writer.writerow(["Name", "Location"])
writer.writerows(list_of_rows)
除了Alastair的优秀建议之外,我发现最简单的选择是使用python3而不是python 2。我的脚本所需要的只是将
open
语句中的wb
更改为accordance with Python3's syntax中的w
。Python 2.x CSV库已损坏。你有三个选择。按复杂程度排序:
编辑:请参见下面的
使用固定库https://github.com/jdunck/python-unicodecsv(pip install unicodecsv
)。作为替换品使用-示例:阅读有关Unicode的CSV手册:https://docs.python.org/2/library/csv.html(请参阅底部的示例)
手动将每个项目编码为UTF-8:
编辑,我发现python unicodecsv在读取UTF-16时也断了。它抱怨任何
0x00
字节。相反,使用https://github.com/ryanhiebert/backports.csv,它更类似于Python 3实现,使用
io
模块。。安装:
用法:
相关问题 更多 >
编程相关推荐