Below is a Python script that accomplishes the task you described. It uses libraries like requests, BeautifulSoup, os, and zipfile to fetch, process, and save the images. Make sure you have the required libraries installed (pip install requests beautifulsoup4).
import os
import re
import requests
from bs4 import BeautifulSoup
import zipfile
from pathlib import Path
def extract_series_id(url):
"""Extract series ID from the URL."""
parts = url.split('/')
return parts[-1]
def fetch_page(url):
"""Fetch the HTML content of a page."""
response = requests.get(url)
response.raise_for_status()
return response.text
def extract_title(html):
"""Extract and shorten the title from the HTML."""
soup = BeautifulSoup(html, 'html.parser')
title_tag = soup.find('h1', class_=lambda x: x and 'font-bold' in x and 'capitalize' in x)
if title_tag:
title = title_tag.get_text(strip=True)
short_title = re.sub(r'[^a-zA-Z0-9 ]', '', title)[:20].strip()
return short_title
return "unknown_title"
def extract_chapters(html):
"""Extract chapter IDs from the HTML."""
soup = BeautifulSoup(html, 'html.parser')
chapters_div = soup.find('div', id='chapters')
if chapters_div:
chapters = chapters_div.find_all('a', href=True)
return [chapter['href'].split('/')[-1] for chapter in chapters]
return []
def download_chapter_images(series_id, chapter_id, tmp_folder, base_url="https://example.com"):
"""Download images for a chapter and save them to a temporary folder."""
page_num = 1
while True:
image_url = f"{base_url}/storage/series/webtoon/{series_id}/chapters/{chapter_id}/{page_num:03}.jpg"
try:
response = requests.get(image_url)
response.raise_for_status()
with open(os.path.join(tmp_folder, f"{page_num:03}.jpg"), 'wb') as f:
f.write(response.content)
page_num += 1
except requests.exceptions.HTTPError:
break
def zip_folder(folder_path, output_filename):
"""Zip the contents of a folder."""
with zipfile.ZipFile(output_filename, 'w') as zipf:
for root, _, files in os.walk(folder_path):
for file in files:
zipf.write(os.path.join(root, file), file)
def main(series_url):
# Extract series ID
series_id = extract_series_id(series_url)
# Fetch series page
series_html = fetch_page(series_url)
# Extract title
short_title = extract_title(series_html)
# Extract chapters
chapter_ids = extract_chapters(series_html)
# Process each chapter
for i, chapter_id in enumerate(chapter_ids, start=1):
tmp_folder = f"tmp_chapter_{i:02}"
os.makedirs(tmp_folder, exist_ok=True)
download_chapter_images(series_id, chapter_id, tmp_folder)
# Zip the folder and rename it
output_filename = f"{short_title}-chapter-{i:02}.cbz"
zip_folder(tmp_folder, output_filename)
# Clean up temporary folder
for file in os.listdir(tmp_folder):
os.remove(os.path.join(tmp_folder, file))
os.rmdir(tmp_folder)
if __name__ == "__main__":
series_url = "https://example.com/series/b804ce9a-7e94-4f03-bddb-c14a763d1d7f"
main(series_url)
Key Points and Questions:
- Error Handling: The script includes basic error handling for HTTP requests. Let me know if you want more robust error handling.
- Temporary Folder Cleanup: The script cleans up temporary folders after zipping. Is this behavior desired?
- Base URL: The base URL is hardcoded as
"https://example.com". Should it be configurable?
- Chapter Numbering: The script assumes chapter IDs are sequential. If not, how should chapters be named?
- Rate Limiting: The script does not handle rate limiting. Should it include delays between requests?
Let me know if you need further adjustments!