2017-02-01 21 views
0

このコードはオンラインで見つかり、収集したデータをcsvファイルにエクスポートする方法が不思議でした。beautifulsoup scrapeからcsvファイルにデータをエクスポートする方法

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

url = "http://www.thestar.com.my/news/nation/" –

+0

あなたのサンプルは、見つかったすべてのテキストを一括して返すだけなので、決して構造化されていません。それをCSV列で整列させることは意味がありません。ウェブページの特定の部分に興味がある可能性があります(たとえば、ニュースエントリのみ)。あなたはそのテキストだけを抽出するためにスープを使用する必要があり、それをCSVにすることができます。 –

答えて

1

コードは、指定されたURLからすべてのテキストを抽出しただけです。これは構造を失い、開始したいテキストと終了するテキストを決定するのが非常に困難になります。

あなたが指定したページでは、たとえば、HTMLソースを見て、すべての見出しを抽出し、5つのストーリーがすべて固有のHTML IDを持つことを確認することができます。あなたはsoup()を使ってこれらを見つけ出し、そこからテキストを抽出することができます。これで各記事の見出しと要約が作成され、CSVファイルに書き込むことができました。以下は、Python 3.5.2を使用してテストされています。

from urllib.request import urlopen 
from bs4 import BeautifulSoup 
import csv 

html = urlopen("http://www.thestar.com.my/news/nation/") 
soup = BeautifulSoup(html, "html.parser") 

# IDs found by looking at the HTML source in a browser 
ids = [ 
    "slcontent3_3_ileft_0_hlFirstStory", 
    "slcontent3_3_ileft_0_hlSecondStory", 
    "slcontent3_3_ileft_0_lvStoriesRight_ctrl0_hlStoryRight", 
    "slcontent3_3_ileft_0_lvStoriesRight_ctrl1_hlStoryRight", 
    "slcontent3_3_ileft_0_lvStoriesRight_ctrl2_hlStoryRight"] 

with open("news.csv", "w", newline="", encoding='utf-8') as f_news: 
    csv_news = csv.writer(f_news) 
    csv_news.writerow(["Headline", "Summary"]) 

    for id in ids: 
     headline = soup.find("a", id=id) 
     summary = headline.find_next("p") 
     csv_news.writerow([headline.text, summary.text]) 

次のようにあなたのCSVファイルを与えることになる:あなたはそれを持っているURLに依存する

Headline,Summary 
Many say convicted serial rapist Selva still considered âa person of high riskâ,PETALING JAYA: Convicted serial rapist Selva Kumar Subbiah will be back in the country from Canada in three days and a policeman who knows him says there is no guarantee that he will not strike again. 
Liow: Way too many road accidents,"PETALING JAYA: Road accidents took the lives of 7,152 and incurred a loss of about RM9.2bil in Malaysia last year, says Datuk Seri Liow Tiong Lai." 
Ex-civil servant wins RM27.4mil jackpot,PETALING JAYA: It was the ang pow of his life. 
"Despite latest regulation, many still puff away openly at parks and R&R;","KUALA LUMPUR: It was another cloudy afternoon when office workers hung out at the popular KLCC park, puffing away at the end of lunch hour, oblivious to the smoking ban there." 
Police warn groups not to cause disturbances on Thaipusam,GEORGE TOWN: Police have warned supporters of the golden and silver chariots against provo­king each other during the Thaipusam celebration next week. 
+0

ありがとう、それは完全に動作します。 –

+0

よかった、あなたが必要としてくれたことをうれしく思いました。上下の矢印の下にある灰色のチェックマークをクリックすることを忘れないでください。 –

関連する問題