Pythonモジュール「BeautifulSoup」でWebスクレイピングでTable(表)のデータをCSVに保存する方法についてまとめました。
## 【BeautifulSou】Table(表)のデータをCSVに保存
Pythonモジュール「BeautifulSoup」でWebスクレイピングでTable(表)のデータをCSVに保存します。
■対象の表(classがtest)
名前 | HP | ATK |
---|---|---|
セイバー | 15600 | 14580 |
アーチャー | 13630 | 12580 |
ランサー | 14510 | 15580 |
## サンプルコード
サンプルプログラムのソースコードです。
# -*- coding: utf-8 -*- import csv from urllib.request import urlopen from bs4 import BeautifulSoup def table_to_csv(file_path, url, selecter): html = urlopen(url) soup = BeautifulSoup(html, "html.parser") # セレクタ(タグ:table、クラス:test) table = soup.findAll("table", selecter)[0] trs = table.findAll("tr") # ファイルオープン csv_file = open(file_path, 'wt', newline = '', encoding = 'utf-8') csv_write = csv.writer(csv_file) for tr in trs: csv_data = [] # 1行ごとにtd, tr要素のデータを取得してCSVに書き込み for cell in tr.findAll(['td', 'th']): csv_data.append(cell.get_text()) csv_write.writerow(csv_data) # ファイルクローズド csv_file.close() # URLの指定 url = "https://algorithm.joho.info/programming/python/beautifulsoup-table-to-csv/" # セレクタ selecter = {"class":"test"} # 指定したURL・セレクタの表のデータをCSVに保存 table_to_csv("test.csv", url, selecter)
■実行結果
test.csv
名前,HP,ATK セイバー,15600,14580 アーチャー,13630,12580 ランサー,14510,15580
– | 関連記事 |
---|---|
1 | ■【Python/BeautifulSoup4】Webスクレイピング入門 |
2 | ■Python入門 基本文法 |
コメント