2015-12-02 34 views
0

我目前在學校學習python,並一直在玩BeautifulSoup,它一直非常簡單。我現在正嘗試使用python的csv模塊導出列表,但它不能按照我希望的方式運行。這裏是我的代碼: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但隨後它把所有的名字在一個cell.enter代碼在這裏

+0

當你在Python中使用csv時,我建議你使用'pandas'。它會讓你的生活更輕鬆。 – burhan

回答

0

你可以試試這個:

with open('csvnametest.csv', "w") as csv_file: 
    writer = csv.writer(csv_file) 
    for row in eateryName: 
     writer.writerow(row) 
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]) 

的原因是你寫的是外循環,所以你只寫了最後一個條目,和你寫只有「W」只寫一遍又犯規追加。

相關問題