Skip to content

Instantly share code, notes, and snippets.

@AlexLadd
Created October 2, 2019 13:00
Show Gist options
  • Select an option

  • Save AlexLadd/db3d09b204d6c59787ad85d26c412b33 to your computer and use it in GitHub Desktop.

Select an option

Save AlexLadd/db3d09b204d6c59787ad85d26c412b33 to your computer and use it in GitHub Desktop.
import requests
from bs4 import BeautifulSoup
import json
def get_spotify_token(username, password):
"""spotify_token
Retrieves a web player access_token from Spotify
Written by Alex Ladd http://github.com/AlexLadd
Original Code from spotify_token: https://github.com/enriquegh/spotify-webplayer-token
Contributors:
Daniel Lashua http://github.com/dlashua
Updated: 2019-10-02
"""
# arbitrary value and can be static
cookies = {"__bon": "MHwwfC01ODc4MjExMzJ8LTI0Njg4NDg3NTQ0fDF8MXwxfDE="}
user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) \
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
headers = {'user-agent': user_agent}
session = requests.Session()
response = session.get("https://accounts.spotify.com/login", headers=headers, cookies=cookies)
response.raise_for_status()
csrf_token = response.cookies['csrf_token']
data = {"remember": False, "username": username, "password": password, "csrf_token": csrf_token}
response = session.post("https://accounts.spotify.com/api/login", data=data, cookies=cookies, headers=headers)
response.raise_for_status()
response = session.get("https://open.spotify.com/browse", headers=headers, cookies=cookies)
response.raise_for_status()
data = response.content.decode("utf-8")
xml_tree = BeautifulSoup(data, 'lxml')
script_node = xml_tree.find("script", id="config")
config = json.loads(script_node.string)
access_token = config['accessToken']
expires_timestamp = config['accessTokenExpirationTimestampMs']
expires_in = int(expires_timestamp) // 1000 - int(time.time())
return (access_token, expires_in)
@CounterPill
Copy link

thx!!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment