You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Eel框架中打开文件对话框以选择YouTube视频下载路径?

Solution: Implement File Dialog in Eel for YouTube Downloader

Absolutely! You can easily add a folder selection dialog to your Eel app—combining JavaScript for the frontend dialog and Python to handle the download path with PyTube. Let's break this down into actionable steps that fit your existing setup:

Step 1: Set Up Eel Basics

First, make sure you have Eel installed (pip install eel). We'll structure your app so the frontend can communicate seamlessly with the Python backend.

Step 2: Modify the Frontend to Add Folder Selection

Update your HTML to add a click handler to the download button. We'll use a reliable folder selection method that works in Eel's Chrome environment, then send both the YouTube URL and selected path to Python via Eel's cross-language communication.

Here's the updated HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Downloader</title>
    <link rel="stylesheet" href="main.css">
    <!-- Load Eel's JavaScript library -->
    <script type="text/javascript" src="/eel.js"></script>
</head>
<body>
    <div class="container">
        <h1>Downloader</h1>
        <div class="line"></div>
        <form id="downloadForm">
            <label for="">Enter YouTube video URL</label>
            <input type="text" class="youtubeUrl" placeholder="Paste the URL here" required>
            <button type="button" id="downloadBtn">Download</button>
        </form>
    </div>

    <script>
        document.getElementById('downloadBtn').addEventListener('click', () => {
            const urlInput = document.querySelector('.youtubeUrl');
            const videoUrl = urlInput.value.trim();
            
            if (!videoUrl) {
                alert('Please enter a valid YouTube URL!');
                return;
            }

            // Create hidden input to trigger folder selection
            const folderInput = document.createElement('input');
            folderInput.type = 'file';
            folderInput.style.display = 'none';
            folderInput.directory = true; // Enable folder selection
            document.body.appendChild(folderInput);

            // Handle folder selection
            folderInput.addEventListener('change', () => {
                const downloadPath = folderInput.files[0].path;
                // Send URL and path to Python backend
                eel.download_youtube_video(videoUrl, downloadPath)()
                    .then(() => alert('Download completed successfully!'))
                    .catch(err => alert(`Error: ${err}`));
                document.body.removeChild(folderInput);
            });

            // Trigger the dialog
            folderInput.click();
        });
    </script>
</body>
</html>

Step 3: Update the Python Backend with Eel

Rewrite your Python code to use Eel, expose a function that receives the URL and download path, and handle the PyTube download logic.

Here's the Python code:

import eel
from pytube import YouTube

# Initialize Eel: point to the folder containing your frontend files
eel.init('web')  # Ensure your HTML/CSS are in a folder named 'web'

@eel.expose
def download_youtube_video(video_url, download_path):
    """Exposed function to handle YouTube video download"""
    try:
        video = YouTube(video_url)
        stream = video.streams.get_highest_resolution()
        stream.download(output_path=download_path)
        return "Success"
    except Exception as e:
        # Raise error to be caught by frontend
        raise Exception(f"Download failed: {str(e)}")

if __name__ == "__main__":
    # Launch the app in Chrome with a fixed window size
    eel.start('index.html', mode='chrome', size=(600, 400))

Step 4: Project File Structure

Organize your files like this to ensure Eel works correctly:

your_downloader_app/
├── web/
│   ├── index.html
│   └── main.css
└── app.py

How to Run

  1. Install required packages: pip install eel pytube
  2. Run app.py—a Chrome window will open with your downloader interface.
  3. Paste a YouTube URL, click Download, select your target folder, and the video will save directly to that location.

Key Notes

  • We use the input type="file" directory method because it reliably returns the absolute folder path (which PyTube needs), unlike modern browser APIs that restrict path access for security.
  • Error handling is added on both frontend (missing URL alerts) and backend (catching PyTube exceptions and relaying them to the user).

内容的提问来源于stack exchange,提问作者Akash p

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 14:13:15