最近,我喜欢看视频,所以我四处游荡,终于来到了世界上最大的视频平台。
[En]
Recently, I like to watch videos, so I wander around and finally come to the largest video platform in the world.
心动不如行动 ,咱们直接用python开整,好看的视频都给它下载下来,完事了喊上表弟一起看~
表弟:
不多哔哔,咱们开始吧~
; 环境模块
开发环境
这里咱们安装Python3 ,推荐3.6-3.8,编辑器还是pycharm,但是可以下载pycharm 2021 ,新版本自带汉化插件,直接安装就可以汉化了。
对于不会说英语的兄弟来说,这是一种福气。
[En]
It’s a blessing for brothers who don’t speak English.
模块
这里本次用到的两个第三方模块需要pip安装一下
requests # 数据请求模块
tqdm #进度条配置
Python学习交流群:815624229
没有软件,不会安装软件,不会安装模块、报错了等等,或者Python相关学习资料、代码、视频、解答等等,都在上面的裙了。
我想给你看一段攀登后的视频。
[En]
I would like to show you a video after climbing.
表弟:呸,就一个?就这就这?能不能多放点!
实现步骤
pa虫的步骤讲了这么多遍,不知道各位记住了没有~
首先,让我们打开目标页面,然后搜索我们最喜欢的视频。
[En]
First of all, let’s open the target page and then search for our favorite videos.
至于如何进入这个网站,请慢慢听我说。
[En]
As for how to get into this website, listen to me slowly.
声明一下,我只说怎么去下载,至于怎么进这个网站,这个不是我能教的,大家自行百度,我有点慌~
emmm~
我们不谈这个了,让我们回去寻找我们最喜欢的视频,比如
[En]
Let’s not talk about this, let’s go back to searching for our favorite videos, such as
啊哼,别担心我搜索了什么,这不是重点!
[En]
Ahem, don’t worry about what I searched, that’s not the point!
那我们就以这段视频为例,让我们直截了当。
[En]
Then let’s take this video as an example, let’s be plain.
咱们点开视频,然后按 F12 打开开发者工具,然后刷新网页,去找到我们的数据包内容。
刷新后,它会慢慢加载包,我们可以在里面找到很多内容,我不会详细写了,大家可以看到我的视频,详细的步骤都已经录下来了。
[En]
After refreshing, it will slowly load the packet, we can find a lot of content inside, I will not write in detail, you can see my video, the detailed steps have been recorded.
视频地址:【Python爬取YouTube视频】
为什么不写呢,主要是因为太多了,人不喜欢看,只喜欢看代码,危害~
[En]
Why not write it, mainly because it is too much, people do not like to read, only like to look at the code, harm ~
; 代码展示
导入模块
这些都是需要使用的模块。需要安装的模块都是内置模块,不需要安装。
[En]
These are all the modules that need to be used. The modules that need to be installed are all built-in modules, which do not need to be installed.
import requests # 数据请求模块
import re # 正则表达式模块
import json # 数据类型处理模块
from tqdm import tqdm #进度条配置
import os # 处理文件和目录
发送请求获取数据
headers = {
'cookie': 'VISITOR_INFO1_LIVE=9qZVrzB27uI; PREF=f4=4000000&tz=Asia.Shanghai; _ga=GA1.2.621834420.1648121145; _gcl_au=1.1.1853038046.1648121145; NID=511=Zc1APdmEbCD-iqVNVgI_vD_0S3LVI3XSfl-wUZEvvMU2MLePFKsQCaKUlUtchHSg-kWEVMGOhWUbxpQMwHeIuLjhxaslwniMh1OsjVfmOeTfhpwcRYpMgqpZtNQ7qQApY21xEObCvIez6DCMbjRhRQ5P7siOD3X87QX0CFyUxmY; OTZ=6430350_24_24__24_; GPS=1; YSC=0E115KqM_-I; GOOGLE_ABUSE_EXEMPTION=ID=d02004902c3d0f4d:TM=1648620854:C=r:IP=47.57.243.77-:S=YmZXPW7dxbu83bDuauEpXpE; CONSISTENCY=AGDxDeNysJ2boEmzRP4v6cwgg4NsdN4-FYQKHCGhA0AeW1QjFIU1Ejq1j8l6lwAc6c-pYTJiSaQItZ1M6QeI1pQ3wictnWXTOZ6_y8EKlt0Y_JdakwW6srR39-NLuPgSgXrXwtS0XTUGXpdnt4k3JjQ',
'referer': 'https://www.youtube.com/results?search_query=jk%E7%BE%8E%E5%A5%B3',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.36'
}
url = 'https://www.youtube.com/watch?v=ImoXcSpR_io'
response = requests.get(url=url, headers=headers)
print(response.text)
匹配json数据
json_str = re.findall('var ytInitialPlayerResponse = (.*?);var', response.text)[0]
json字符串转变为字典
json_data = json.loads(json_str)
提取视频链接
video_url = json_data['streamingData']['adaptiveFormats'][0]['url']
提取音频链接
audio_url = json_data['streamingData']['adaptiveFormats'][-2]['url']
提取标题
title = json_data['videoDetails']['title']
替换掉标题当中的空格
title = title.replace(' ', '')
替换标题中的非法字符
[En]
Replace the illegal characters in the title
title = re.sub(r'[\/:|?*"<>]', '', title)
print(video_url)
print(audio_url)
print(title)
向视频链接发送请求
video = requests.get(video_url, stream=True)
获取视频大小
file_size = int(video.headers.get('Content-Length'))
初始化进度条大小
video_pbar = tqdm(total=file_size)
开始保存视频
with open(f'{title}.mp4', mode='wb') as f:
# 把视频分成 1024 * 1024 * 2 为等分的大小 进行遍历
for video_chunk in video.iter_content(1024*1024*2):
# 写入数据
f.write(video_chunk)
# 更新进度条
video_pbar.set_description(f'正在下载{title}视频中......')
# 更新进度条长度
video_pbar.update(1024*1024*2)
# 下载完毕
video_pbar.set_description('下载完成!')
# 关闭进度条
video_pbar.close()
音频同理
audio = requests.get(audio_url, stream=True)
file_size = int(audio.headers.get('Content-Length'))
audio_pbar = tqdm(total=file_size)
with open(f'{title}.mp3', mode='wb') as f:
for audio_chunk in audio.iter_content(1024*1024*2):
f.write(audio_chunk)
audio_pbar.set_description(f'正在下载{title}音频中......')
audio_pbar.update(1024*1024*2)
audio_pbar.set_description('下载完成!')
audio_pbar.close()
使用FFmpeg进行合并
def merge(title):
ffmpeg = r'D:\Download\ffmpeg\bin\ffmpeg.exe -i ' + title + '.mp4 -i ' + title + '.mp3 -acodec copy -vcodec copy ' + title + '-out.mp4'
os.popen(ffmpeg)
merge(title)
兄弟们赶紧试试吧!
记得点赞收藏评论,爱你!
[En]
Remember to like the collection comments, love you!
Original: https://www.cnblogs.com/hahaa/p/16089280.html
Author: 轻松学Python
Title: python爬取YouTube视频
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/500138/
转载文章受原作者版权保护。转载请注明原作者出处!