[英]Moving scraped data using BeautifulSoup to csv
能夠將使用BeautifulSoup抓取的數據移動到CSV文件中似乎很關鍵。 我快要成功了,但是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")
將#Move移至csv文件:For循環中的一部分。
同樣在這里似乎您也在for循環內覆蓋了winner_category。 采取其他一些變量可能是一個更好的主意。
像(未經測試的)這樣的東西應該有所幫助
#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()
問題在於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
模塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.