T 流年印迹
流年印迹
首页 Python 正文

Python 100 天 · 第 46 天:爬虫 + OAuth:把榜单变成 Spotify 歌单

这是「Python 100 天」系列第 46 天的学习笔记:爬虫 + OAuth:把榜单变成 Spotify 歌单。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

输入一个日期(YYYY-MM-DD),抓取那一天 Billboard Hot 100 的歌单,然后在 Spotify 里自动创建一个同名私有歌单,把能搜到的歌都加进去。README 知识点:BeautifulSoup 选择元素、API Key、Spotipy 授权、重定向 URI。

一、OAuth:为什么不能只用账号密码

Spotify 这类服务用 OAuth 2.0:你的程序不接触用户密码,而是让用户在浏览器里登录并"授权",然后拿到一个 access token(短期有效)和 refresh token(用来续期)。

1
2
3
4
5
6
7
8
9
10
11
import spotipy
from spotipy.oauth2 import SpotifyOAuth

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
scope="playlist-modify-private", # 申请的权限范围
redirect_uri="https://example.com/",
cache_path="token.txt", # token 缓存,避免每次都登录
show_dialog=True,
))
  • scope 是最小权限:只要"改私有歌单",就不要申请"读取邮箱";
  • redirect_uri 必须和 Spotify 后台登记的一模一样(多一个斜杠都不行),否则报 INVALID_CLIENT: Invalid redirect URI;
  • cache_path 把 token 存本地,第二次运行就不用再授权。

二、搜索与 URI

1
2
3
result = sp.search(q=f"track:{song} year:{year}", type="track")
uri = result["tracks"]["items"][0]["uri"] # 'spotify:track:xxxx'
sp.playlist_add_items(playlist_id=..., items=song_uris)

Spotify 用 URI 标识资源,加歌单要传 URI 列表,不是歌名。

三、爬虫 + API 的组合

1
爬 Billboard(拿歌名) → 搜 Spotify(歌名 → URI) → 建歌单 → 批量加歌

这就是"数据管道":每个环节的输出是下一个环节的输入。中间任何一步失败,都要能跳过而不是整体崩掉。

代码全文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from bs4 import BeautifulSoup
import requests
import os
from dotenv import load_dotenv
import spotipy
from spotipy.oauth2 import SpotifyOAuth

load_dotenv(".env")
CLIENT_ID = os.getenv("CLIENT_ID")
CLIENT_SECRET_ID = os.getenv("CLIENT_SECRET_ID")

date = input("Which day do you want to travel to? Type the date in this format: YYYY-MM-DD: ")

URL = f"https://www.billboard.com/charts/hot-100/{date}/"
response = requests.get(URL)
website_html = response.text

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

all_songs = soup.findAll(name="h3", class_="c-title a-no-trucate a-font-primary-bold-s u-letter-spacing-0021 lrv-u-font-size-18@tablet lrv-u-font-size-16 u-line-height-125 u-line-height-normal@mobile-max a-truncate-ellipsis u-max-width-330 u-max-width-230@tablet-only", id="title-of-a-story")
number_one = soup.find(name="h3", class_="c-title a-no-trucate a-font-primary-bold-s u-letter-spacing-0021 u-font-size-23@tablet lrv-u-font-size-16 u-line-height-125 u-line-height-normal@mobile-max a-truncate-ellipsis u-max-width-245 u-max-width-230@tablet-only u-letter-spacing-0028@tablet", id="title-of-a-story").getText()
number_one = number_one.replace("n", "")
song_titles = [song.getText().replace("n", "") for song in all_songs]
song_titles.insert(0, number_one)

sp = spotipy.Spotify(
auth_manager=SpotifyOAuth(
client_id=f"{CLIENT_ID}",
client_secret=f"{CLIENT_SECRET_ID}",
scope="playlist-modify-private",
show_dialog=True,
cache_path="token.txt",
redirect_uri="https://example.com/",
)
)

user_id = sp.current_user()["id"]

song_uris = []
year = date.split("-")[0]
for song in song_titles:
result = sp.search(q=f"track:{song} year:{year}", type="track")
print(result)
try:
uri = result["tracks"]["items"][0]["uri"]
song_uris.append(uri)
except IndexError:
print(f"{song} doesn't exist in Spotify. Skipped.")

playlist = sp.user_playlist_create(user=user_id, name=f"{date} Billboard 100", public=False)
sp.playlist_add_items(playlist_id=playlist["id"], items=song_uris)

