【问题标题】:beautifulsoup export to csvBeautifulsoup 导出到 csv
【发布时间】:2017-02-20 19:57:04
【问题描述】:

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

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']]

【问题讨论】:

  • 为什么要以二进制模式打开文件?无关,但您可以使用writer.writerows(data_mod)
  • 我不知道我正在以二进制打开 - 该行应该是什么? writer.writerows(data_mod) 仍然不允许我在单独的字段中加载到 csv;一切都进入第一列
  • "wb" b-> 二进制模式,你只需要wdata_mod 长什么样子?
  • 添加了一个示例输出行
  • 列表中的列表?

标签: python-2.7 csv beautifulsoup


【解决方案1】:

不要将行包装在列表中,您已经有一个列表列表。您还需要去除换行符,否则每一行都会得到它自己的行,而不是全部写在一行中并编码为 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)

【讨论】:

  • 我刚试过这个,我在写 csv 文件时得到UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128)
  • 编辑应该可以工作,你从哪里得到这些数据?您将 unicode、str 和整数混合在一起。
  • 我正在从网页上抓取它-tripadviser
  • 我看不出你怎么可能得到所有不同的类型,除非你手动更改它们,否则它们都应该是 unicode 字符串。 bs4 为您提供 unicode,因此您肯定会对其进行处理。
  • 是的,我改回了这个
猜你喜欢
  • 2021-03-23
  • 2020-09-05
  • 2018-02-12
  • 1970-01-01
  • 2014-03-07
  • 1970-01-01
  • 2021-06-24
  • 2020-12-12
  • 2017-08-12
相关资源
最近更新 更多