Well, I can get the video formats directly by using this in terminal -
$ youtube-dl -F "some youtube url"
Output :
[youtube] Setting language
[youtube] P9pzm5b6FFY: Downloading webpage
[youtube] P9pzm5b6FFY: Downloading video info webpage
[youtube] P9pzm5b6FFY: Extracting video information
[info] Available formats for P9pzm5b6FFY:
format code extension resolution note
140 m4a audio only DASH audio , audio@128k (worst)
160 mp4 144p DASH video , video only
133 mp4 240p DASH video , video only
134 mp4 360p DASH video , video only
135 mp4 480p DASH video , video only
136 mp4 720p DASH video , video only
17 3gp 176x144
36 3gp 320x240
5 flv 400x240
43 webm 640x360
18 mp4 640x360
22 mp4 1280x720 (best)
but I want to use the same option while using youtube-dl as a module in python .
Right now I have to guess and specify the options for downloading as :
import youtube_dl
options = {
'format': 'bestaudio/best', # choice of quality
'extractaudio' : True, # only keep the audio
'audioformat' : "mp3", # convert to mp3
'outtmpl': '%(id)s', # name the file the ID of the video
'noplaylist' : True, # only download single song, not playlist
}
with youtube_dl.YoutubeDL(options) as ydl:
ydl.download(url)
I'm unable to know which format is available or not. but if I can get to list the available formats , then I can set those options accordingly .
Is there any way to use that "-F" switch inside python ?
If you use the listformats
option to print the table to standard output, it won't download the video. For example:
import youtube_dl
options = {
'format': 'bestaudio/best', # choice of quality
'extractaudio': True, # only keep the audio
'audioformat': "mp3", # convert to mp3
'outtmpl': '%(id)s', # name the file the ID of the video
'noplaylist': True, # only download single song, not playlist
'listformats': True, # print a list of the formats to stdout and exit
}
with youtube_dl.YoutubeDL(options) as ydl:
ydl.download(['http://www.youtube.com/watch?v=BaW_jenozKc'])
Look at the source code of youtube-dl, I see how do they list format of video
def list_formats(self, info_dict):
formats = info_dict.get('formats', [info_dict])
table = [
[f['format_id'], f['ext'], self.format_resolution(f), self._format_note(f)]
for f in formats
if f.get('preference') is None or f['preference'] >= -1000]
if len(formats) > 1:
table[-1][-1] += (' ' if table[-1][-1] else '') + '(best)'
header_line = ['format code', 'extension', 'resolution', 'note']
self.to_screen(
'[info] Available formats for %s:\n%s' %
(info_dict['id'], render_table(header_line, table)))
So is it very simple to get list the available formats by this way
ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
meta = ydl.extract_info(
'https://www.youtube.com/watch?v=9bZkp7q19f0', download=False)
formats = meta.get('formats', [meta])
for f in formats:
print(f['ext'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With