代码走读

  1. load_dotenv(".env") + os.getenv(...):密钥从环境变量读,不写进代码。
  2. 拼 Billboard 的 URL,requests.get 拿 HTML。
  3. 两次 find:一次抓 100 首(findAll 的第一个参数是 name),一次单独抓第 1 名——因为第 1 名的 HTML 结构和其余 99 首不一样(class 更长)。这是爬虫里最典型的"特例处理"。
  4. number_one.replace("n", ""):去掉换行。
  5. song_titles.insert(0, number_one):把第 1 名插到列表最前面。
  6. SpotifyOAuth(...) 建客户端,current_user()["id"] 拿用户 id。
  7. 循环搜歌,try/except IndexError 处理"搜不到",打印跳过。
  8. user_playlist_create 建歌单 → playlist_add_items 批量加歌。

值得注意的地方

  • print(result) 在循环里:调试用,正式跑要删掉,否则 100 次搜索会刷屏。
  • q=f"track:{song} year:{year}":Spotify 的搜索语法,track: 限定字段。歌名里有引号、括号时容易搜不到。
  • 榜单 class 名是硬编码的长串:Billboard 一改版就失效,这是爬虫的宿命。稳健做法是用 select 匹配部分类名,或改用官方榜单 API。
  • redirect_uri="https://example.com/":只是占位,授权后浏览器会跳到这个地址(打不开也没关系,复制地址栏里的 code 参数即可)。

运行结果

Spotify 里多了一个歌单 2026-12-02 Billboard 100,里面是当天能搜到的歌。

易错点

  1. redirect_uri 不一致:最常见的授权失败原因。
  2. scope 不够:加歌单需要 playlist-modify-private(或 public)。
  3. 免费账号限制:部分接口对免费用户不可用。
  4. items 一次最多 100 个:超过要分批调用。
  5. find(...) 返回 None:页面结构变了,.getText() 直接崩。

动手改

  • 把 print(result) 删掉,只在失败时打印。
  • 加"文件已存在就跳过搜索"的缓存(json 存"歌名 → URI")。
  • 用 date 校验输入格式,非法就重新输入。

源文件逐个讲解

2 个文件:一个脚本 + 一个 README。这一天没有数据文件(.env、token.txt 都是运行时才产生的,仓库里没有)。

文件 行数 职责
main.py47爬 Billboard 榜单 → 搜 Spotify → 建歌单
README.md9说明页

main.py(47 行)——三段式

(1)导入与环境变量

1
2
3
4
5
6
7
8
import os
from dotenv import load_dotenv
import spotipy
from spotipy.oauth2 import SpotifyOAuth

load_dotenv(".env")
CLIENT_ID = os.getenv("CLIENT_ID")
CLIENT_SECRET_ID = os.getenv("CLIENT_SECRET_ID")

load_dotenv(".env") 把 .env 文件里的键值对注入 os.environ:

1
2
3
# .env 文件内容(仓库里没有,要自己建)
CLIENT_ID=你的client_id
CLIENT_SECRET_ID=你的secret

这是本项目第一次用 .env——密钥不进代码、不进 Git,这是安全底线。对比 Day 35/36/38 直接用 os.environ["X"],这里多了「从文件加载」这一步,本地开发不再需要 export。

CLIENT_SECRET_ID 这个名字起得别扭——通常叫 CLIENT_SECRET。

(2)爬榜单

1
2
3
date = input("Which day do you want to travel to? Type the date in this format: YYYY-MM-DD: ")

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

把用户输入直接拼进 URL——没有校验格式。输入 2020-8-1 或中文都会 404。

1
all_songs = soup.findAll(name="h3", class_="c-title a-no-trucate a-font-primary-bold-s u-letter-spacing-0021 lrv-u-font-size-18@tablet lrv-u-font-size-16 u-line-height-125 u-line-height-normal@mobile-max a-truncate-ellipsis u-max-width-330 u-max-width-230@tablet-only", id="title-of-a-story")

这一行 300 多字符,是全书最长的一行。

为什么这么长? 因为它用了 Billboard 的 utility class 命名法(Tailwind 风格)——一个 class 管一个样式,所以定位一个元素要写十几二十个 class。

正确的做法:只取其中一个「语义性」的 class,比如 class_="c-title",或者用 id="title-of-a-story":

