#!/usr/bin/env python
# coding: utf-8
from threading import Thread
from googleapiclient.discovery import build
import pafy
import csv
import os
import sys
youtube = build("youtube", "v3", developerKey="REPLACE ME") # в оригинале здесь мой токен
DIRNM="videos"
QUERY="Horses"
PAGES=2
MAXSZ=100 * 1000 ** 2 # 100 megabyte
def csv_writer(filename, dirname):
if not os.path.exists(dirname): os.mkdir(dirname)
csvfile = open(dirnamee + "/" + filename, "w+")
writer = csv.writer(csvfile)
writer.writerow(["FILE","ID","AUTHOR","TITLE","DURATION","VIEWS","THUMBNAIL"])
return writer
def search(query, max_results):
results = youtube.search().list(
q=query,
maxResults=max_results,
part="id"
).execute()
items = results['items']
ids = [vid['id']['videoId'] for vid in items]
return ids
def write(filename, video, writer):
writer.writerow([filename, video.videoid, video.author, video.title, video.duration, video.viewcount, video.bigthumbhd])
def download(video_id, dirname, writer, max_size=100 * 1000 ** 2, quiet=True):
video = pafy.new(video_id)
stream = video.getbest(preftype="mp4")
if stream.get_filesize() < max_size:
filename = video_id + "." + stream.extension
stream.download(filepath=dirname + "/" + filename, quiet=quiet)
if __name__ == "__main__":
writer = csv_writer(file)
ids = search(QUERY, PAGES)
for video_id in ids:
thread = Thread(target=download, args=(video_id, DIRNM, writer, MAXSZ, False))
thread.start()
Файл создается, но ничего в него не записывается