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

如何使用Python解析Apple Music获取歌单全部歌曲链接

问题原因与修复方案

报错根因

你遇到的Objects has no attribute "get"报错,是因为错误使用了enumerate()函数:enumerate(applelinks)遍历返回的是*(索引值, 元素对象)*的元组,直接对元组调用.get()方法自然会触发属性不存在的报错。

需同步修正的其他问题

  • 代码中未提前导入依赖库requests和BeautifulSoup,运行会触发模块未找到报错
  • 没有提前初始化可写入的文件对象file,直接调用file.write()会触发变量未定义报错
  • 写入链接时未添加换行符,会导致所有链接拼接在同一行,后续读取不便

修正后的完整代码

# 提前导入依赖库
import requests
from bs4 import BeautifulSoup

def getLinks():
    url = "https://music.apple.com/ua/playlist/techno-essentials/pl.de1ac365ed3549698bcd6e099db5171d"
    response = requests.get(url)
    html = response.text
    soup = BeautifulSoup(html, 'html.parser')
    applelinks = soup.find_all('meta', attrs = {"property":"music:song"})
    # 自动管理文件句柄,避免资源泄漏
    with open("apple_music_songs.txt", "w", encoding="utf-8") as file:
        # 不需要索引直接遍历元素列表即可,无需加enumerate
        for link in applelinks:
            song_url = link.get("content")
            # 写入链接加换行符分隔
            file.write(song_url + "\n")
    return

getLinks()

如果确实需要用到索引统计歌曲数量,可以把遍历部分改成:

for index, link in enumerate(applelinks):
    song_url = link.get("content")
    file.write(f"第{index+1}首:{song_url}\n")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 17:24:07