1
soup.find_all(name="h3", id="title-of-a-story")

findAll 是 find_all 的旧别名——能跑,但文档推荐下划线版。同一个文件里 findAll 和 find 混用,风格不统一。

1
2
3
4
number_one = soup.find(name="h3", class_="...u-max-width-245...", id="title-of-a-story").getText()
number_one = number_one.replace("n", "")
song_titles = [song.getText().replace("n", "") for song in all_songs]
song_titles.insert(0, number_one)

为什么要单独抓「第一名」?

因为 Billboard 页面上第 1 名的 HTML 结构和 2–100 名不一样(字号更大、class 多一个 u-font-size-23@tablet、u-max-width-245)。所以:

  • all_songs 抓到的是 2–100 名(99 首);
  • number_one 单独抓第 1 名;
  • insert(0, ...) 把它插到列表开头,凑成 100 首。

这是一个非常典型的「网页结构不一致」问题——爬虫经常要「特殊处理第一条/最后一条」。

.replace("n", "") 去掉换行:getText() 拿到的文本前后有大量空白和换行(HTML 源码的缩进)。

(3)Spotify 认证

1
2
3
4
5
6
7
8
9
10
11
sp = spotipy.Spotify(
auth_manager=SpotifyOAuth(
client_id=f"{CLIENT_ID}",
client_secret=f"{CLIENT_SECRET_ID}",
scope="playlist-modify-private",
show_dialog=True,
cache_path="token.txt",
redirect_uri="https://example.com/",
)
)
user_id = sp.current_user()["id"]

五个参数各有作用:

参数 作用
scope="playlist-modify-private"权限范围:只能改私有歌单
show_dialog=True每次都弹授权页(方便换账号)
cache_path="token.txt"token 存本地,第二次不用重新授权
redirect_uri授权后跳回的地址(example.com 是占位)

f"{CLIENT_ID}" 是多余写法:CLIENT_ID 本身已是字符串,直接传 client_id=CLIENT_ID 即可。这种 f"{x}" 是初学者常见的「过度格式化」。

redirect_uri="https://example.com/" 必须在 Spotify 后台的 App 设置里登记过,否则报 INVALID_CLIENT: Invalid redirect URI。

(4)逐首搜索

1
2
3
4
5
6
7
8
9
10
song_uris = []
year = date.split("-")[0]
for song in song_titles:
result = sp.search(q=f"track:{song} year:{year}", type="track")
print(result)
try:
uri = result["tracks"]["items"][0]["uri"]
song_uris.append(uri)
except IndexError:
print(f"{song} doesn't exist in Spotify. Skipped.")

q=f"track:{song} year:{year}":Spotify 的搜索语法,track: 限定歌名、year: 限定年份。

except IndexError:搜不到时 items 是空列表,[0] 抛 IndexError。这里捕获得对(对比 Day 40 的 pprint 崩)。

print(result) 是个坏习惯:100 首歌会打印 100 个巨大字典,把有用信息全冲掉。而且 result 可能很大,终端会卡。

搜索精度问题:只给歌名 + 年份,同名歌会搜错(比如一堆叫《Intro》的)。没有歌手名做二次校验。

(5)建歌单

1
2
playlist = sp.user_playlist_create(user=user_id, name=f"{date} Billboard 100", public=False)
sp.playlist_add_items(playlist_id=playlist["id"], items=song_uris)

两步:先建空歌单,再批量加歌。playlist_add_items 一次最多 100 首——正好够用。

public=False:私有歌单,别人看不到。

这份代码的问题

  1. class_ 写了 300 字符,应该只用一个稳定的 class 或 id。
  2. f"{CLIENT_ID}" 多余格式化。
  3. print(result) 污染输出。
  4. 用户输入的日期没校验。
  5. 搜索没有歌手名,容易匹配错歌。
  6. findAll / find_all 混用。
  7. .env 和 token.txt 没在仓库里,直接跑会 KeyError / 需重新授权。

README.md(9 行)

标题 Day 46 - Create a Spotify Playlist using the Musical Time Machine,知识点:Finding Elements and Finding Multiple Elements、Scraping a Live Website、Working with Spotify API、Spotipy。

「Musical Time Machine」= 音乐时光机:输入一个过去的日期,把那天 Billboard 榜单的 100 首歌做成今天的歌单。这是本课程最有名的项目之一。

微信收款码 微信
支付宝收款码 支付宝
评论