从流媒体服务获取歌曲流计数以在 Excel 表格中自动更新

问题描述 投票:0回答:1

这是一个更大的想法问题,但我正在开发一个项目,在该项目中,在 Excel 工作表中包含几列,每天自动更新一堆歌曲的流数量,这将非常有帮助。 (也包含在电子表格中)在不同的流媒体服务上(Spotify/Apple music/YouTube/等的不同列)。解决这个问题的最佳方法是什么?

我的第一个想法是使用这些服务的 API 和 Openpyxl 来编写一些 Python 脚本来完成上面列出的任务。我写了一个适用于 Spotify 的文章,我将在下面发布,以便您了解我的情况(它从一列充满 Spotify 歌曲 ID 的列中找到歌曲的流行度,这些 ID 是我从我编写的另一个脚本中获得的) .

Apple Music API 似乎需要付费订阅 Apple 开发计划,而且我发现了一些其他 API 似乎可以完成这项工作(即 https://docs.songstats.com/)。但总而言之,我想我的问题是这些 API 是做到这一点的最佳方法,还是有一种我应该考虑的更有效和高效的方法,因为最终我并没有真正编写应用程序,也没有需要将所有其他花哨的功能合并到 API 中吗?

非常感谢任何帮助,因为我是一个相对新手的编码员(在大学上了几门课,将我的专业转为英语,在创意领域找到了一份工作,现在为他们提供了编码技能,我不确定我仍然有:)。

import openpyxl
import requests
import base64

# Spotify API credentials
CLIENT_ID = (not posting these here haha)
CLIENT_SECRET = ""

# Function to get an access token from Spotify
def get_access_token():
    url = 'https://accounts.spotify.com/api/token'
    credentials = f'{CLIENT_ID}:{CLIENT_SECRET}'
    encoded_credentials = base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
    headers = {'Authorization': f'Basic {encoded_credentials}'}
    data = {'grant_type': 'client_credentials'}
    response = requests.post(url, data=data, headers=headers)
    return response.json()['access_token']

# Function to get song popularity from Spotify
def get_song_popularity(song_uri, access_token):
    if song_uri is None:
        return None
    
    song_id = song_uri.split(':')[-1]  # Extract the last part of the URI as the song ID
    url = f'https://api.spotify.com/v1/tracks/{song_id}'
    headers = {'Authorization': f'Bearer {access_token}'}
    response = requests.get(url, headers=headers)
    data = response.json()
    
    if 'popularity' in data:
        return data['popularity']
    else:
        return None

# Function to process the Excel file and update with song popularity
def process_excel(excel_file_path):
    wb = openpyxl.load_workbook(excel_file_path)
    ws = wb.active

    access_token = get_access_token()

    # Adding a new column header
    ws.cell(row=1, column=4, value='Popularity')

    for row_idx, cell in enumerate(ws['C'][1:], start=2):  # Assuming URIs are in column A starting from the second row
        song_uri = cell.value
        song_popularity = get_song_popularity(song_uri, access_token)
        
        if song_popularity is not None:
            ws.cell(row=row_idx, column=4, value=song_popularity)

    wb.save(excel_file_path)

if __name__ == '__main__':
    excel_file_path = 'streams.xlsx'
    process_excel(excel_file_path)

(令人烦恼的是,SpotifyAPI 不允许您访问原始歌曲流,而是访问“流行指数”,它是 0-100 之间的整数,具有讽刺意味的是,它在算法中的某个位置使用流来获取最终数字,但我猜 Spotify 只是想成为尽可能复杂。所以侧面,但如果有人有关于如何直接访问流的想法,请告诉我)。

python excel analytics spotify
1个回答
0
投票

您所需要的通常是通过付费第三方服务提供的,例如 ChartmetricSoundcharts,它们会为您完成所有日常抓取和聚合等工作。正如您提到的,大多数官方 API 并不倾向于公开提供原始流。

© www.soinside.com 2019 - 2024. All rights reserved.