【Python】Wikipediaの表の特定の項目のみを取得
アニメ一覧表から各アニメのタイトル、各アニメの記事へのリンクの2要素のみを取得しCSVとして保存する場合
ja.wikipedia.org
import requests from bs4 import BeautifulSoup import csv # スクレイピング対象の URL にリクエストを送り HTML を取得する res = requests.get('https://ja.wikipedia.org/wiki/%E6%97%A5%E6%9C%AC%E3%81%AE%E3%83%86%E3%83%AC%E3%83%93%E3%82%A2%E3%83%8B%E3%83%A1%E4%BD%9C%E5%93%81%E4%B8%80%E8%A6%A7_(2010%E5%B9%B4%E4%BB%A3_%E5%BE%8C%E5%8D%8A)') # レスポンスの HTML から BeautifulSoup オブジェクトを作る soup = BeautifulSoup(res.text, 'html.parser') # ページに含まれるテーブルをすべて取得する tables = [table for table in soup.find_all("table", {"class":"wikitable"})] # 各テーブルから行を取得する rows = [] for table in tables: rows_each_table = [row for row in table.find_all("tr")] rows_each_table.pop(0) # 表の題目を除去 (deque推奨) rows += rows_each_table # ラインのリストからタイトルとURLを取得 animes = [] for row in rows: a_list = row.find_all("a") anime_object = a_list[0] anime_name, anime_link = anime_object.get("title"), anime_object.get("href") animes.append((anime_name, anime_link)) # CSV へ書き込み with open("./anime.csv", "w", encoding="utf-8") as f: writer = csv.writer(f, lineterminator="\n") for anime in animes: writer.writerow(anime)