该项目包括使用YTAPI在播放列表中列出所有youtube视频,然后下载视频。 Im使用CSV文件,通过将视频id附加到CSV,确保不再下载相同的视频(相同的视频id)
with open('video-id.csv','a+',newline='') as csv_file:
writer = csv.writer(csv_file)
reader = csv.reader(csv_file)
youtube api代码
for video in videos["items"]:
video_id = video["contentDetails"]["videoId"]
if video_id in reader:
print('duplicate')
elif video_id not in csv_file:
# converts the videoID to a link shich can be used by pytube module
video_url = "https://www.youtube.com/watch?v=" + video_id
# defines url for the pytube module
video = YouTube(video_url)
# only returns 'streams' which are soley 'audio' using the 'first' one in the list (highest audio bitrate)
video_stream = video.streams.filter(only_audio=True).first()
print('Downloading',video_title + '...')
video_stream.download()
# appends id to csv to ensure the video is not downloaded again
writer.writerow({video_id})
CVS文件已成功追加,但每次运行脚本时都会追加相同的视频id,我正在努力找到一种方法来检查csv文件是否有匹配的视频id,以防止发生这种情况
CVS文件:
hi9_oyKAAds
b3T4b3GCRk4
hi9_oyKAAds
b3T4b3GCRk4
hi9_oyKAAds
b3T4b3GCRk4
hi9_oyKAAds
b3T4b3GCRk4
希望下面的评论能有所帮助:
当您第一次读取像
video_id in reader
这样的文件时,然后要重新读取它,您需要使用seek()
方法将“滑块”移动到文件的开头:在读卡器(
video_id in reader
)中检查视频id时,请注意读卡器中的项是一个列表:将返回:
如果使用csv_文件(在代码中)进行迭代,请注意它包含
video_id not in csv_file
个字符,如下所示:会回来的
相关问题 更多 >
编程相关推荐