【问题标题】:Python: using Spotipy to create playlist but getting 403 Code1 ErrorPython:使用 Spotipy 创建播放列表但收到 403 Code1 错误
【发布时间】:2022-11-05 14:42:47
【问题描述】:

我正在使用 Spotipy API 在 python 中创建一个 spotify 播放列表。我的代码使用 beautifulSoup 从网站上抓取内容并创建一个输入以传递给 Spotipy。但是,我的代码尝试创建 Spotipy 播放列表的部分失败了。我认为我按照 API 文档正确地做所有事情。希望任何人都可以提供任何帮助。请参阅下面的代码和错误:

import requests
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from spotipy.oauth2 import SpotifyClientCredentials
from pprint import pprint

SPOTIFY_CLIENT_ID = "[id]"
SPOTIFY_SECRET = "[secret]"
REDIRECT_URL = "http://example.com"

sp = spotipy.Spotify(
    auth_manager=SpotifyOAuth(
        scope="playlist-modify-private",
        redirect_uri=REDIRECT_URL,
        client_id=SPOTIFY_CLIENT_ID,
        client_secret=SPOTIFY_SECRET,
        cache_path="token.txt"
    )
)

SONG_YEAR = input("What year would you like to travel back to? Enter YYYY-MM-DD format: ")
BILL_BOARD_URL = f"https://www.billboard.com/charts/hot-100/{SONG_YEAR}/"
SONG_YEAR_YEAR = SONG_YEAR.split("-")[0]
print(SONG_YEAR_YEAR)

response = requests.get(BILL_BOARD_URL)
song_scrape = response.text

soup = BeautifulSoup(song_scrape, "html.parser")

song_tags_list = soup.findAll(name="h3", class_="a-no-trucate")
artists_tags_list = soup.findAll(name="span", class_="a-no-trucate")


song_list_1 = [tag.getText().replace("\n", "") for tag in song_tags_list]
song_list_2 = [song.replace("\t", "") for song in song_list_1]

artist_list_1 = [tag.getText().replace("\n", "") for tag in artists_tags_list]
artist_list_2 = [artist.replace("\t", "") for artist in artist_list_1]

song_artist_list = dict(zip(artist_list_2, song_list_2))
# pprint(song_artist_list)


results = sp.current_user()
# pprint(results)
user_id = results['id']

# print(results)
# print(user_id)

spotify_song_uris = []
##TAKEN OUT OF BELOW FOR LOOP ['artists'][0] -> remember to add back in
for key, value in song_artist_list.items():
    spotify_result = sp.search(q=f"artist:{key} track:{value} year:{SONG_YEAR_YEAR}", type="track")
    try:
        song_uri = spotify_result['tracks']['items'][0]['uri']
        spotify_song_uris.append(song_uri)
    except IndexError:
        print(f"{value} doesn't exist in Spotify. Skipped.")

print(len(spotify_song_uris))

my_playlist = sp.user_playlist_create(user=f"{user_id}", name=f"{SONG_YEAR} Billboard Top Tracks", public=True,
                                      description="Top Tracks from back in the Dayz of Brunel")

运行代码时出现此错误:

