python CSV模块仅填充一个单元格

2024-09-27 00:20:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前在学校学习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,但它将所有名称放在一个单元格中。请在此处输入代码


Tags: csvimport名称url列表searchdataresponse
2条回答

您可以尝试以下方法:

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

似乎您正试图将整个列表写入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”,它只写入,不追加

相关问题 更多 >

    热门问题