Thư viện pytube cho phép tải video YouTube dễ dàng, miễn phí, không quảng cáo hay giới hạn như các phần mềm thương mại.
Cài đặt
pip install pytube
Sử dụng cơ bản
from pytube import YouTube
# Khởi tạo đối tượng YouTube
yt = YouTube('https://www.youtube.com/watch?v=-KnAZcXzxRA')
# Thông tin video
print(yt.title) # Tiêu đề
print(yt.thumbnail_url) # URL thumbnail
Xem các định dạng có sẵn (streams)
for stream in yt.streams.all():
print(stream)
# Kết quả: Danh sách Stream với itag, mime_type, res, fps, vcodec, acodec...
Tải video
Cách 1: Tải stream đầu tiên (thường là 720p mp4)
stream = yt.streams.first()
stream.download('f:/') # Lưu vào F:\
# Hoặc thư mục hiện tại
stream.download()
Cách 2: Chọn chất lượng cụ thể
# Lọc stream: mp4, 1080p, progressive (video+audio) stream = yt.streams.filter(file_extension='mp4', res='1080p', progressive=True).first() stream.download()
Cách 3: Chỉ tải audio
audio_stream = yt.streams.filter(only_audio=True).first() audio_stream.download(filename='audio.mp3')
Kết quả
File video được lưu tại thư mục chỉ định với tên gốc của video YouTube.
Lưu ý quan trọng
- YouTube thường xuyên thay đổi API → pytube cần cập nhật thường xuyên
- Video có bản quyền, age-restricted, private có thể không tải được
- Tuân thủ Terms of Service của YouTube
- Phiên bản mới:
pip install pytubefix(fork được maintain tích cực hơn)