Created
March 2, 2019 15:43
-
-
Save jbarton311/c34277a0f3e5d6ba81d4963a2f279a38 to your computer and use it in GitHub Desktop.
Works on top of a spotify script (gets current song) and is used to pull lyrics for current playing song from Genius (API & Web Scrape)
This file contains hidden or 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
import requests | |
import os | |
from bs4 import BeautifulSoup | |
# The below gist is where this file lives | |
#https://gist.github.com/jbarton311/df1f5e876ff97eb848a41edcbdcb5e6c | |
import spotify_pulls as sp | |
# Local file that contains API keys and secrets | |
from config import Config | |
def genius_api_song(artist, song): | |
headers = {'Authorization': f'Bearer {SECRET_KEY'} | |
params = ( | |
('q', f'{song}'), | |
) | |
response = requests.get('http://api.genius.com/search', params=params, headers=headers) | |
data = response.json() | |
return data | |
def extract_genius_data(artist, song): | |
data = genius_api_song(artist, song) | |
for hit in data['response']['hits']: | |
if str(hit['result']['primary_artist']['name']) == artist: | |
location = hit['result']['path'] | |
return f"http://genius.com{location}" | |
def scrape_lyrics(url): | |
if url: | |
page = requests.get(url) | |
html = BeautifulSoup(page.text, "html.parser") | |
#remove script tags that they put in the middle of the lyrics | |
[h.extract() for h in html('script')] | |
#at least Genius is nice and has a tag called 'lyrics'! | |
#lyrics = html.find("div", class_="lyrics").get_text() #updated css where the lyrics are based in HTML | |
lyrics = html.find("div", class_="lyrics") #updated css where the lyrics are based in HTML | |
return lyrics | |
else: | |
return "Sorry - couldn't find lyrics on Genius" | |
def genius_lyrics(artist, song): | |
url= extract_genius_data(artist, song) | |
if url: | |
lyrics = scrape_lyrics(url) | |
# Replace relative links to absolute links back to Genius | |
for a in lyrics.findAll('a'): | |
a['href'] = a['href'].replace("/", "genius.com/") | |
return lyrics | |
else: | |
return "No lyrics provided by Genius" | |
def playing_now_lyrics(): | |
# Pull current track playing from spotify | |
current_playing = sp.current_track_data() | |
artist = current_playing['artist'] | |
song = current_playing['song'] | |
# Pass artist and song to grab lyrics from Genius | |
lyrics = genius_lyrics(artist, song) | |
return lyrics |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment