问题:beautifulsoup 导出到 csv

我正在从字段中捕获数据并将其存储为

data.append(newdata)

然后将每个完整记录存储为:

list_of_rows.append(data)

然后我试图保存到 csv

data_mod = [[item] for item in list_of_rows]

with open("./hotels.csv", "wb") as outfile:
    writer = csv.writer(outfile)
    for row in data_mod:
        writer.writerow(row)
outfile.close()

但是当我将它加载到 csv 中时,所有内容都会保存到第一个字段中。如何正确分解?

编辑

每行看起来像

[[u'Staybridge Suites London - Vauxhall', '\nTushar K\n', '\nIlford\n', 0, u'2 reviews', '5 of 5 stars', '29 September 2016', u'\nHome comes at staybridge........it nice with stay bridge.....awesome ambiance, kitchen, rooms, break fast area.............\nEverything is at place.....\nTalking about people of stay bridge... they all are very much cooperative, kind, best service people I have ever saw, meet...... its absolutely fantastic with stay bridge..........love u guysss.....\n']]

解答

不要将行包装在列表中,您已经有一个列表列表。您还需要删除换行符,否则每一行都会得到它自己的行,而不是写在一行中并编码为 utf-8:

with open("./hotels.csv", "w") as outfile:
    writer = csv.writer(outfile)
    writer.writerows([s.strip().encode("utf-8") if isinstance(s, unicode) else s
                     for s in row] for row in list_of_rows)
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