首页 > 其他分享 >当前仍可用的爬取Youtube视频方法

当前仍可用的爬取Youtube视频方法

时间:2024-10-10 20:00:05浏览次数:1  
标签:视频 domain 可用 import Youtube video file path cookie

import yt_dlp  
import http.cookiejar  
import time  
import logging  
import os
import random

# Setup logging  
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')  

def load_cookies_from_netscape(cookie_file):  
    cookie_jar = http.cookiejar.CookieJar()  
    with open(cookie_file, 'r') as file:  
        for line in file:  
            if line.startswith('#') or not line.strip():  
                continue  
            parts = line.strip().split('\t')  
            if len(parts) >= 7:  
                domain, flag, path, expires, name, value = parts[0:6]  
                cookie_jar.set_cookie(http.cookiejar.Cookie(  
                    version=0,  
                    name=name,  
                    value=value,  
                    port=None,  
                    port_specified=False,  
                    domain=domain,  
                    domain_specified=True,  
                    domain_initial_dot=domain.startswith('.'),  
                    path=path,  
                    path_specified=True,  
                    secure=flag == 'TRUE',  
                    expires= None,  
                    discard=True,  
                    comment=None,  
                    comment_url=None,  
                    rest=None  
                ))  
    return cookie_jar  

def download_youtube_videos(video_urls, cookie_file, output_path, user_agent):  
    cookie_jar = load_cookies_from_netscape(cookie_file)  

    ydl_opts = {  
        'cookiejar': cookie_jar,  
        'outtmpl': f'{output_path}/%(id)s.%(ext)s',  # Save file as video ID  
        'http_headers': {  
            'User-Agent': user_agent  
        }  
    }  

    for video_url in video_urls:  
        attempt = 0  
        max_attempts = 2  # Maximum number of retries  
        while attempt < max_attempts:  
            try:  
                with yt_dlp.YoutubeDL(ydl_opts) as ydl:  
                    ydl.download([video_url])  # Note: must pass a list  
                break  # Break if download is successful  
            except Exception as e:  
                logging.error(f"Failed to download {video_url}: {e}")  
                attempt += 1  
                time.sleep(5)  # Delay before retrying  
        else:  
            logging.error(f"Exceeded maximum retries for {video_url}")  

# Example usage  
video_urls = []  
with open('mission.txt', 'r') as file:  
    datas = file.readlines()
    random.shuffle(datas) 
    for data in datas:  
        video_urls.append('https://www.youtube.com/watch?v=' + data.strip())  # Ensure no extra whitespace  

cookie_file = 'youtube.com_cookies.txt'  # Replace with your cookie file path  
output_path = './'  # Replace with your desired output path  
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.5845.96 Safari/537.36'  # Replace with your user agent string  

download_youtube_videos(video_urls, cookie_file, output_path, user_agent)

需要注意的几点是

1,yt_dlp库

2,UA模仿正常用户浏览

3,携带Cookie

其中,mission.txt是待下载的视频ID,youtube.com_cookies.txt为登录Youtube后导出的Cookie,格式如下:

# Netscape HTTP Cookie File
# http://curl.haxx.se/rfc/cookie_spec.html
# This is a generated file!  Do not edit.

.youtube.com	TRUE	/	TRUE ......

可以使用此类工具导出:

标签:视频,domain,可用,import,Youtube,video,file,path,cookie
From: https://www.cnblogs.com/isakovsky/p/18457028

相关文章

  • 【视频笔记】408新增知识点信号——里昂视频
    文章目录**2.信号****3.信号的实现**4.信号的处理**①忽略信号****②执行信号的默认操作****③捕获井处理信号**几个Linux支持的典型信号:**5.信号的产生**①**通过终端按键(键盘)产生信号**例如,`Ctrl+C`发送2号信号SIGINT、`Ctrl+\`发送3号信号SIGQUIT②**程序异常时*......
  • 2024激活Typora,最新版本的1.9.5可用
    目前最新版本 1.9.5也是可以实现激活的注:免修改注册表、不用修改时间,更不需要破解补丁01、下载&安装Typora从官网下载最新版本的Typora,并安装02、激活Typora找到Typora安装目录,依次找到这个文件resources\page-dist\static\js\LicenseIndex.**********.********.chunk.js......
  • 使用ffmpeg修复本地视频文件(mp4)播放时进度条无法拖动的问题
    右击视频文件查看属性,在详细信息页查看视频时长,显示为空,推测进度条无法拖动的原因是时间轴损坏于是采用了以下解决办法将视频分离出来,命名为video.mp4ffmpeg-i视频名称.mp4-map0:v-vcodeccopy-bsf:vh264_mp4toannexbvideo.mp4将音频分离出来,命名为audio.wavffm......
  • SSM舞者网站hwb4m 上传预览视频
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表系统内容:用户,舞蹈分类,舞蹈信息,网站介绍开题报告内容一、课题背景及意义随着互联网技术的快速发展,信息传播方式发生了翻天覆地的变化。舞者网站作为信息传播......
  • 12G-SDI高清视频开发案例,让4K视频采集更便捷!基于Xilinx MPSoC高性能平台
    本文主要介绍基于XilinxUltraScale+MPSoCXCZU7EV的12G-SDI高清视频开发案例,适用开发环境如下:Windows开发环境:Windows764bit、Windows1064bitLinux开发环境:Ubuntu18.04.464bit开发工具包:XilinxUnified2022.2硬件平台:创龙科技TLZU-EVM评估板(基于XilinxUltraScale+......
  • PC软件开发新体验!用 Blazor Hybrid 打造简洁高效的视频处理工具
    前言国庆假期各种活动比较多,直到上班才有时间来更新文章~不过这两天我还是做了个小玩意(Clipify),起因是想给之前开发来自己用的简单视频剪辑工具QuickCutSharp加个功能,不过这个软件是基于WinForms开发的,做界面得拖拉控件,感觉繁琐又不灵活,于是索性重新做一个。原有代码是C#,于......
  • 【FMC214】基于VITA57.1标准的4路12G SDI视频传输FMC子卡模块
     板卡概述FMC214是基于VITA57.1标准的4路12GSDI视频传输FMC子卡模块,该板卡可以作为一个理想的IO单元耦合至FPGA前端,4路BNC接口形式的SDI信号通过电平转换(线缆均衡器)连接至FMC(HPC)接口的高速串行总线上,与FPGA内部的万兆位级收发器(MGT)互联,FPGA内部的SDI固件IP来完成SDI的编解码。......
  • 视频汇聚平台EasyCVR支持云端录像丨监控存储丨录像回看丨录像计划丨录像配置
    EasyCVR视频汇聚融合平台,是TSINGSEE青犀视频垂直深耕音视频流媒体技术、AI智能技术领域的杰出成果。平台以其强大的视频处理、汇聚与融合能力,在构建视频监控系统中展现出了独特的优势。EasyCVR视频汇聚平台可接入传统监控行业中高清网络摄像机的RTSP直播流,及RTMP、HTTP-FLV、HLS(......
  • 矿井人员视频行为分析
    矿井人员视频行为分析系统通过在矿井内部布设监控摄像头,矿井人员视频行为分析实时监测人员的作业行为,矿井人员视频行为分析利用视频分析技术,对人员的行为进行自动分析和识别,并与安全标准进行比对。矿井人员视频行为分析通过视频分析和行为识别,可以及时发现不符合安全要求的行为,预......
  • 基于springboot的网上选课管理系统(含源码+sql+视频导入教程+文档+PPT)
    ......