2014-04-06 53 views
1

將您使用BeautifulSoup抓取的數據移動到CSV文件中似乎至關重要。我接近成功,但不知何故CSV文件中的每一列都是來自刮取信息的一個字母,並且它只是移動最後一個項目刮擦。使用BeautifulSoup將刮取的數據移動到csv

這裏是我的代碼:

import urllib2 
import csv 
from bs4 import BeautifulSoup 
url = "http://www.chicagoreader.com/chicago/BestOf?category=4053660&year=2013" 
page = urllib2.urlopen(url) 
soup_package = BeautifulSoup(page) 
page.close() 

#find everything in the div class="bestOfItem). This works. 
all_categories = soup_package.findAll("div",class_="bestOfItem") 
print(winner_category) #print out all winner categories to see if working 

#grab just the text in a tag: 
for match_categories in all_categories: 
    winner_category = match_categories.a.string 

#Move to csv file: 
f = file("file.csv", 'a') 
csv_writer = csv.writer(f) 
csv_writer.writerow(winner_category) 
print("Check your dropbox for file") 

回答

0

的問題是,writerow()預計可迭代。在你的情況下,它會收到一個字符串並將其分成單獨的字符。將每個值放入列表中。

此外,您需要在循環中執行此操作。

此外,您可以將urllib2.urlopen(url)直接傳遞給BeautifulSoup構造函數。

此外,您應該在使用文件時使用with上下文管理器。

下面是經過修改的代碼:運行腳本後

import urllib2 
import csv 
from bs4 import BeautifulSoup 


url = "http://www.chicagoreader.com/chicago/BestOf?category=4053660&year=2013" 
soup_package = BeautifulSoup(urllib2.urlopen(url)) 
all_categories = soup_package.find_all("div", class_="bestOfItem") 

with open("file.csv", 'w') as f: 
    csv_writer = csv.writer(f) 
    for match_categories in all_categories: 
     value = match_categories.a.string 
     if value: 
      csv_writer.writerow([value.encode('utf-8')]) 

file.csv的內容是:

Best View From a Performance Space 
Best Amateur Hip-Hop Dancer Who's Also a Professional Wrestler 
Best Dance Venue in New Digs 
Best Outré Dance 
Best (and Most Vocal) Mime 
Best Performance in a Fat Suit 
Best Theatrical Use of Unruly Facial Hair 
... 

除此之外,我不知道你需要csv模塊在所有。

+0

Thx。任何關於我可以在哪裏學習這個細節的建議。我在谷歌搜索等方面拼湊在一起。 – user1922698

+0

@ user1922698好吧,有多種資源。 [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/bs4/doc/)文檔,[csv](https://docs.python.org/2/library/csv.html)模塊文檔。另外,請在您感興趣的標籤中查看SO中最常見的問題。希望有所幫助。 – alecxe

0

移動的#Move到CSV文件:在for循環的一部分。

另外這裏似乎你也覆蓋winner_category裏面for循環。採取其他變量可能是一個更好的主意。

喜歡的東西(未經測試)應該幫助

#grab just the text in a tag: 
f = file("file.csv", 'a') 

for match_categories in all_categories: 
    fwinner = match_categories.a.string 

    #Move to csv file: 
    csv_writer = csv.writer(f) 
    csv_writer.writerow(fwinner) 
    print("Check your dropbox for file") 
f.close()