【问题标题】:python CSV module- Only getting one cell filledpython CSV模块-只填充一个单元格
【发布时间】:2015-12-02 21:50:06
【问题描述】:

我目前正在学校学习 python,并且一直在玩 BeautifulSoup,它非常简单。我现在正在尝试使用 python 的 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', "w") as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow([eateryName])

我正在获取所有餐厅名称(作为打印功能的证据),但是当我打开 Excel 文档时,它只有列表中的姓氏而不是所有名称。我试图附加eateryName,但随后它将所有名称放在一个单元格中。在此处输入代码

【问题讨论】:

  • 当你在 Python 中使用 csv 时,我建议你使用pandas。它会让你的生活更轻松。

标签: python csv beautifulsoup


【解决方案1】:

你可以试试这个:

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

【讨论】:

    【解决方案2】:

    您似乎正在尝试将整个列表写入 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])
    

    原因是您的写入在循环之外,因此您只写入最后一个条目,而您的写入只有“w”,它只覆盖而不追加。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-08
      • 1970-01-01
      • 2010-11-12
      • 2014-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多