Selenium爬取Spotify歌单仅输出单个字典,如何生成所有条目字典?
问题:爬取Spotify歌单仅生成最后一首歌曲的字典,如何获取所有歌曲的字典列表?
我使用Python Selenium爬取Spotify指定歌单页面(https://open.spotify.com/playlist/37i9dQZF1DXbTop77dnX35),代码遍历获取歌曲的标题、专辑、歌手、时长信息,但最终仅生成最后一条歌曲的字典。期望为所有爬取到的歌曲生成对应字典列表,原代码及执行结果如下:
原代码
from selenium import webdriver from selenium.webdriver.common.by import By url ='https://open.spotify.com/playlist/37i9dQZF1DXbTop77dnX35' driver = webdriver.Edge() driver.get(url) songs = [] musics = driver.find_elements(By.CLASS_NAME, "IjYxRc5luMiDPhKhZVUH.UpiE7J6vPrJIa59qxts4") for music in musics: title = music.find_element(By.CLASS_NAME, "btE2c3IKaOXZ4VNAb8WQ").text album = music.find_element(By.CLASS_NAME, "_TH6YAXEzJtzSxhkGSqu").text artist = music.find_element(By.CLASS_NAME, "Text__TextElement-sc-if376j-0.gYdBJW.encore-text-body-small").text duration = music.find_element(By.CLASS_NAME, "PAqIqZXvse_3h6sDVxU0").text print(title, album, artist, duration) new_music = { 'title' : title, 'album' : album, 'artist' : artist, 'duration' : duration } songs.append(new_music) print(songs)
原执行结果
[{'title': 'Let It Flow', 'album': 'Let It Flow', 'artist': 'Maya Amolo', 'duration': '2:58'}]
解决方案
你的代码问题在于:创建new_music字典和调用songs.append(new_music)的语句在for循环外部。循环里每次会更新title、album等变量,但只有循环结束后才会执行一次字典创建和添加操作,自然只能捕获最后一首歌曲的数据。
只需将这两行代码缩进,放到for循环的代码块内部,让每遍历一首歌曲就生成对应的字典并添加到列表中:
修改后的代码
from selenium import webdriver from selenium.webdriver.common.by import By url ='https://open.spotify.com/playlist/37i9dQZF1DXbTop77dnX35' driver = webdriver.Edge() driver.get(url) songs = [] musics = driver.find_elements(By.CLASS_NAME, "IjYxRc5luMiDPhKhZVUH.UpiE7J6vPrJIa59qxts4") for music in musics: title = music.find_element(By.CLASS_NAME, "btE2c3IKaOXZ4VNAb8WQ").text album = music.find_element(By.CLASS_NAME, "_TH6YAXEzJtzSxhkGSqu").text artist = music.find_element(By.CLASS_NAME, "Text__TextElement-sc-if376j-0.gYdBJW.encore-text-body-small").text duration = music.find_element(By.CLASS_NAME, "PAqIqZXvse_3h6sDVxU0").text print(title, album, artist, duration) # 把字典创建和添加操作移到循环内部 new_music = { 'title' : title, 'album' : album, 'artist' : artist, 'duration' : duration } songs.append(new_music) print(songs)
修改后,循环每处理一首歌曲就会生成对应的字典并添加到songs列表中,最终输出的就是所有歌曲的字典列表。
内容的提问来源于stack exchange,提问作者Martha Imoh
相关产品推荐
相关产品推荐

