めうの雑記

備忘録

pythonでCDタイトルから曲名を取得する

ORICON NEWS|最新情報を発信する総合トレンドメディアスクレイピングしてCDの情報を取得する。

コード

# -*- coding: utf-8 -*-
#曲名を取得

from natsort import natsorted
import os 
from bs4 import BeautifulSoup
import urllib.request as req

list = []

title = input("title>>")
    
#フォルダ名を取得
dirname = os.path.basename(パス + title)
#指定したフォルダの中にあるファイル名をリストで取得
dirfile = os.listdir(パス + title)
#ファイルをソート
dirfile = sorted(dirfile)

cdtitle = dirname.replace(" ", "+")
res = req.urlopen("https://www.oricon.co.jp/search/result.php?types=cd&search_string=" + cdtitle)
soup = BeautifulSoup(res, "html.parser")
text = soup.find_all("a")
for string in text:
    if dirname in string.text:
        res = req.urlopen("https://www.oricon.co.jp" + string.attrs['href'])
        soup = BeautifulSoup(res, "html.parser")
        #曲名のリスト
        text = soup.find_all("div", class_="music-title") 
        if (len(dirfile)) == len(text):
            for string in text:
                list.append(string.text)
            break

i = 0
for name in dirfile:
    #ファイル名を書き換える
    os.rename(パス" + title + "/" + name, パス + title + "/" + list[i])
    i = i + 1

CDのタイトルは「I beg you」を入力する。

実行前

f:id:umesann:20190113205538p:plain:w400

実行後

f:id:umesann:20190113205545p:plain:w400