2017-02-03 14 views
0

このコードはオンラインであり、使用したいのですが、収集したデータをcsvファイルにエクスポートする方法が見つかりません。クロールからcsvファイルにデータをエクスポートしようとしています

import urllib 
import scrapy 
import json 
import csv 
from bs4 import BeautifulSoup 


url = "http://www.straitstimes.com/tags/malaysia-crimes" 

html = urllib.urlopen(url).read() 
soup = BeautifulSoup(html) 

# kill all script and style elements 
for script in soup(["script", "style"]): 
    script.extract() # rip it out 

# get text 
text = soup.body.get_text() 

# break into lines and remove leading and trailing space on each 
lines = (line.strip() for line in text.splitlines()) 
# break multi-headlines into a line each 
chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) 
# drop blank lines 
text = '\n'.join(chunk for chunk in chunks if chunk) 

print(text) 
+0

あなたが望む出力を投稿してください。 –

+0

ここで答えを見てください:http://stackoverflow.com/questions/41985454/how-to-export-data-from-a-beautifulsoup-scrape-to-a-csv-file それは非常に似ています問題と答えはあなたを助けることができます。 –

+0

[csvファイルにcleansoupスクレープからデータをエクスポートする方法]の可能な複製(http://stackoverflow.com/questions/41985454/how-to-export-data-from-a-beautifulsoup-scrape-to-a -csv-file) –

答えて

0

以下は、私はあなたが望む信じるもののために働くように見えます:

私は、作成への書き込みやブックを保存するためにxlwtパッケージを使用して、テキストや書き込みの各ラインを通過するループそれをブックに送ってください。私はtesting.csvとして保存しました

import urllib 
import scrapy 
import json 
import csv 
from bs4 import BeautifulSoup 
from xlwt import Workbook 


url = "http://www.straitstimes.com/tags/malaysia-crimes" 

html = urllib.urlopen(url).read() 
soup = BeautifulSoup(html) 

# create excel workbook 
wb = Workbook() 
sheet1 = wb.add_sheet('Sheet 1') 

# kill all script and style elements 
for script in soup(["script", "style"]): 
    script.extract() # rip it out 

# get text 
text = soup.body.get_text() 

# break into lines and remove leading and trailing space on each 
lines = (line.strip() for line in text.splitlines()) 
# break multi-headlines into a line each 
chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) 
# drop blank lines 
text = '\n'.join(chunk for chunk in chunks if chunk) 

print(text) 

# go through each line and print to a new row in excel 
counter = 1 
for text_to_write in text.splitlines(): 
    sheet1.write(counter,1,text_to_write) 
    counter = counter + 1 

wb.save('testing.csv') 
関連する問題