1
0

More than 1 year has passed since last update.

車で子供がお歌を歌いやすいように歌詞カードを用意したくてスクレイピングしてみた(Python)

Posted at

以下のページを参考にさせていただきました。
https://qiita.com/yuuuusuke1997/items/122ca7597c909e73aad5

悩んでいたこと

「ちいさなせかいの歌詞つくってー」
「アカシアの歌詞つくってー」
「トトロのうたもうたいたーい」
上記の要望に答えるため、日々歌詞カードを作っていた私はあるとき、一つのことに気づいた。

気づいたこと

私の歌詞カード作成は以下の手順で行われていたのだ。(そうだろうね・・・)

  1. ブラウザを立ち上げ、歌詞名を検索する
  2. 見つけた歌詞をコピーし、自作のドキュメントに貼り付ける
  3. ついでに検索画面に表示された画像で、子供にあいそうな画像もドキュメントに貼り付ける
  4. ある程度、歌詞カードのページが溜まってきたら、印刷して、子供に渡す

歌詞はスクレイピングしよう

わたしは歌詞はスクレイピングすることにした。

import requests
from bs4 import BeautifulSoup
import pandas as pd
import time

#曲ページ先頭アドレス
base_url = 'https://www.uta-net.com'

#歌詞一覧ページ
#url = 'https://www.uta-net.com/artist/4002/4/'童謡
#url = 'https://www.uta-net.com/artist/1194/4/'アリス
url = 'https://www.uta-net.com/artist/3979/4/'
response = requests.get(url)
soup = BeautifulSoup(response.content)

# getでリンク要素のhref属性の値を取得しtて出力
links = soup.find_all("a", class_='py-2 py-lg-0')
count = 0
for link in links:
    a = 'https://www.uta-net.com' + link.get('href','')
#    print(a)
    #歌詞詳細ページ
    response = requests.get(a)
    soup = BeautifulSoup(response.text)
    
    title = soup.find("h2", class_='ms-2 ms-md-3')
    topic = soup.find(class_="row pt-4 pe-2 ps-lg-3 pb-lg-4 kashi")
    songLyrics = soup.select("#kashi_area")
    
    print('\n')
    print(title.text)
    if(count == 2):
        break
#    print(songLyrics.text + '\n')
    for songLyric in songLyrics:
#    区切り' 'もしくは、'、'で改行が必要
        songLyricsplits_kugiri =songLyric.text.split("、")
        songLyricsplits_space =songLyric.text.split(" ")
        if(len(songLyricsplits_kugiri) > 1):
            for songLyricsplit in songLyricsplits_kugiri:
                print(songLyricsplit)
        elif(len(songLyricsplits_space) > 1):
            for songLyricsplit in songLyricsplits_space:
                print(songLyricsplit)
        
        
#            print('\n')
        #サーバーに負荷を与えないため1秒待機
        time.sleep(1)

アーティストもしくは歌のカテゴリごとにひっぱてこれるように作った。
count = 0でカウントアップし、for文をbreakするように処理を入れているが動かないところがポイントかな!

頑張った点

歌詞の改行がある程度適切(読みやすい程度の文脈)であれば良いと思ったので、スペースもしくは句読点で開業を行うように対処した。
逆にスペース表記の多い歌詞だと改行地獄になった。さらなる考慮を欲しているがまぁいい。

かかった時間

10/2にやりだしたよ。夜1~2時間で、3日目くらいに完成したよ。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0