Day 046

AWESOMee·2022년 3월 19일
0

Udemy Python Bootcamp

목록 보기
46/64
post-thumbnail

Udemy Python Bootcamp Day 046

Musical Time Machine

Scraping the Billboard Hot 100

from bs4 import BeautifulSoup
import requests

date = input("Which year do you want to travel to? Type the date in this format YYYY-MM-DD: ")

response = requests.get(f"https://www.billboard.com/charts/hot-100/{date}")
billboard_web_page = response.text

soup = BeautifulSoup(billboard_web_page, "html.parser")
songs = soup.select(selector="li ul li h3")
song_names = [song.getText().strip() for song in songs]

Authentication with Spotify

import spotipy
from spotipy.oauth2 import SpotifyOAuth

sp = spotipy.Spotify(
    auth_manager=SpotifyOAuth(
        client_id="***************",
        client_secret="****************",
        redirect_uri="http://example.com/",
        scope="playlist-modify-private",
        show_dialog=True,
        cache_path="token.txt"
    )
)
user_id = sp.current_user()

Spotify인데 모듈이름이 spotipy라 모듈 설치하는데 에러좀 났었음 ㅎ..
Documentation 파악하는데 아직 좀 버거운 듯 함 ㅠㅠ
.current_user() method를 사용해야 한다는 것 자체를 감을 못잡음..

Search Spotify for the Songs

user_id = sp.current_user()["id"]

song_uris = []
year = date.split("-")[0]
for song in song_names:
    result = sp.search(q=f"track:{song} year:{year}", type="track")
    # print(result)
    try:
        uri = result["tracks"]["items"][0]["uri"]
        song_uris.append(uri)
    except IndexError:
        # print(f"{song} doesn't exist in Spotify. Skipped.")
        pass
print(song_uris)

#output

song URIs 만드는 것부터 막혔다...
.search()를 사용해야 한다는 것도,
힌트로 나온 query를 .search() 안에 사용해야 한다는 것도 아예 감을 못잡음 왜이래...
질의응답 보면 spotify documentation이 특히 엉망이라고 하긴 하는데
일단 저 많은 methods 중에서 어떤 상황에 어떤 method를 사용해야 하는지 감을 잡는 게 우선일듯..

Creating and Adding to Spotify Playlist

result = sp.user_playlist_create(
    user=user_id,
    name=f"{date} Billboard 100",
    public=False,
)
sp.playlist_add_items(
    playlist_id=result["id"],
    items=song_uris,
)

creating은 잘 했는데!!
adding에서 조금 버벅거렸음
곡 하나씩 넣어야 하는 줄 알고 for loop썼는데 오류나서
솔루션 보니까 그냥 리스트song_uris 통째로 넣으면 되는 거였음ㅋ

근데 문제는 내가 만든 이 플리를 어디서 보는 지 모르겠다는 거임...
그래서 사실 플리가 정상적으로 만들어졌는지도 모름..
앱을 깔아서 봐야하나..?

내가 다른 강의는 질의응답 잘 안봐서 모르겠는데
근데 이번 섹션 질의응답에 사람들 엄청 다 막 화나있엌ㅋㅋㅋㅋ

FINAL

import spotipy
from bs4 import BeautifulSoup
import requests
from spotipy.oauth2 import SpotifyOAuth

sp = spotipy.Spotify(
    auth_manager=SpotifyOAuth(
        client_id="7deb5a2e02cd46a191959a19265089e6",
        client_secret="b32c154bba5448129fe3a33097672bb8",
        redirect_uri="http://example.com/",
        scope="playlist-modify-private",
        show_dialog=True,
        cache_path="token.txt"
    )
)
user_id = sp.current_user()["id"]
date = input("Which year do you want to travel to? Type the date in this format YYYY-MM-DD: ")

response = requests.get(f"https://www.billboard.com/charts/hot-100/{date}")
billboard_web_page = response.text

soup = BeautifulSoup(billboard_web_page, "html.parser")
songs = soup.select(selector="li ul li h3")
song_names = [song.getText().strip() for song in songs]

song_uris = []
year = date.split("-")[0]
for song in song_names:
    result = sp.search(q=f"track:{song} year:{year}", type="track")
    try:
        uri = result["tracks"]["items"][0]["uri"]
        song_uris.append(uri)
    except IndexError:
        # print(f"{song} doesn't exist in Spotify. Skipped.")
        pass

result = sp.user_playlist_create(
    user=user_id,
    name=f"{date} Billboard 100",
    public=False,
)

sp.playlist_add_items(
    playlist_id=result["id"],
    items=song_uris,
)

스포티파이 3개월 무료라길래 구독했는데
플리 정상적으로 만들어져있음..!!!!! 감동 ㅠㅠ
(무료지만) 구독해놓은 김에 프로그램에서 차트 생성해서 들어야지 히히

profile
개발을 배우는 듯 하면서도

0개의 댓글