Traceback (most recent call last):
  File "C:\Users\zeesh\PycharmProjects\Day46-UsingBeautifulSoup\venv\lib\site-packages\spotipy\client.py", line 245, in _internal_call
    response.raise_for_status()
  File "C:\Users\zeesh\PycharmProjects\Day46-UsingBeautifulSoup\venv\lib\site-packages\requests\models.py", line 960, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://api.spotify.com/v1/users/31qjiqkvnqvjhi34ukkoef7mloom/playlists

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\zeesh\PycharmProjects\Day46-SpotifyPlaylist\main.py", line 65, in <module>
    my_playlist = sp.user_playlist_create(user=f"{user_id}", name=f"{SONG_YEAR} Billboard Top Tracks", public=True,
  File "C:\Users\zeesh\PycharmProjects\Day46-UsingBeautifulSoup\venv\lib\site-packages\spotipy\client.py", line 784, in user_playlist_create
    return self._post("users/%s/playlists" % (user,), payload=data)
  File "C:\Users\zeesh\PycharmProjects\Day46-UsingBeautifulSoup\venv\lib\site-packages\spotipy\client.py", line 302, in _post
    return self._internal_call("POST", url, payload, kwargs)
  File "C:\Users\zeesh\PycharmProjects\Day46-UsingBeautifulSoup\venv\lib\site-packages\spotipy\client.py", line 267, in _internal_call
    raise SpotifyException(
spotipy.exceptions.SpotifyException: http status: 403, code:-1 - https://api.spotify.com/v1/users/31qjiqkvnqvjhi34ukkoef7mloom/playlists:
 Insufficient client scope, reason: None

当我单击错误中的 API 调用链接时,我得到:

{
"error": {
"status": 401,
"message": "No token provided"
}
}

我在 StackOverflow 和其他网站上做了一些阅读。我尝试更改范围,但没有奏效。

任何想法或指导将不胜感激。 谢谢你。 泽山

【问题讨论】:

  • 你刚刚泄露了你的 Spotify API 秘密!请作废立即地.从你的问题中编辑它是不够: 你把它发布在互联网上,它永远被泄露了。

标签: python spotify spotipy


【解决方案1】:

代码中的scopeplaylist-modify-private,但在最后一行中,您尝试使用public=True 创建播放列表。
要解决此问题,您必须将scope 更改为playlist-modify-public或者public 更改为False

【讨论】:

    【解决方案2】:

    如果您希望您的播放列表是私人的,试试这个(我将公共更改为 False):

    import requests
    import spotipy
    from spotipy.oauth2 import SpotifyOAuth
    from spotipy.oauth2 import SpotifyClientCredentials
    from pprint import pprint
    
    SPOTIFY_CLIENT_ID = "[id]"
    SPOTIFY_SECRET = "[secret]"
    REDIRECT_URL = "http://example.com"
    
    sp = spotipy.Spotify(
        auth_manager=SpotifyOAuth(
            scope="playlist-modify-private",
            redirect_uri=REDIRECT_URL,
            client_id=SPOTIFY_CLIENT_ID,
            client_secret=SPOTIFY_SECRET,
            cache_path="token.txt"
        )
    )
    
    SONG_YEAR = input("What year would you like to travel back to? Enter YYYY-MM-DD format: ")
    BILL_BOARD_URL = f"https://www.billboard.com/charts/hot-100/{SONG_YEAR}/"
    SONG_YEAR_YEAR = SONG_YEAR.split("-")[0]
    print(SONG_YEAR_YEAR)
    
    response = requests.get(BILL_BOARD_URL)
    song_scrape = response.text
    
    soup = BeautifulSoup(song_scrape, "html.parser")
    
    song_tags_list = soup.findAll(name="h3", class_="a-no-trucate")
    artists_tags_list = soup.findAll(name="span", class_="a-no-trucate")
    
    
    song_list_1 = [tag.getText().replace("
    ", "") for tag in song_tags_list]
    song_list_2 = [song.replace("	", "") for song in song_list_1]
    
    artist_list_1 = [tag.getText().replace("
    ", "") for tag in artists_tags_list]
    artist_list_2 = [artist.replace("	", "") for artist in artist_list_1]
    
    song_artist_list = dict(zip(artist_list_2, song_list_2))
    # pprint(song_artist_list)
    
    
    results = sp.current_user()
    # pprint(results)
    user_id = results['id']
    
    # print(results)
    # print(user_id)
    
    spotify_song_uris = []
    ##TAKEN OUT OF BELOW FOR LOOP ['artists'][0] -> remember to add back in
    for key, value in song_artist_list.items():
        spotify_result = sp.search(q=f"artist:{key} track:{value} year:{SONG_YEAR_YEAR}", type="track")
        try:
            song_uri = spotify_result['tracks']['items'][0]['uri']
            spotify_song_uris.append(song_uri)
        except IndexError:
            print(f"{value} doesn't exist in Spotify. Skipped.")
    
    print(len(spotify_song_uris))
    
    my_playlist = sp.user_playlist_create(user=f"{user_id}", name=f"{SONG_YEAR} Billboard Top Tracks", public=False,
                                          description="Top Tracks from back in the Dayz of Brunel")
    

    【讨论】:

      【解决方案3】:

      使用这 song_uri = spotify_result["tracks"]["items"][0]["external_urls"]["spotify"]

      而不是 song_uri = spotify_result['tracks']['items'][0]['uri']

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-17
        • 1970-01-01
        • 2018-07-13
        • 2017-01-01
        • 2016-10-22
        • 1970-01-01
        • 2019-11-03
        • 1970-01-01
        相关资源
        最近更新 更多