UnicodeEncodeError:“ascii”编解码器无法对位置6中的字符u“\u2019”进行编码:序号不在范围(128)内

2024-06-01 11:11:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从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

Tags: textindivrestcontentitemarray餐厅
1条回答
网友
1楼 · 发布于 2024-06-01 11:11:54

您正在将非ascii字符写入csv输出文件。确保使用允许对字符进行编码的适当字符编码打开输出文件。安全的赌注通常是UTF-8。试试这个:

with open('ListingsPull-Amsterdam.csv', 'a', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerow(rest_array)

编辑这是针对Python 3.x的,抱歉。

相关问题 更多 >