מבוא
הקוד הזה מאפשר להוריד סרטונים מ-YouTube באמצעות הספרייה pytube. הספרייה זו מספקת ממשק קל לשימוש להורדת סרטונים מ-YouTube, כולל סרטונים בפורמטים שונים, כגון MP4, AVI ו-MP3.
from pytube import YouTube
import time
import sys
def main():
url = input("Enter the URL of the video to download: ")
try:
yt = YouTube(url)
streams = yt.streams
print("Select the format and quality of the video to download:")
for i, stream in enumerate(streams):
print(f"{i + 1}. {stream.resolution} - {stream.type}")
selection = input("Select an option: ")
stream = streams[int(selection) - 1]
print("Starting download...")
for i in range(100):
time.sleep(0.1)
sys.stdout.write("\rProgress: %d%%" % i)
sys.stdout.flush()
sys.stdout.write("\n")
stream.download()
print("Video downloaded successfully:", yt.title)
except Exception as e:
print("Error downloading the video:", e)
if __name__ == "__main__":
main()
-הסבר שורה אחר שורה:
קודם כל מייבאים את הספריות pytube , time , sys
from pytube import YouTube
import time
import sys
-מגדיר את הפונקציה main().
def main():
-מקבלים מהמשתמש את כתובת ה-URL של הסרטון להורדה ומאחסן אותה בתוך המשתנה url.
url = input("Enter the URL of the video to download: ")
-יוצרים אובייקט של YouTube עם כתובת ה-URL של הסרטון.
yt = YouTube(url)
-מקבלים רשימה של כל הרזולוציות הזמינות.
streams = yt.streams
- מדפיסים רשימה של הרזולוציות הזמינות עם מספרים.
print("Select the format and quality of the video to download:")
for i, stream in enumerate(streams):
print(f"{i + 1}. {stream.resolution} - {stream.type}")
-מקבלים את הבחירה של המשתמש.(מספר) בכוונה לא שמתי int.
selection = input("Select an option: ")
-מתחילים את הנפשת ההורדה.
print("Starting download...")
-מדפיסים איך מתקדמת ההורדה.
for i in range(100):
time.sleep(0.1)
sys.stdout.write("\rProgress: %d%%" % i)
sys.stdout.flush()
sys.stdout.write("\n")
-מורידים את הסרטון.
stream.download()
-אם הוריד בהצלחה מדפיס הודעה.
print("Video downloaded successfully:", yt.title)
-אם יש שגיאה באיזהו שלב מדפיס שגיאה.
except Exception as e:
print("Error downloading the video:", e)
-אחר כך קוראים לפונקציה main().
if __name__ == "__main__":
main()
הערה
צריך להתקין את הספריה דרך PIP.
pip install pytube
הנה הקובץ להורדה: YouTube.py
בהנאה!