Advertisement
load-net

python_download_yutube

Jan 15th, 2025
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.33 KB | None | 0 0
  1. #myVideo = pytube.YouTube('https://www.youtube.com/watch?v=ZMbkyYmOir0')
  2.  
  3. #from pytube import YouTube
  4. #yt = YouTube("https://www.youtube.com/watch?v=ZMbkyYmOir0")
  5. #print(yt.title)
  6. #mp4files = yt.filter('mp4')
  7. #stream = yt.streams.first()
  8. #stream.download() # this will download in your current working Dir
  9.  
  10.  
  11. import os.path
  12. import time
  13.  
  14. import requests
  15. from tqdm import tqdm
  16.  
  17.  
  18. def playlist_item(url):
  19. headers = {
  20. 'authority': 'api.youtubemultidownloader.com',
  21. 'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "Yandex";v="22"',
  22. 'accept': 'application/json, text/javascript, */*; q=0.01',
  23. 'dnt': '1',
  24. 'sec-ch-ua-mobile': '?0',
  25. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
  26. 'Chrome/98.0.4758.141 YaBrowser/22.3.3.852 Yowser/2.5 Safari/537.36',
  27. 'sec-ch-ua-platform': '"Windows"',
  28. 'origin': 'https://youtubemultidownloader.net',
  29. 'sec-fetch-site': 'cross-site',
  30. 'sec-fetch-mode': 'cors',
  31. 'sec-fetch-dest': 'empty',
  32. 'referer': 'https://youtubemultidownloader.net/',
  33. 'accept-language': 'ru,en;q=0.9,uk;q=0.8',
  34. }
  35.  
  36. params = {
  37. 'url': url,
  38. 'nextPageToken': '',
  39. }
  40.  
  41. response = requests.get('https://api.youtubemultidownloader.com/playlist', params=params, headers=headers).json()
  42. list_items = []
  43. for item in range(0, len(response['items'])):
  44. list_items.append(response['items'][item]['id'])
  45. return list_items
  46.  
  47.  
  48. def get_channel_name(vid_id):
  49. headers = {
  50. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
  51. 'Chrome/98.0.4758.141 Safari/537.36',
  52. 'accept': '*/*',
  53. }
  54.  
  55. params = {
  56. 'key': 'AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8',
  57. 'prettyPrint': 'false',
  58. }
  59.  
  60. json_data = {
  61. 'videoId': vid_id,
  62. 'context': {
  63. 'client': {
  64. 'hl': 'ru',
  65. 'gl': 'RU',
  66. 'remoteHost': '31.173.242.98',
  67. 'deviceMake': '',
  68. 'deviceModel': '',
  69. 'visitorData': 'CgtrdUNhZ3U2VGNEOCiDndSTBg%3D%3D',
  70. 'userAgent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
  71. 'Chrome/98.0.4758.141 Safari/537.36,gzip(gfe)',
  72. 'clientName': 'WEB',
  73. 'clientVersion': '2.20220502.01.00',
  74. 'osName': 'Windows',
  75. 'osVersion': '10.0',
  76. 'originalUrl': 'https://www.youtube.com/watch?v=4MPWVKFaLD8',
  77. 'platform': 'DESKTOP',
  78. 'clientFormFactor': 'UNKNOWN_FORM_FACTOR',
  79. 'configInfo': {
  80. 'appInstallData': 'CIOd1JMGELiLrgUQmN79EhCUj64FEOqQrgUQw_KtBRCY6q0FELfLrQUQ8IKuBRC7ka4FENSDrgUQ6JCu'
  81. 'BRCw7q0FEK_yrQUQgub9EhCR-PwSENi-rQU%3D',
  82. },
  83. 'userInterfaceTheme': 'USER_INTERFACE_THEME_DARK',
  84. 'timeZone': 'Asia/Omsk',
  85. 'browserName': 'Chrome',
  86. 'browserVersion': '98.0.4758.141',
  87. 'screenWidthPoints': 1137,
  88. 'screenHeightPoints': 870,
  89. 'screenPixelDensity': 1,
  90. 'screenDensityFloat': 1,
  91. 'utcOffsetMinutes': 360,
  92. 'connectionType': 'CONN_CELLULAR_4G',
  93. 'memoryTotalKbytes': '8000000',
  94. 'mainAppWebInfo': {
  95. 'graftUrl': 'https://www.youtube.com/watch?v=4MPWVKFaLD8',
  96. 'webDisplayMode': 'WEB_DISPLAY_MODE_BROWSER',
  97. 'isWebNativeShareAvailable': True,
  98. },
  99. 'playerType': 'UNIPLAYER',
  100. 'tvAppInfo': {
  101. 'livingRoomAppMode': 'LIVING_ROOM_APP_MODE_UNSPECIFIED',
  102. },
  103. 'clientScreen': 'WATCH_FULL_SCREEN',
  104. },
  105. 'user': {
  106. 'lockedSafetyMode': False,
  107. },
  108. 'request': {
  109. 'useSsl': True,
  110. 'internalExperimentFlags': [],
  111. 'consistencyTokenJars': [],
  112. },
  113. 'adSignalsInfo': {
  114. 'params': [
  115. {
  116. 'key': 'dt',
  117. 'value': '1651838604229',
  118. },
  119. {
  120. 'key': 'flash',
  121. 'value': '0',
  122. },
  123. {
  124. 'key': 'frm',
  125. 'value': '0',
  126. },
  127. {
  128. 'key': 'u_tz',
  129. 'value': '360',
  130. },
  131. {
  132. 'key': 'u_his',
  133. 'value': '5',
  134. },
  135. {
  136. 'key': 'u_h',
  137. 'value': '1080',
  138. },
  139. {
  140. 'key': 'u_w',
  141. 'value': '1920',
  142. },
  143. {
  144. 'key': 'u_ah',
  145. 'value': '1032',
  146. },
  147. {
  148. 'key': 'u_aw',
  149. 'value': '1920',
  150. },
  151. {
  152. 'key': 'u_cd',
  153. 'value': '24',
  154. },
  155. {
  156. 'key': 'bc',
  157. 'value': '31',
  158. },
  159. {
  160. 'key': 'bih',
  161. 'value': '870',
  162. },
  163. {
  164. 'key': 'biw',
  165. 'value': '1121',
  166. },
  167. {
  168. 'key': 'brdim',
  169. 'value': '43,12,43,12,1920,0,1708,991,1137,870',
  170. },
  171. {
  172. 'key': 'vis',
  173. 'value': '1',
  174. },
  175. {
  176. 'key': 'wgl',
  177. 'value': 'true',
  178. },
  179. {
  180. 'key': 'ca_type',
  181. 'value': 'image',
  182. },
  183. ],
  184. },
  185. },
  186. 'playbackContext': {
  187. 'contentPlaybackContext': {
  188. 'html5Preference': 'HTML5_PREF_WANTS',
  189. 'lactMilliseconds': '2979',
  190. 'referer': 'https://www.youtube.com/watch?v=4MPWVKFaLD8',
  191. 'signatureTimestamp': 19117,
  192. 'autonavState': 'STATE_OFF',
  193. 'autoCaptionsDefaultOn': False,
  194. 'mdxContext': {},
  195. 'playerWidthPixels': 647,
  196. 'playerHeightPixels': 364,
  197. },
  198. },
  199. 'cpn': 'pwy4NMkpT8PY63hl',
  200. 'captionParams': {
  201. 'deviceCaptionsOn': True,
  202. },
  203. 'attestationRequest': {
  204. 'omitBotguardData': True,
  205. },
  206. }
  207.  
  208. print('\n[+] Получаю название канала...')
  209. channel_name = str(requests.post('https://www.youtube.com/youtubei/v1/player', params=params, headers=headers,
  210. json=json_data).json()['videoDetails']['author'])
  211.  
  212. for m in ["?", '"', "/", ":", "#", "|", ",", " ?", "?!", "?!", "? ", " / ", " | "]:
  213. channel_name = channel_name.replace(m, " ")
  214. print(f'[+] Название канала получено: "{channel_name}"')
  215. return channel_name
  216.  
  217.  
  218. def get_video_download(vid_id, channel_name):
  219. headers = {
  220. 'authority': 'downloader.freemake.com',
  221. 'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "Yandex";v="22"',
  222. 'dnt': '1',
  223. 'x-cf-country': 'RU',
  224. 'sec-ch-ua-mobile': '?0',
  225. 'x-user-platform': 'Win32',
  226. 'accept': 'application/json, text/javascript, */*; q=0.01',
  227. 'x-user-browser': 'YaBrowser',
  228. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
  229. 'Chrome/98.0.4758.141 YaBrowser/22.3.3.852 Yowser/2.5 Safari/537.36',
  230. 'x-analytics-header': 'UA-18256617-1',
  231. 'x-request-attempt': '1',
  232. 'x-user-id': '94119398-e27a-3e13-be17-bbe7fbc25874',
  233. 'sec-ch-ua-platform': '"Windows"',
  234. 'origin': 'https://www.freemake.com',
  235. 'sec-fetch-site': 'same-site',
  236. 'sec-fetch-mode': 'cors',
  237. 'sec-fetch-dest': 'empty',
  238. 'referer': 'https://www.freemake.com/ru/free_video_downloader/',
  239. 'accept-language': 'ru,en;q=0.9,uk;q=0.8',
  240. }
  241.  
  242. print(f'[+] Получаю название и ссылку на видео...')
  243. response = requests.get(f'https://downloader.freemake.com/api/videoinfo/{vid_id}', headers=headers).json()
  244. if response['qualities'][0]['qualityInfo']['itag'] == 22:
  245. video_title = str(response['metaInfo']['title'])
  246. for m in ["?", '"', "'", "/", ":", "#", "|", ",", " | "]:
  247. video_title = video_title.replace(m, "")
  248. url = response['qualities'][0]['url']
  249. print(f'[+] Название и ссылка получены. Начинаю загрузку: "{video_title}"...')
  250. if not os.path.isdir(f'{channel_name}'):
  251. os.mkdir(f'{channel_name}')
  252. print(f'[+] Создаю папку для сохранения видео...\n')
  253. else:
  254. print(f'[+] Папка для сохранения существует...\n')
  255. req = requests.get(url=url, headers=headers, stream=True)
  256. total = int(req.headers.get('content-length', 0))
  257. with open(f'{os.path.join(channel_name, f"{video_title}.mp4")}', 'wb') as file, tqdm(
  258. desc=f"{video_title[0:int(len(video_title) / 2)]}...",
  259. total=total,
  260. unit='iB',
  261. unit_scale=True,
  262. unit_divisor=1024,
  263. ) as bar:
  264. for data in req.iter_content(chunk_size=1024):
  265. size = file.write(data)
  266. bar.update(size)
  267. print(f'\n[+] Видео сохранено в папку: "{channel_name}".\n[+] Загрузка завершена.\n')
  268. else:
  269. user_change = input('\n[+] Нет видео в качестве 720р...\n[+] Загрузить в доступном качестве?:\n'
  270. '\t[1]: Да\n\t[2]: Нет\n\t>>> ')
  271. if user_change == "1":
  272. video_title = str(response['metaInfo']['title'])
  273. for m in ["?", '"', "'", "/", ":", "#", "|", ",", " | "]:
  274. video_title = video_title.replace(m, "")
  275. url = response['qualities'][0]['url']
  276. print(f'[+] Название и ссылка получены. Начинаю загрузку: "{video_title}"...')
  277. if not os.path.isdir(f'{channel_name}'):
  278. os.mkdir(f'{channel_name}')
  279. print(f'[+] Создаю папку для сохранения видео...\n')
  280. else:
  281. print(f'[+] Папка для сохранения существует...\n')
  282. req = requests.get(url=url, headers=headers, stream=True)
  283. total = int(req.headers.get('content-length', 0))
  284. with open(f'{os.path.join(channel_name, f"{video_title}.mp4")}', 'wb') as file, tqdm(
  285. desc=f"{video_title[0:int(len(video_title) / 2)]}...",
  286. total=total,
  287. unit='iB',
  288. unit_scale=True,
  289. unit_divisor=1024,
  290. ) as bar:
  291. for data in req.iter_content(chunk_size=1024):
  292. size = file.write(data)
  293. bar.update(size)
  294. print(f'\n[+] Видео сохранено в папку: "{channel_name}".\n[+] Загрузка завершена.\n')
  295. elif user_change == "2":
  296. main()
  297. return
  298. else:
  299. print('[-] Вы ввели чушь. Закрываю программу...')
  300. exit(0)
  301.  
  302.  
  303. def get_target_path(user_input):
  304. if user_input == "1":
  305. vid_id = input('\t[+] Введите ссылку на видео\n\t[+] Для выхода в меню введите: ex\n\t>>> ')
  306. if vid_id == 'ex':
  307. main()
  308. return
  309. while not "https://www.youtube.com" in vid_id:
  310. vid_id = input('\t[+] Введите ссылку на видео\n\t[+] Для выхода в меню введите: ex\n\t>>> ')
  311. if vid_id == 'ex':
  312. main()
  313. return
  314. if '&list' in vid_id:
  315. vid_id = vid_id.split("&")[0].split("=")[-1]
  316. else:
  317. vid_id = vid_id.split("=")[-1]
  318. channel_name = get_channel_name(vid_id)
  319. get_video_download(vid_id, channel_name)
  320. main()
  321. elif user_input == "2":
  322. while not os.path.isfile(user_path := input("\t[+] Введите путь к списку\n\t[+] Для выхода в меню введите: ex\n"
  323. "\t>>> ").replace('"', '')):
  324. if user_path == 'ex':
  325. main()
  326. return
  327. print(f"\n\t[+] Список {user_path} не найден\n")
  328. with open(f'{user_path}', 'r', encoding='utf-8') as file:
  329. video_list = file.readlines()
  330. for video in video_list:
  331. if '&list' in video:
  332. vid_id = video.split("&")[0].split("=")[-1]
  333. else:
  334. vid_id = video.split("=")[-1].strip()
  335. if video.strip() == "":
  336. continue
  337. else:
  338. channel_name = get_channel_name(vid_id)
  339. get_video_download(vid_id, channel_name)
  340. main()
  341. elif user_input == "3":
  342. vid_id = input('\t[+] Введите ссылку на плейлист\n\t[+] Для выхода в меню введите: ex\n\t>>> ')
  343. if vid_id == 'ex':
  344. main()
  345. return
  346. while not "https://www.youtube.com/playlist" in vid_id:
  347. vid_id = input('\t[+] Введите ссылку на плейлист\n\t[+] Для выхода в меню введите: ex\n\t>>> ')
  348. if vid_id == 'ex':
  349. main()
  350. return
  351. list_items = playlist_item(vid_id)
  352. print(f'[+] Видео в плейлисте: {len(list_items)}\n[+] Загружаю плейлист...')
  353. for item in list_items:
  354. channel_name = get_channel_name(item)
  355. time.sleep(0.3)
  356. get_video_download(item, channel_name)
  357. time.sleep(0.3)
  358. main()
  359. elif user_input == "4":
  360. exit(0)
  361. else:
  362. main()
  363.  
  364.  
  365. def main():
  366. get_target_path(input(f'\n[+] Выберите варианты загрузки:\n\t[1] Загрузить видео\n'
  367. f'\t[2] Загрузить видео из списка\n\t[3] Загрузить плейлист\n\t[4] Выход\n\t>>> '))
  368.  
  369.  
  370. if __name__ == "__main__":
  371. main()
  372.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement