You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用Spotify API获取歌手热门歌曲时遇TypeError求助

问题排查与解决

核心错误原因

你遇到的TypeError: can only concatenate str (not "function") to str,根源是没有调用get_token函数,只是把函数本身赋值给了token变量:

# 错误写法:仅引用函数对象,未执行获取token的逻辑
token = get_token
# 正确写法:加括号调用函数,拿到返回的token字符串
token = get_token()

当你把函数对象传入get_auth_header时,代码尝试把字符串"Bearer "和函数对象拼接,自然触发类型错误。

其他需修复的问题

  1. get_songs_by_artist函数无返回值
    当前函数处理完歌曲数据后没有返回,导致后续songs变量为None,遍历会报错。需要添加返回语句:

    def get_songs_by_artist(token, artist_id):
        url = f"https://api.spotify.com/v1/artists/{artist_id}/top-tracks?country=US"
        headers = get_auth_header(token)
        result = get(url, headers=headers)
        json_result = json.loads(result.content)["tracks"]
        return json_result  # 新增返回歌曲列表的语句
    
  2. 环境变量与硬编码变量混淆
    代码里同时定义了硬编码的Client_ID/Client_S和从环境变量读取的client_id/client_secret,但get_token用的是硬编码变量,建议统一用环境变量(确保.env文件配置了正确的密钥):

    def get_token():
        auth_string = client_id + ':' + client_secret  # 改用环境变量读取的密钥
        auth_bytes = auth_string.encode("utf-8")
        auth_base64 = str(base64.b64encode(auth_bytes), "utf-8")
        # 后续代码不变
    
  3. 重复导入与拼写错误

    • 删除重复的import base64语句
    • 修正Content-Type的拼写错误:application/x-www-urlencoded → application/x-www-form-urlencoded(符合HTTP规范)

修复后的完整代码

import base64
import os
import json
from dotenv import load_dotenv
from requests import post, get

load_dotenv()

# 从环境变量读取Spotify密钥
client_id = os.getenv("Client_ID")
client_secret = os.getenv("Client_S")


def get_token():
    auth_string = client_id + ':' + client_secret
    auth_bytes = auth_string.encode("utf-8")
    auth_base64 = str(base64.b64encode(auth_bytes), "utf-8")

    url = "https://accounts.spotify.com/api/token"
    headers = {
        "Authorization": "Basic " + auth_base64,
        "Content-Type": "application/x-www-form-urlencoded"
    }
    data = {"grant_type": "client_credentials"}
    result = post(url, headers=headers, data=data)
    json_result = json.loads(result.content)
    token = json_result["access_token"]
    return token


def get_auth_header(token):
    return {"Authorization": "Bearer " + token}


def search_for_artist(token, artist_name):
    url = "https://api.spotify.com/v1/search"
    headers = get_auth_header(token)
    query = f"q={artist_name}&type=artist&limit=1"

    query_url = url + "?" + query
    result = get(query_url, headers=headers)
    json_result = json.loads(result.content)["artists"]["items"]
    if len(json_result) == 0:
        print("没有找到该歌手")
        return None

    return json_result[0]


def get_songs_by_artist(token, artist_id):
    url = f"https://api.spotify.com/v1/artists/{artist_id}/top-tracks?country=US"
    headers = get_auth_header(token)
    result = get(url, headers=headers)
    json_result = json.loads(result.content)["tracks"]
    return json_result


# 修复函数调用逻辑
token = get_token()
result = search_for_artist(token, "ACDC")
if result:
    artist_id = result["id"]
    songs = get_songs_by_artist(token, artist_id)
    print("热门歌曲:")
    for idx, song in enumerate(songs):
        print(f"{idx + 1}. {song['name']}")

额外提示

确保你的.env文件和代码在同一目录,内容格式如下:

Client_ID=你的Spotify客户端ID
Client_S=你的Spotify客户端密钥

内容的提问来源于stack exchange,提问作者zyrex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 08:03:28