-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyoutube_downloader.py
72 lines (62 loc) · 1.86 KB
/
youtube_downloader.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#Extracting YouTube links using BeautifulSoup
import requests
import json
from bs4 import BeautifulSoup
# url = "https://www.youtube.com/watch?v=xoWxv2yZXLQ"
url = "PASTE A YOUTUBE LINK HERE"
#Returns lists of links of thumbnails, videos and audios
def getYouTubeLinks(url):
response = requests.get(url)
data = response.content.decode("utf-8")
soup = BeautifulSoup(data, 'html.parser')
page = soup.prettify()
X = [i.split("\n") for i in page[page.find(
".googlevideo.com/videoplayback?"):].split(",") if '"url":' in i]
filename = ''.join(soup.find("title", text=True))
links, thumbs, videos, audios = [], [], [], []
for x in X:
try:
links.append(json.loads(str(x[0])+'}'))
except:
try:
links.append(json.loads('{'+str(x[0])+'}'))
except:
continue
for m in links:
try:
if "maxresdefault.jpg" in m["url"]:
thumbs.append(m["url"])
if "mime=video%2" in m["url"]:
videos.append(m["url"])
if "mime=audio%2" in m["url"]:
audios.append(m["url"])
except:
continue
return filename, links, thumbs, videos, audios
filename, links, thumbs, videos, audios = getYouTubeLinks(url)
#Name of the video
print(filename)
#All links
print(len(links), links)
#Thumbnail links
print(len(thumbs), thumbs)
#Video links
print(len(videos), videos)
#Audio links
print(len(audios), audios)
#Downloading files from links
def downloadLink(link, filename):
r = requests.get(link, stream=True, allow_redirects=True)
ext = r.headers.get('content-type').split("/")[-1]
x = filename.replace("/", "_").replace("\\","_")+"."+ext
with open(x, "wb") as file:
i = 0
total_length = int(r.headers.get('content-length'))
print(f"[DOWNLOAD STARTED]: {filename} of {total_length / 1000000:.2} MB" )
for chunk in r.iter_content(chunk_size=1024):
if chunk:
file.write(chunk)
else:
break
print("[DOWNLOAD FINISHED]")
downloadLink(audios[0], filename)