Skip to content

Instantly share code, notes, and snippets.

@py-ranoid
Created January 15, 2018 07:18
Show Gist options
  • Save py-ranoid/1bde68d0e0fdfcb07c90a9676ddd5b9b to your computer and use it in GitHub Desktop.
Save py-ranoid/1bde68d0e0fdfcb07c90a9676ddd5b9b to your computer and use it in GitHub Desktop.
Song Downloader (from YouTube)
from bs4 import BeautifulSoup
import youtube_dl
import webbrowser
import urllib2
import os
import sys
'''
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("date", help="Date to search tickets for",type=str)
parser.add_argument("month", help=" Month to search tickets for",type=str)
parser.add_argument("num", help="Number of tickets to search for",type=str)
args = parser.parse_args()
req_date=args.date
req_month=args.month
req_tick=args.num
'''
def fetchListfromAM(url):
soup = BeautifulSoup(urllib2.urlopen(url).read(), "lxml")
soup = soup.find('div', attrs={'class': 'track-list album music'})
songs = soup.find_all('tr', attrs={'class', 'song music'})
l = []
for i in songs:
song_name = i.find(
'td', attrs={'class': 'name flexible-col'}).span.text
song_artist = i.find(
'td', attrs={'class': 'artist flexible-col'}).span.text
l.append(song_name + ' - ' + song_artist)
return l
class MyLogger(object):
def debug(self, msg): pass
def warning(self, msg): pass
def error(self, msg): print(msg)
def my_hook(d):
if d['status'] == 'finished':
print('\n Done downloading, now converting ...')
if d['status'] == 'downloading':
percentage = 100 * d['downloaded_bytes'] / d['total_bytes']
sys.stdout.write('\r')
sys.stdout.flush()
sys.stdout.write("Download : [%-20s] %d%%" %
('=' * (percentage / 5), percentage))
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '320',
}],
'logger': MyLogger(),
'progress_hooks': [my_hook],
}
def fetch_list():
a = []
while True:
title = raw_input()
if title == 'q':
break
a.append(title)
return a
def fetch_link(query, value=None):
query = '+'.join(query.split(' '))
site = 'https://www.youtube.com/results?search_query=' + query
soup = BeautifulSoup(urllib2.urlopen(site).read(), "html.parser")
links, titles, meta = [], [], []
all_divs = soup.find_all('div', attrs={'class': 'yt-lockup-content'})
for i in all_divs:
if value is None:
meta = i.find('ul', attrs={'class': 'yt-lockup-meta-info'})
if meta is not None:
meta.append([x.text for x in meta.find_all('li')])
else:
continue
links.append("https://www.youtube.com" + i.find('h3',
attrs={'class': 'yt-lockup-title '}).a.get('href'))
titles.append(
i.find('h3', attrs={'class': 'yt-lockup-title '}).a.get('title'))
if value is None:
for i in xrange(5):
try:
print i, ' - ', titles[i], '\n', ' ', meta[i][0], ' - ', ','.join(
meta[i][1].split(',')[:-1]) + ' K', '\n'
except IndexError:
pass
num = input("\nOpen ? : ")
sel_link = links[num]
sel_title = titles[num]
else:
sel_link = links[value]
sel_title = titles[value]
return sel_link, sel_title
input_choice = input(
' 1. Download list of mp3s \n 2.Single\n 3.Download Apple Music playlist\n >>> ')
if input_choice == 1 or input_choice == 3:
song_list = fetchListfromAM(
raw_input('AM url >>')) if input_choice == 3 else fetch_list()
for q in song_list:
if q[0:4] == 'http':
sel = q
else:
sel, title = fetch_link(q, 0)
print title
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([sel])
else:
q = raw_input("Enter Title or Link: ")
if q[0:4] == 'http':
sel = q
else:
sel, title = fetch_link(q, 0)
opt = input("1. Open in Browser\n2. Open in VLC\n3. Download mp3\n >> ")
if opt == 1:
webbrowser.open(sel)
elif opt == 2:
os.system('vlc ' + sel)
elif opt == 3:
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([sel])
'''
#os.system("youtube-dl -o - "+sel+" | vlc -")
for i in soup.find_all('div', attrs={'class': 'yt-lockup-content'}):links.append("https://www.youtube.com"+i.a.get('href'))'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment