アイドルマスターのカレンダーをスクレイピング

gomao9.github.io

qiita.com

を参考にPythonスクレイピングのところだけやってみた

select_oneはCSSセレクタ指定できるのでいつもよりシンプルでわかりやすかった。

いつもの書き方もコメントにして書いてます。

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


# ホームページより取得
url = "http://idolmaster.jp/schedule/2016/april.php"
html = urlopen(url).read()

soup = BeautifulSoup(html, 'html5lib')

"""
# ファイル保存
with open('idol.html', mode = 'w', encoding = 'utf-8') as fw:
    fw.write(soup.prettify())

soup = BeautifulSoup(open("idol.html", encoding='utf-8'), "html5lib")
"""

tr = soup.select('#tabelarea > table > tbody > tr')

data = []

for i in tr[3:-1]:

    # ジャンル
    # temp = i.find('td', class_='genre2').string
    temp = i.select_one('td.genre2').string
    genre = temp.strip() if temp else None

    # 内容・リンク
    # temp = i.find('td', class_='article2').find('a')
    temp = i.select_one('td.article2 > a')

    article = temp.string.strip() if temp else None
    link = temp.get('href') if temp else None

    # 日付
    # temp = i.find('td', class_='day2')
    temp = i.select_one('td.day2')
    day = int(temp.img.get('src')[-6:-4]) if temp else day

    # 時刻
    # temp = i.find('td', class_='time2').string
    temp = i.select_one('td.time2').string
    time = temp.strip() if temp else None

    # 出演者
    # temp = i.find('td', class_='performance2').find('img')
    temp = i.select_one('td.performance2 > img')
    performance = temp.get('alt') if temp else None

    data.append({'day':day, 'time':time, 'genre':genre, 'article':article, 'link':link})

pprint(data)