Certainly! Below is a Python script that implements a generalized, reusable, and scalable pipeline to process a user-provided URL. The script performs the following tasks:
- Name Generation: Creates a suitable directory name based on the provided URL.
- Content Extraction: Fetches the content of the URL and extracts all downloadable links.
- Categorization: Categorizes the links based on their file extensions (e.g.,
.pdf, .pptx, .ipynb, .py).
- Directory Structure Creation: Creates separate folders for each file extension.
- File Downloading: Downloads the files into their respective folders with comprehensive error handling.
The script adheres to PEP-8 standards, uses type hints for clarity, optimizes performance for handling large datasets, and includes robust error handling mechanisms.
import os
import re
import requests
from urllib.parse import urlparse, urljoin
from typing import List, Dict
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor, as_completed
# Define constants
VALID_EXTENSIONS = [
'pdf', 'pptx', 'ipynb', 'py', 'jpg', 'jpeg', 'png', 'docx', 'xlsx', 'zip', 'tar', 'gz'
]
MAX_WORKERS = 10 # Number of threads for downloading
def generate_folder_name(url: str) -> str:
"""
Generate a suitable folder name from the given URL.
Args:
url (str): The URL to process.
Returns:
str: A sanitized folder name.
"""
parsed_url = urlparse(url)
folder_name = f"{parsed_url.netloc}_{parsed_url.path.strip('/').replace('/', '_')}"
folder_name = re.sub(r'[^\w\-_. ]', '_', folder_name)
return folder_name or "downloaded_files"
def get_all_links(url: str) -> List[str]:
"""
Retrieve all valid links from the given URL.
Args:
url (str): The URL to scrape.
Returns:
List[str]: A list of absolute URLs found on the page.
"""
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
except requests.RequestException as e:
raise ConnectionError(f"Failed to fetch URL '{url}': {e}")
soup = BeautifulSoup(response.text, 'html.parser')
links = set()
for tag in soup.find_all(['a', 'link']):
href = tag.get('href')
if href:
absolute_url = urljoin(url, href)
links.add(absolute_url)
return list(links)
def categorize_links(links: List[str]) -> Dict[str, List[str]]:
"""
Categorize links based on their file extensions.
Args:
links (List[str]): A list of URLs.
Returns:
Dict[str, List[str]]: A dictionary mapping extensions to their respective URLs.
"""
categorized = {ext: [] for ext in VALID_EXTENSIONS}
for link in links:
path = urlparse(link).path
ext = os.path.splitext(path)[1][1:].lower()
if ext in VALID_EXTENSIONS:
categorized[ext].append(link)
return categorized
def create_directories(base_path: str, extensions: Dict[str, List[str]]) -> Dict[str, str]:
"""
Create directories for each file extension.
Args:
base_path (str): The base directory path.
extensions (Dict[str, List[str]]): The extensions dictionary.
Returns:
Dict[str, str]: A dictionary mapping extensions to their directory paths.
"""
dirs = {}
for ext in extensions:
ext_dir = os.path.join(base_path, ext)
os.makedirs(ext_dir, exist_ok=True)
dirs[ext] = ext_dir
return dirs
def download_file(session: requests.Session, url: str, dest_path: str) -> None:
"""
Download a single file from the URL to the destination path.
Args:
session (requests.Session): The HTTP session.
url (str): The file URL.
dest_path (str): The destination file path.
"""
try:
with session.get(url, stream=True, timeout=10) as response:
response.raise_for_status()
with open(dest_path, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
except requests.RequestException as e:
print(f"Failed to download '{url}': {e}")
except OSError as e:
print(f"Error saving '{dest_path}': {e}")
def download_files(extensions: Dict[str, List[str]], directories: Dict[str, str]) -> None:
"""
Download all files categorized by extensions into their respective directories.
Args:
extensions (Dict[str, List[str]]): The extensions dictionary.
directories (Dict[str, str]): The directories mapping.
"""
with requests.Session() as session:
with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
future_to_url = {}
for ext, urls in extensions.items():
for url in urls:
filename = os.path.basename(urlparse(url).path)
if not filename:
filename = f"unnamed.{ext}"
dest_path = os.path.join(directories[ext], filename)
future = executor.submit(download_file, session, url, dest_path)
future_to_url[future] = url
for future in as_completed(future_to_url):
url = future_to_url[future]
try:
future.result()
except Exception as e:
print(f"Unexpected error downloading '{url}': {e}")
def main(url: str) -> None:
"""
Main function to execute the pipeline.
Args:
url (str): The URL to process.
"""
try:
folder_name = generate_folder_name(url)
os.makedirs(folder_name, exist_ok=True)
print(f"Created base directory: {folder_name}")
links = get_all_links(url)
print(f"Found {len(links)} links.")
categorized = categorize_links(links)
for ext, urls in categorized.items():
print(f" - {ext}: {len(urls)} files")
directories = create_directories(folder_name, categorized)
download_files(categorized, directories)
print("Download completed successfully.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Generalized Pipeline to Download Files from a URL")
parser.add_argument('url', type=str, help='The URL to process')
args = parser.parse_args()
main(args.url)
Explanation of the Script
-
Imports and Constants:
- Utilizes standard libraries such as
os, re, requests, urllib.parse, and concurrent.futures for threading.
BeautifulSoup from bs4 is used for HTML parsing.
- Defines a list of valid file extensions to categorize downloaded files.
- Sets a maximum number of worker threads to optimize downloading speed.
-
Function generate_folder_name:
- Parses the URL to create a sanitized folder name by removing invalid characters.
- Ensures that the folder name is filesystem-friendly.
-
Function get_all_links:
- Fetches the content of the provided URL.
- Parses the HTML to extract all anchor and link tags.
- Converts relative URLs to absolute URLs.
- Handles connection-related exceptions gracefully.
-
Function categorize_links:
- Iterates through all extracted links.
- Categorizes them based on predefined valid file extensions.
- Ensures only supported file types are processed.
-
Function create_directories:
- Creates a base directory derived from the URL.
- Within the base directory, creates subdirectories for each file extension.
- Ensures directories are created only once and handles existing directories.
-
Function download_file:
- Handles the downloading of individual files.
- Uses streaming to handle large files efficiently.
- Includes error handling for network issues and file I/O problems.
-
Function download_files:
- Manages the concurrent downloading of files using a thread pool.
- Submits download tasks to the executor and handles their completion.
-
Function main:
- Orchestrates the entire pipeline.
- Handles high-level exceptions to ensure robustness.
- Provides informative print statements for user feedback.
-
Usage
-
Install Dependencies:
Ensure that the required libraries are installed. You can install requests and beautifulsoup4 using pip:
pip install requests beautifulsoup4
-
Run the Script:
Execute the script from the command line by providing the target URL:
python download_pipeline.py https://web.stanford.edu/~jurafsky/slp3/
Replace download_pipeline.py with the filename you saved the script as.
Features and Best Practices
- PEP-8 Compliance: The code is structured with proper naming conventions, indentation, and spacing for readability.
- Type Hints: Utilizes Python's
typing module to provide type annotations, enhancing code clarity and maintainability.
- Concurrency: Implements multi-threading to download multiple files simultaneously, improving performance.
- Error Handling: Comprehensive try-except blocks ensure that the script can handle unexpected issues gracefully without crashing.
- Modularity: The script is divided into well-defined functions, making it easy to maintain and extend.
- Scalability: Designed to handle large numbers of files and large file sizes efficiently.
- User Feedback: Provides clear console messages to inform the user about the progress and any issues encountered.
This script serves as a robust foundation for a generalized file downloading pipeline and can be further extended or integrated into larger systems as needed.