Skip to content

Instantly share code, notes, and snippets.

@gbrauen
Created April 7, 2019 22:48
Show Gist options
  • Save gbrauen/451f859046c05ccdadf355d645bcee02 to your computer and use it in GitHub Desktop.
Save gbrauen/451f859046c05ccdadf355d645bcee02 to your computer and use it in GitHub Desktop.
Pyton script to create a xspf playlist of the songs from a Spotify album and write it to a specified file when given the link to the Spotify album.
#!/usr/bin/python3
#-*- coding: utf-8 -*-
"""
Dumps an xspf (xml schema) playlist for all of the songs in a spotify album
when given the spotify album's link (URL: from menu
"share" -> "Copy album link").
"""
import sys
import requests
import re
import json
from xml.sax.saxutils import escape
import os
def regex(page, reg):
data = re.search(reg, page.text)
if data is not None:
return data.group(1)
else:
return ""
def getJson(page):
return regex(page, 'Spotify.Entity = ([^;]+)')
def dumpAlbum(outfile, url):
page = requests.Session().get(url)
jStr = getJson(page)
j = json.loads(jStr)
aTitle = escape(j["name"])
outfile.write("""<?xml version="1.0" encoding="UTF-8"?>
<playlist version="1" xmlns="http://xspf.org/ns/0/">
<trackList>\n""")
trackString = """ <track>
<location>{}</location>
<title>{}</title>
<creator>{}</creator>
<trackNum>{}</trackNum>
<duration>{!s}</duration>
<album>{}</album>
</track>\n"""
for t in j["tracks"]["items"]:
outfile.write(trackString.format(
t["uri"], escape(t["name"]), escape(t["artists"][0]["name"]),
t["track_number"], t["duration_ms"], aTitle))
outfile.write(""" </trackList>
</playlist>\n
""")
return
if len(sys.argv) != 3 or '--help' in sys.argv or '-h' in sys.argv:
print('Usage:')
print(' %s <url> <outfile>' % os.path.basename(sys.argv[0]))
print(__doc__)
raise SystemExit
with open(sys.argv[2], 'w') as outfile:
url = sys.argv[1]
dumpAlbum(outfile, url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment