スクレイピングや機械学習で注目されているpythonがどこまで手軽にできるのか
ちょっと試してみた。
参考文献
PythonによるWebスクレイピング
O’REILLY
オライリー・ジャパン
システム要件
https://en.wikipedia.org/wiki/Comparison_of_text_editors
の最初に現れる表の内容を取得しCSVに保存する。
実装例
事前にBeautifulSoupをinstallすること。
コード:適当な名前で作成し、シェルから
python [作成したファイル名].py で実行する。
import csv
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen('https://en.wikipedia.org/wiki/Comparison_of_text_editors')
bs = BeautifulSoup(html, 'html.parser')
table = bs.findAll('table', {'class':'wikitable'})[0]
rows = table.findAll('tr') csvFile = open('editors.csv', 'wt+')
writer = csv.writer(csvFile)
try:
for row in rows:
csvRow = []
for cell in row.findAll(['td', 'th']):
csvRow.append(cell.get_text())
writer.writerow(csvRow)
finally:
csvFile.close()
実行結果
editors.csvが実行したプログラムと同じ場所へ書き出される。
Excel(2007以降)のデータ→外部データ取り込み→テキストファイル→インポートしてみるが、改行制御コードがどうやら怪しく
期待通りに取り込めなかった。
writerowメソッドで配列をテキストに変換してファイルへ追加してるので、ここらに何か起きている。
コード修正
テーブルセルの中に改行があったので取り除いたところ、ほぼ期待するCSVで出力されました。
import csv
from urllib.request import urlopen
from bs4 import BeautifulSoup
# 文末の改行を除去する
def cleanRN(str):
if str != None:
return str.rstrip('\r\n')
else:
return str
html = urlopen('https://en.wikipedia.org/wiki/Comparison_of_text_editors')
bs = BeautifulSoup(html, 'html.parser')
table = bs.findAll('table', {'class':'wikitable'})[0]
rows = table.findAll('tr')
csvFile = open('editors.csv', 'wt+', newline='')
writer = csv.writer(csvFile, dialect='excel') # dialect='excel'を追加
try:
for row in rows:
csvRow = []
for cell in row.findAll(['td', 'th']):
csvRow.append(cleanRN(cell.get_text()))
writer.writerow(csvRow)
finally:
csvFile.close()