iTunes Chrat の1位から5位までの曲名と歌手名をリストアップする https://www.apple.com/itunes/charts/songs/ リストアップの結果は以下の通りです。 3*5の多重配列のリストをpandasのdataFrameに変換することでpandasの関数(to_csv)を利用してcsv fileを生成することが出来ます。 「csv/file.csv」の中身は以下の通りですBeautifulSoupを使ってWeb上のデータ集めも簡単♪
from bs4 import BeautifulSoup
from urllib.request import urlopen
if __name__ == '__main__':
#URLのHTML全体を読み込む
url = 'https://www.apple.com/itunes/charts/songs/'
urlRead = urlopen(url).read()
html = BeautifulSoup(urlRead, "html.parser")
#欲しいデータを絞り込む
section = html.find("section", { "class" : "section chart-grid" })
div = section.find("div", { "class" : "section-content" })
chart = div.find_all('li')
for n in range(5) :
s = chart[n].find('strong').get_text() + '位 : '
s = s + chart[n].find_all('a')[1].get_text() + ' 【 '
s = s + chart[n].find_all('a')[2].get_text() + ' 】'
print(s)
ランキングの結果
1.位 : Almost Like Praying (feat. Artists for Puerto Rico) 【 Lin-Manuel Miranda 】
2.位 : Dear Hate (feat. Vince Gill) 【 Maren Morris 】
3.位 : Thunder 【 Imagine Dragons 】
4.位 : Heaven 【 Kane Brown 】
5.位 : Feel It Still 【 Portugal. The Man 】
結果をCSVファイルとして出力する
from bs4 import BeautifulSoup
from urllib.request import urlopen
import pandas as pd
if __name__ == '__main__':
#URLのHTML全体を読み込む
url = 'https://www.apple.com/itunes/charts/songs/'
urlRead = urlopen(url).read()
html = BeautifulSoup(urlRead, "html.parser")
#欲しいデータを絞り込む
section = html.find("section", { "class" : "section chart-grid" })
div = section.find("div", { "class" : "section-content" })
chart = div.find_all('li')
tempList = []
for n in range(5) :
temp = [chart[n].find('strong').get_text(),
chart[n].find_all('a')[1].get_text(),
chart[n].find_all('a')[2].get_text()]
tempList.append(temp)
df = pd.DataFrame(tempList)
df.to_csv('csv/file.csv',sep=',',header=False,index=False)
1.,Almost Like Praying (feat. Artists for Puerto Rico),Lin-Manuel Miranda
2.,Thunder,Imagine Dragons
3.,Feel It Still,Portugal. The Man
4.,Perfect,Ed Sheeran
5.,Look What You Made Me Do,Taylor Swift
2017年10月22日日曜日
iTunes のランキングをサクッとスクラッピング
投稿日 10月 22, 2017
Tags
関連記事
登録:
コメントの投稿 (Atom)