使用 Python 下载 YouTube 视频到某个目录 [英] Download YouTube video using Python to a certain directory

查看:34
本文介绍了使用 Python 下载 YouTube 视频到某个目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已尝试使用以下代码在 YouTube 中下载视频并且可以正常工作,但我想将视频保存在特定位置.现在它将视频保存在 C:/Users/Download 中.如果我想把视频保存在桌面,代码需要做哪些改动?

I have tried the following code to download a video in YouTube and it is working, but I want to save the video at a particular location. Now it is saving the video in C:/Users/Download. If I want to save the video in the desktop, what changes do I need in the code?

from __future__ import unicode_literals
import youtube_dl
import urllib
import shutil
ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['https://www.youtube.com/watch?v=n06H7OcPd-g'])

推荐答案

我发现了一个非常酷的 python 模块,它允许您轻松地从 youtube 下载视频.安装:

I found out a really cool python module that allows you to download videos from youtube easily. TO install it:

pip install pytube

现在,您可以像这样下载视频 -

Now, You can download your video like this -

from pytube import YouTube
yt = YouTube("https://www.youtube.com/watch?v=n06H7OcPd-g")
yt = yt.get('mp4', '720p')
yt.download('/path/to/download/directory')

Boom,现在您可以轻松地使用 Python 轻松抓取此类视频;现在,我们喝酒!

Boom, Now you can easily scrape such videos using Python easily; Now, We Drink!

感谢@Chiramisu 的评论,您可以使用以下单行下载最高质量的视频:

Thanks to @Chiramisu's comment, You can use the following one-liner to download the highest quality video:

YouTube('video_url').streams.first().download('save_path')

对于 Windows,请使用双反斜杠指定路径,例如:

For Windows, please specify path with double backslashes ex:

YouTube('video_url').streams.first().download('C:\\Users\\username\\save_path')

更新 2:

如果 pytube 似乎不适合您,请尝试使用 youtube-dl:

Update 2:

If pytube doesn't seem to work for you, try using youtube-dl:

sudo -H pip install --upgrade youtube-dl

现在下载视频:

from __future__ import unicode_literals
import youtube_dl

ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['https://www.youtube.com/watch?v=BaW_jenozKc'])

有关 Python 中 ytdl 的更多信息 这里.

More info on ytdl in python here.

这篇关于使用 Python 下载 YouTube 视频到某个目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