dtr*_*inh 7 python web-scraping python-2.7 python-unicode
我想从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)
Run Code Online (Sandbox Code Playgroud)
我尝试了一些我在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
Run Code Online (Sandbox Code Playgroud)
Lau*_*RTE 12
该rest_array包含unicode字符串.当您使用csv.writer写行时,需要序列化字节字符串(您使用的是Python 2.7).
我建议你使用"utf8"编码:
with open('ListingsPull-Amsterdam.csv', mode='a') as fd:
writer = csv.writer(fd)
rest_array = [text.encode("utf8") for text in rest_array]
writer.writerow(rest_array)
Run Code Online (Sandbox Code Playgroud)
注意:请不要使用file变量,因为你影响了内置函数file()(函数的别名open()).
如果要使用Microsoft Excel打开此CSV文件,可以考虑使用其他编码,例如"cp1252"(它允许使用"\ u2019"字符).
| 归档时间: |
|
| 查看次数: |
21017 次 |
| 最近记录: |