【问题标题】:Why am I getting incorrect response_json from my request in python为什么我从 python 中的请求中得到不正确的响应 json
【发布时间】:2020-04-04 11:56:03
【问题描述】:

我正在尝试使用 python 自动添加歌曲以进行 spotify。 在代码中,我尝试使用 song_name 和艺术家姓名搜索歌曲,并使用 spotify api 获取歌曲的 URI。 (https://developer.spotify.com/documentation/web-api/reference/search/search/)

但是我得到的响应是无效的,即它不返回带有 uris 的歌曲列表,它只是返回查询或我发送到 API 的请求。

例如 {'tracks': {'href': 'https://api.spotify.com/v1/search?query=track%3AYEAH+RIGHT+artist%3AJoji&type=track&offset=0&limit=20', 'items': [], 'limit': 20, 'next': None, 'offset': 0, 'previous': None , '总计': 0}}

def get_spotify_uri(self, song_name, artist):
    """Search For the Song"""
    query = "https://api.spotify.com/v1/search?q=track:{}%20artist:{}&type=track".format(
        song_name,
        artist
    )
    response = requests.get(
        query,
        headers={
            "Content-Type": "application/json",
            "Authorization": "Bearer {}".format(spotify_token)
        }
    )
    response_json = response.json()
    print(response_json)
    songs = response_json["tracks"]["items"]

    # only use the first song
    uri = songs[0]["uri"]

    return uri            



Error: response
{'tracks': {'href': 'https://api.spotify.com/v1/search?query=track%3ANext+%28Album+Version%29+artist%3AThe+Weeknd&type=track&offset=0&limit=20', 'items': [], 'limit': 20, 'next': None, 'offset': 0, 'previous': None, 'total': 0}}
Traceback (most recent call last):
  File "/home/nikhil/Crypy/spotifyplaylist.py", line 149, in <module>
    cp.add_song_to_playlist()
  File "/home/nikhil/Crypy/spotifyplaylist.py", line 124, in add_song_to_playlist
    self.get_liked_videos()
  File "/home/nikhil/Crypy/spotifyplaylist.py", line 77, in get_liked_videos
    "spotify_uri": self.get_spotify_uri(song_name, artist)
  File "/home/nikhil/Crypy/spotifyplaylist.py", line 119, in get_spotify_uri
    uri = songs[0]["uri"]

【问题讨论】:

  • 编辑您的问题,在其中包含响应代码和文本,您是否首先从accounts.spotify.com/api/token 获得了oAuth 令牌?
  • @αԋɱҽԃαмєяιcαη 我已添加错误响应,是的,我已从给定链接获取 oAuth 令牌
  • 我现在注意到了您的编辑。您收到的回复不是因为没有找到与您的查询匹配的曲目吗?
  • 嗨@user2464424,我在赛道上找到比赛后得到了这个回复。这个脚本的问题是它有时会起作用,而大多数时候它不起作用,我不知道。
  • 您的示例仅在删除 (Album+Version) 位时才有效:?q=track:Next+artist:The+Weeknd&amp;type=track。我的印象是这个问题只是一个糟糕的搜索查询问题。我建议您收集一大堆查询示例,即使在 spotify 上存在这些曲目也不会给出任何结果,并创建一个算法来去除通常会妨碍搜索的搜索词。

标签: python python-requests spotify youtube-dl


【解决方案1】:

我发布答案是因为我无法在评论中包含整个内容。我只想说我成功使用了下面的准系统代码,但是使用了urllib,鉴于您使用了requests 库,这可能不是您想要的。也许它可以用于比较目的(在 python 3.8 中测试):

import urllib.request, urllib.parse
import base64, json

# fill with your own
client_id = b"insert_here_your_client_id"
client_secret = b"insert_here_your_client_secret"

# ask for authorization
query = "https://accounts.spotify.com/api/token"
postdata = urllib.parse.urlencode({"grant_type": "client_credentials"})
postheaders = {'Authorization': "Basic "+base64.b64encode( client_id+b':'+client_secret ).decode('latin-1')}
req = urllib.request.Request(query, data=postdata.encode('latin-1'), headers=postheaders)
req = urllib.request.urlopen(req).read().decode('latin-1')
req = json.loads(req)

# do the search query
query = "https://api.spotify.com/v1/search?q=track:Castles%20artist:Freya&type=track"
req = urllib.request.Request(query, data=None, headers={'Authorization': "Bearer "+req['access_token']})
req = urllib.request.urlopen(req).read().decode('latin-1')
print(req)

【讨论】:

  • 嗨,我们可以通过硬编码令牌跳过授权部分吗?还是需要授权?
  • @invalidexplorer in the docs 它在响应中说有一个 "expires_in" 字段,所以是的,令牌将在 x 秒后过期。
猜你喜欢
  • 1970-01-01
  • 2020-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-22
  • 2016-12-23
  • 2012-07-11
  • 1970-01-01
相关资源
最近更新 更多