BeautifulSoup csv中的逗号

时间:2016-10-11 09:22:09

标签: python csv beautifulsoup

我正在尝试将一些网页抓取信息输出到csv。当我将它打印到屏幕时,它会像我期望的那样出现,但是当我输出到csv时,它在每个角色之间都有逗号。我很笨,但我错过了什么?

这是我的相关python代码:

list_of_rows = []
for hotel in hotels:
    for row in hotel.findAll('div', attrs={'class': 'listing_title'}):
        list_of_rows.append(row.find('a').text.replace('\nspb;', ''))

print(list_of_rows)
outfile = open("./hotels.csv", "wb")
writer = csv.writer(outfile)
writer.writerows(list_of_rows)
outfile.close()

编辑:添加了示例输出

打印时,list_of_rows出现如下:

  

[u“130 Queen's Gate”,u'Hotel 41',u'Egerton House Hotel',u'The   Milestone Hotel',u'The Beaumont',u'COMO The Halkin',u'Taj 51   白金汉门套房和住宅',你在蒙塔古   花园'','Goring',u'Haymarket Hotel',u'Amba Hotel Charing   Cross',u'Rosewood London',u'Covent Garden Hotel',u'The Connaught',   你是切斯特菲尔德梅菲尔','蒙特卡姆伦敦大理石拱门',   u'Corinthia Hotel London',u'The Soho Hotel',u'Four Seasons Hotel   伦敦公园巷','Nadler Soho',u'Charlotte Street Hotel',   u'The Ritz London',u'The Nadler Victoria',u'Bulgari Hotel,London',   你是“布朗的酒店”,“伦敦拱门”,“伦敦西部的皮卡迪利”   结束',你'Stafford London',u'Ham Yard Hotel',u'Sofitel London St.   James',u'Staybridge Suites London - Vauxhall']

但是当发送到csv时,每个字母/空格之间都有一个逗号。

1 个答案:

答案 0 :(得分:0)

您应该将数据作为嵌套列表提供,其中每个子列表代表一行。

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)

# With writerows() being equivalent to the for loop + writerow()
相关问题