download_video.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import html
  2. import subprocess
  3. import time
  4. import requests
  5. from loguru import logger
  6. class DownLoad:
  7. @classmethod
  8. def download_video(cls, video_url, video_path_url):
  9. video = video_path_url + 'video.mp4'
  10. url_type = html.unescape(video_url).split('?')[0]
  11. if ".m3u8" in url_type:
  12. logger.info(f"[+] {video_url}开始下载m3u8格式的视频")
  13. ffmpeg_cmd_oss = [
  14. "ffmpeg",
  15. "-y", # 覆盖输出文件
  16. "-protocol_whitelist", "file,http,https,tcp,tls",
  17. "-i", video_url, # 输入文件
  18. "-c", "copy", # 复制视频流
  19. "-bsf:a", "aac_adtstoasc", # 转换 AAC 音频格式
  20. video # 输出文件
  21. ]
  22. subprocess.run(ffmpeg_cmd_oss)
  23. return video
  24. else:
  25. try:
  26. for i in range(3):
  27. payload = {}
  28. headers = {}
  29. response = requests.request("GET", video_url, headers=headers, data=payload, timeout=240)
  30. if response.status_code == 200:
  31. # 以二进制写入模式打开文件
  32. with open(f"{video}", "wb") as file:
  33. # 将响应内容写入文件
  34. file.write(response.content)
  35. time.sleep(5)
  36. return video
  37. return None
  38. except Exception:
  39. return None