如何将Python获取的Spotify API JSON数据展示到HTML表格中
解决方案
方法1:手动拼接HTML字符串(快速上手)
修改你的get_playlists函数,拿到Spotify返回的JSON数据后,直接生成带样式的HTML代码并写入本地文件:
import requests from datetime import datetime from flask import redirect, session # 按你实际使用的框架调整 API_BASE_URL = "https://api.spotify.com/v1/users/你的用户ID" # 补全你的API地址 def get_playlists(): if 'access_token' not in session: return redirect('/login') if datetime.now().timestamp() > session['expires_at']: return redirect('/refresh-token') headers = { 'Authorization': f"Bearer {session['access_token']}" } response = requests.get(f'{API_BASE_URL}/playlists', headers=headers) playlists_data = response.json() # 构建HTML头部和基础样式 html_content = """ <!DOCTYPE html> <html> <head> <title>我的Spotify播放列表</title> <style> table {width: 90%; margin: 20px auto; border-collapse: collapse;} th {background-color: #1DB954; color: white; padding: 10px; text-align: left;} td {border-bottom: 1px solid #eee; padding: 8px;} tr:hover {background-color: #f5f5f5;} h1 {text-align: center; color: #191414;} </style> </head> <body> <h1>我的Spotify播放列表</h1> <table> <tr> <th>播放列表名称</th> <th>歌曲数量</th> <th>创建时间</th> </tr> """ # 循环生成表格行 for playlist in playlists_data['items']: name = playlist['name'] track_count = playlist['tracks']['total'] created_at = playlist['created_at'] html_content += f""" <tr> <td>{name}</td> <td>{track_count}</td> <td>{created_at}</td> </tr> """ # 补全HTML尾部 html_content += """ </table> </body> </html> """ # 写入HTML文件 with open('spotify_playlists.html', 'w', encoding='utf-8') as f: f.write(html_content) return "HTML文件已生成:spotify_playlists.html"
你可以直接修改<style>标签里的代码自定义样式,也能添加原生JavaScript实现搜索、排序等交互功能。
方法2:用Jinja2模板(推荐,易维护)
Jinja2能把Python数据和HTML结构分离,方便后续单独修改样式和交互逻辑,不用改动Python代码。
- 先安装Jinja2:
pip install jinja2
- 创建一个HTML模板文件
playlist_template.html:
<!DOCTYPE html> <html> <head> <title>我的Spotify播放列表</title> <style> .playlist-container {width: 90%; margin: 0 auto;} .search-box {width: 100%; padding: 8px; margin: 15px 0; box-sizing: border-box;} .playlist-table {width: 100%; border-collapse: collapse;} .playlist-table th {background: #1DB954; color: white; padding: 10px;} .playlist-table td {border-bottom: 1px solid #eee; padding: 8px;} .playlist-table tr:hover {background: #f8f8f8;} </style> <script> // 原生JS实现搜索功能 document.addEventListener('DOMContentLoaded', function() { const searchInput = document.querySelector('.search-box'); const tableRows = document.querySelectorAll('.playlist-table tr:not(:first-child)'); searchInput.addEventListener('keyup', function() { const keyword = this.value.toLowerCase(); tableRows.forEach(row => { const rowText = row.textContent.toLowerCase(); row.style.display = rowText.includes(keyword) ? '' : 'none'; }); }); }); </script> </head> <body> <div class="playlist-container"> <h1>我的Spotify播放列表</h1> <input type="text" class="search-box" placeholder="搜索播放列表..."> <table class="playlist-table"> <tr> <th>名称</th> <th>歌曲数</th> <th>所有者</th> </tr> {% for playlist in playlists %} <tr> <td>{{ playlist.name }}</td> <td>{{ playlist.tracks.total }}</td> <td>{{ playlist.owner.display_name }}</td> </tr> {% endfor %} </table> </div> </body> </html>
- 修改Python脚本,用Jinja2渲染模板并生成文件:
import requests from datetime import datetime from flask import redirect, session from jinja2 import Environment, FileSystemLoader API_BASE_URL = "https://api.spotify.com/v1/users/你的用户ID" def get_playlists(): if 'access_token' not in session: return redirect('/login') if datetime.now().timestamp() > session['expires_at']: return redirect('/refresh-token') headers = { 'Authorization': f"Bearer {session['access_token']}" } response = requests.get(f'{API_BASE_URL}/playlists', headers=headers) playlists_data = response.json() # 加载模板文件 env = Environment(loader=FileSystemLoader('.')) template = env.get_template('playlist_template.html') # 把播放列表数据传入模板,生成最终HTML rendered_html = template.render(playlists=playlists_data['items']) # 写入文件 with open('spotify_playlists.html', 'w', encoding='utf-8') as f: f.write(rendered_html) return "HTML文件已生成:spotify_playlists.html"
方法3:用Pandas快速生成表格
如果你的数据结构规整,用Pandas可以一键生成表格代码,适合数据量较大的场景:
- 安装Pandas:
pip install pandas
- 修改Python脚本:
import requests import pandas as pd from datetime import datetime from flask import redirect, session API_BASE_URL = "https://api.spotify.com/v1/users/你的用户ID" def get_playlists(): if 'access_token' not in session: return redirect('/login') if datetime.now().timestamp() > session['expires_at']: return redirect('/refresh-token') headers = { 'Authorization': f"Bearer {session['access_token']}" } response = requests.get(f'{API_BASE_URL}/playlists', headers=headers) playlists_data = response.json() # 提取需要的字段,转换成DataFrame playlist_info = [] for playlist in playlists_data['items']: playlist_info.append({ '名称': playlist['name'], '歌曲数': playlist['tracks']['total'], '创建时间': playlist['created_at'] }) df = pd.DataFrame(playlist_info) # 生成表格HTML,指定样式类 table_html = df.to_html(classes='playlist-table', escape=False) # 包裹成完整的HTML页面 full_html = f""" <!DOCTYPE html> <html> <head> <title>我的Spotify播放列表</title> <style> .playlist-table {width: 90%; margin: 20px auto; border-collapse: collapse;} .playlist-table th {background: #1DB954; color: white; padding: 10px;} .playlist-table td {border: 1px solid #ddd; padding: 8px;} h1 {text-align: center;} </style> </head> <body> <h1>我的Spotify播放列表</h1> {table_html} </body> </html> """ with open('spotify_playlists.html', 'w', encoding='utf-8') as f: f.write(full_html) return "HTML文件已生成:spotify_playlists.html"
内容的提问来源于stack exchange,提问作者Nick Thompson
相关产品推荐
相关产品推荐

