Last active
March 24, 2017 23:30
-
-
Save pR0Ps/61311ccc7e786e4a25a84e43e33a8660 to your computer and use it in GitHub Desktop.
[quick hack] Get artists and names from a list of spotify track urls
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
Takes a file full of Spotify track URLss and prints their artists and track | |
names to stdout. Useful for converting a spotify playlist export to a list of | |
human-readable songs. | |
File format: | |
``` | |
https://open.spotify.com/track/<track id> | |
[...] | |
https://open.spotify.com/track/<track id> | |
``` | |
""" | |
import json | |
import sys | |
import urllib.request | |
def get_html(url): | |
with urllib.request.urlopen(url) as r: | |
return r.read().decode("utf-8") | |
def parse_html(html): | |
for line in html.splitlines(): | |
s = line.split("Spotify.Entity = ") | |
if len(s) == 2: | |
s = s[-1] | |
break | |
else: | |
return None | |
d = json.loads(s.rstrip(";")) | |
name = d["name"] | |
artists = ", ".join(x["name"] for x in d["artists"]) | |
return "{1} - {0}".format(name, artists) | |
def main(): | |
if len(sys.argv) < 2: | |
print("Syntax: {} <input file>".format(sys.argv[0])) | |
return | |
with open(sys.argv[1], "r") as f: | |
for line in f: | |
html = get_html(line) | |
info = parse_html(html) | |
if info is None: | |
print ("ERROR: Couldn't find song data for url {}".format(line)) | |
else: | |
print(info) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment