我正试图从 TripAdvisor 拉出阿姆斯特丹 500 家餐厅的名单;然而,在第 308 家餐厅之后,我收到以下错误:
Traceback (most recent call last):
File "C:/Users/dtrinh/PycharmProjects/TripAdvisorData/LinkPull-HK.py", line 43, in <module>
writer.writerow(rest_array)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 6: ordinal not in range(128)
我尝试了一些在 StackOverflow 上找到的东西,但目前没有任何效果。我想知道是否有人可以看一下我的代码,看看是否有任何潜在的很棒的解决方案。
for item in soup2.findAll('div', attrs={'class', 'title'}):
if 'Cuisine' in item.text:
item.text.strip()
content = item.findNext('div', attrs=('class', 'content'))
cuisine_type = content.text.encode('utf8', 'ignore').strip().split(r'\xa0')
rest_array = [account_name, rest_address, postcode, phonenumber, cuisine_type]
#print rest_array
with open('ListingsPull-Amsterdam.csv', 'a') as file:
writer = csv.writer(file)
writer.writerow(rest_array)
break
原文由 dtrinh 发布,翻译遵循 CC BY-SA 4.0 许可协议
rest_array
包含 unicode 字符串。当您使用csv.writer
写入行时,您需要序列化字节字符串(您使用的是 Python 2.7)。我建议你使用“utf8”编码:
注意:请不要使用
file
作为变量,因为你隐藏了内置函数file()
(open()
e638ee8382dae412956bd506bf70-cfunction388- 的别名)。如果您想使用 Microsoft Excel 打开此 CSV 文件,您可以考虑使用其他编码,例如“cp1252”(它允许 u”\u2019” 字符)。