웹 스크래핑 및 API

JOOYEUN SEO·2024년 10월 2일

100 Days of Python

목록 보기
46/76
post-thumbnail

🗂️ Day46 프로젝트: 음악 타임머신

과거 특정 시점의 인기차트 100곡을 스크래핑하여 스포티파이 API로 플레이리스트를 생성하기

1. Billboard Hot 100 스크래핑

🔍 유의 사항

⌨️ main.py

import requests
from bs4 import BeautifulSoup

date = input("Which year do you want to travel to? Type the date in this format YYYY=MM-DD: ")
url = "https://www.billboard.com/charts/hot-100/" + date

headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) 이하 생략",
    "Accept-Language": "ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7"
}
response = requests.get(url, headers=headers)

soup = BeautifulSoup(response.text, "html.parser")

song_names_spans = soup.select("li ul li h3")
song_names = [song.getText().strip() for song in song_names_spans]
artist_names_spans = soup.select("li ul li span")
artist_names = [artist.getText().strip() for artist in artist_names_spans]

2. Spotify를 통한 인증

🔍 유의 사항

  • 스포티파이 무료 계정 생성 후 https://developer.spotify.com/ 에서 로그인
  • Dashboard에서 Create app (비공개 플레이리스트를 만들 목적)
    • Redirect URIs : http://example.com 으로 설정
    • 생성 후 Client ID와 Client secret를 프로젝트로 복사
      (OAuth로 파이참 등의 3rd party 앱이 사용자 이름과 비밀번호 없이도 계정에 접근 가능)
  • 파이썬 모듈 spotipy 2.24.0 다운받기
  • 참고문서 1
    참고문서 2
  • current_user()로 인증된 사용자의 user id(생성한 스포티파이의 사용자 이름) 가져오기

⌨️ main.py

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()["id"]

동의하기

해당 페이지의 URL 복사

파이참 프롬프트에 붙여넣기하고 입력

token.txt 파일 생성됨

3. 1단계에서 가져온 곡을 Spotify에서 검색

🔍 유의 사항

  • 노래 URI 목록 만들기 (IDs URIs and URLs)
  • Search for Item 참조
    • 쿼리(q) 형식 : "track: {name} year: {YYYY}"
      (특정 연도에 발매된 곡명으로 좁히기)
  • 스포티파이에 곡이 없을 경우를 대비하여 예외처리하기

⌨️ main.py

import spotipy
from spotipy.oauth2 import SpotifyOAuth

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.")

4. Spotify 플레이리스트 생성 및 추가

🔍 유의 사항

  • user_playlist_create() : 플레이리스트 생성
    • user : 2단계에서 얻은 user id
    • name : 플레이리스트 이름 정하기
    • public : False로 비공개 설정하기
  • playlist_add_items() : 플레이리스트에 곡 넣기
    • playlist_id : 플레이리스트 id(플레이리스트 생성 후 프린트해서 찾기)
    • items : URIs 리스트

⌨️ main.py 최종

import requests
from bs4 import BeautifulSoup

date = input("Which year do you want to travel to? Type the date in this format YYYY=MM-DD: ")
url = "https://www.billboard.com/charts/hot-100/" + date

headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) 이하 생략",
    "Accept-Language": "ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7"
}
response = requests.get(url, headers=headers)

soup = BeautifulSoup(response.text, "html.parser")
song_names_spans = soup.select("li ul li h3")
song_names = [song.getText().strip() for song in song_names_spans]

#Spotify Authentication
sp = spotipy.Spotify(
    auth_manager=SpotifyOAuth(
        client_id="a7e1470277b7488a8a2e83d5d821fb72",
        client_secret="c9684b2678e3416db5c20d3e85cf4483",
        redirect_uri="http://example.com",
        scope="playlist-modify-private",
        show_dialog=True,
        cache_path="token.txt"
    )
)
user_id = sp.current_user()["id"]
print(f"user_id is '{user_id}'")

#Searching Spotify for songs by title
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.")
    time.sleep(2)

#Creating a new private playlist in Spotify
playlist = sp.user_playlist_create(user=user_id, name=f"{date} Billboard 100", public=False)

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




▷ Angela Yu, [Python 부트캠프 : 100개의 프로젝트로 Python 개발 완전 정복], Udemy, https://www.udemy.com/course/best-100-days-python/?couponCode=ST3MT72524

0개의 댓글