python CSV模块 - 只填充一个单元格

时间:2015-12-02 21:50:06

标签: python csv beautifulsoup

我目前正在学校学习python并且一直在玩BeautifulSoup并且它非常直接。我现在正在尝试使用csv模块为python导出列表,但它没有按照我想要的方式运行。这是我的代码:

:3306

我得到了所有的餐馆名称(作为打印功能的证据)但是当我打开Excel文档时,它只是列表上的姓氏而不是所有的名字。我试图附加eateryName但是它将所有名称放在一个cell.enter代码中

2 个答案:

答案 0 :(得分:0)

你可以试试这个:

with open('csvnametest.csv', "w") as csv_file:
    writer = csv.writer(csv_file)
    for row in eateryName:
        writer.writerow(row)

答案 1 :(得分:0)

似乎你正在尝试将整个列表写入CSV。您应该执行以下操作:

import csv
import requests
from bs4 import BeautifulSoup
import pprint
import sys

url = 'http://www.yellowpages.com/search?search_terms=restaurants&geo_location_terms=Charleston%2C%20SC'
response = requests.get(url)
html = response.content

soup = BeautifulSoup(html, "html.parser")
g_data = soup.find_all("div", {"class": "info"}) #this isolates the big chunks of data which houses our child tags
for item in g_data: #iterates through big chunks    
    try:
        eateryName = (item.contents[0].find_all("a", {"class": "business-name"})[0].text)
    except:
        pass

    print(eateryName)
    with open('csvnametest.csv', "wa") as csv_file:
        writer = csv.writer(csv_file)
        writer.writerow([eateryName])

原因是你的写作在循环之外,所以你只写了最后一个条目,而你的写只有#34; w"只写过并且没有附加。