1
私は、テキストマイニングの目的でいくつかの記事を含むデータベースを作成しようとしています。 私はウェブスクレイピングで本文を抽出し、これらの記事の本文をcsvファイルに保存します。しかし、私はすべての本文を保存することができませんでした。 私が思いついたコードは、最後のURL(記事)のテキストのみを保存しますが、私が掻いているもの(そして私が保存するもの)を印刷すると、すべての記事の本文が取得されます。csvファイルに本文テキストを保存する| Python 3
import requests
from bs4 import BeautifulSoup
import csv
r=["http://www.nytimes.com/2016/10/12/world/europe/germany-arrest-syrian-refugee.html",
"http://www.nytimes.com/2013/06/16/magazine/the-effort-to-stop-the- attack.html",
"http://www.nytimes.com/2016/10/06/world/europe/police-brussels-knife-terrorism.html",
"http://www.nytimes.com/2016/08/23/world/europe/france-terrorist-attacks.html",
"http://www.nytimes.com/interactive/2016/09/09/us/document-Review-of-the-San-Bernardino-Terrorist-Shooting.html",
]
for url in r:
t= requests.get(url)
t.encoding = "ISO-8859-1"
soup = BeautifulSoup(t.content, 'lxml')
text = soup.find_all(("p",{"class": "story-body-text story-content"}))
print(text)
with open('newdb30.csv', 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)
spamwriter.writerow(text)
TypeError:リストに連結できるのは "str"ではなく、リストのみです。だから私はstr(テキスト)+ "\ r \ n"で編集します。そして、それが今働いているように見えますが、出力は次のようなものです:d " - t o t a l - c ou t t =" 6 5 5 2 "> M r。 | | | |私は| | | | | | w h e n | | - | | o r | | e v e n | | i f |どのように読みやすくするためのヒント? –
forループの前に 'all_text = []'や 'all_text =" "'を実行しましたか?それは秒でなければなりません。 – yper
私は提案されたall_text = ""として2番目を使いました。 str(text)を追加することでエラーを解決しますが、出力を読みにくくしています。 –