Download Youtube with Python

How to download youtube with python? using youtube-dl package.

Youtube-dl package

1
$ python3 -m youtube_dl -f 140 --proxy http://$host:$post -g https://m.youtube.com/watch?v=id | xargs -n 1 python3 downloader.py -p -n 16 -o "test.m4a" --

Varify SHA256 and MD5

1
2
3
4
5
6
7
8
9
10
11
12
13
def validate_file(file_path, hash):
md5 = hashlib.md5()
sha256 = hashlib.sha256()
with open(file_path, 'rb') as f:
while True:
chunk = f.read(1024 * 1024)
if not chunk:
break
md5.update(chunk)
sha256.update(chunk)
print('md5sum: ' + md5.hexdigest())
print('sha256sum: ' + sha256.hexdigest())
return md5.hexdigest() == hash

Check ranges support

1
2
3
4
5
6
7
8
9
10
11
12
13
def pre_headers(url, file_name):
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
with open(file_name, 'r') as f:
head = f.read().split('\n')
head = dict(zip(head[0::2],head[1::2]))
# If-Match | If-Unmodified-Since | If-None-Match | If-Modified-Since
# if head['etag']:
# headers['If-Match'] = f'{head["etag"]}'
# if head['last-modified']:
# headers['If-Unmodified-Since'] = head['last-modified']
headers['If-Range'] = head['etag'] or head['last-modified']
headers['Range'] = f'bytes=0-9'
return headers