【问题标题】:How to prevent Spotipy from adding incorrect song to playlist?如何防止 Spotipy 将不正确的歌曲添加到播放列表?
【发布时间】:2022-06-28 01:35:26
【问题描述】:

通过 Angela Yu 的 100 天代码,我正在执行一个项目,用户输入 YYYY-MM-DD 以搜索该日期广告牌前 100 名中的 100 首歌曲的列表。这些歌曲被网络抓取并通过 Spotipy 添加到播放列表中。但是,我注意到添加了来自不需要的年份的歌曲。例如,如果我输入 1996-11-15,我的播放列表中会出现一首 Bruno Mars 的歌曲,这不是 1996 年的。

为了防止这种情况,我在 for 循环中添加了更多条件来搜索确切的歌曲名称和艺术家姓名,然后我添加了一个名为“duplicate_check”的空列表,我将为已经添加到的歌曲添加歌曲名称播放列表列表。问题是我现在得到的歌曲少于 100 首。

我如何获得 100 首完全来自指定日期的广告牌前 100 名的歌曲?

# Asks user to input YYYY-MM-DD.
time_period = input("What year would you like to travel to in YYYY-MM-DD format? ")
year = time_period.split("-")[0]

url = f"https://www.billboard.com/charts/hot-100/{time_period}/"


# Initialize BS to parse url above.
response = requests.get(url)
webpage = response.text
soup = BeautifulSoup(webpage, "html.parser")


# Scrapes Billboard page to find song titles
song_titles = soup.select(selector="ul li h3")
song_artists = soup.select(selector="li ul li span")
artist_list = [artist.getText().strip() for artist in song_artists[0:700:7]]
song_list = [title.getText().strip() for title in song_titles[0:100:1]]

song_uri_list = []
# The purpose of this list is to prevent duplication by adding the song name to this list, once the uri is added.
duplicate_check = []

# Using params and header, creates a POST request to create new playlist on my account.
params = {
    "name": f"{time_period} Billboard 100",
    "public": False,
    "collaborative": False,
}

# Gets Access Token from .cache file generated after initializing spotipy API.
with open(".cache", "r") as file:
    data = file.read().split()
    token = data[1].strip(',"')

header = {
    "Authorization": f"Bearer {token}",
    "Content-Type": "application/json",
}

# Initializes Spotipy API.
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope="playlist-modify-private",
                                               client_id=SPOTIFY_CLIENT_ID,
                                               client_secret=SPOTIFY_CLIENT_SECRET,
                                               redirect_uri=SPOTIPY_REDIRECT_URI,
                                               cache_path=".cache"
                                               ))

# Creates a playlist on my account.
response = requests.post(url=f"{SPOTIFY_ENDPOINT}/users/{SPOTIFY_USER_ID}/playlists", json=params, headers=header)
playlist_uri = json.loads(response.text)["uri"]


# Searches Spotify for each song scraped from url via a unique URI and adds it to a list.
for song, artist in zip(song_list, artist_list):
    results = sp.search(q=f"track: {song} artist: {artist} year: {year}", type="track")
    for dict in results["tracks"]["items"]:
        if dict["name"] == song and dict["artists"][0]["name"] == artist and song not in duplicate_check:
            try:
                song_uri_list.append(dict["uri"])
                duplicate_check.append(song)
            except IndexError:
                print("no song found")
                pass


# Adds list of songs to playlist.
sp.playlist_add_items(
    playlist_id=playlist_uri,
    items=song_uri_list,
    position=None
)

【问题讨论】:

    标签: python spotipy


    【解决方案1】:

    最初获取更多,120 应该足够了,

    artist_list = [artist.getText().strip() for artist in song_artists[0:840:7]]
    song_list = [title.getText().strip() for title in song_titles[0:120:1]]
    

    然后只取 100 首独特的歌曲:

    # Searches Spotify for each song scraped from url via a unique URI and adds it to a list.
    for song, artist in zip(song_list, artist_list):
        # take only 100 songs
        if len(duplicate_check >= 100): 
            break
        results = sp.search(q=f"track: {song} artist: {artist} year: {year}", type="track")
        ...
    

    【讨论】:

      猜你喜欢
      • 2017-01-01
      • 2017-08-22
      • 1970-01-01
      • 2011-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多