I'll create a Python script to download images from a webtoon-style site based on your requirements. First, let me ask a few clarifying questions:
- Is the chapter ID in the URL the same as the chapter number (e.g., does "Chapter 20" correspond to chapter_id "101257c2-1b72-4eed-b54b-587c66e83427")?
- Should the script stop trying page numbers after the first 404 error (assuming sequential numbering), or should it try all 99 pages regardless?
- Do you want any error handling for cases where the series page structure changes?
- Should the script create a subdirectory for each series, or save all CBZ files directly to the current working directory?
- Do you need any progress reporting during the download process?
Here's a basic implementation based on your requirements:
import os
import re
import requests
import zipfile
from bs4 import BeautifulSoup
from urllib.parse import urlparse
def sanitize_title(title):
# Keep only alphanumeric and spaces, first ~20 chars
sanitized = re.sub(r'[^a-zA-Z0-9 ]', '', title)
return sanitized[:20].strip()
def download_series(series_url):
# Extract series ID from URL
parsed_url = urlparse(series_url)
series_id = os.path.basename(parsed_url.path)
# Fetch series page
try:
response = requests.get(series_url)
response.raise_for_status()
except requests.RequestException as e:
print(f"Error fetching series page: {e}")
return
soup = BeautifulSoup(response.text, 'html.parser')
# Extract title
title_tag = soup.find('h1', class_=re.compile(r'font-bold capitalize'))
if not title_tag:
print("Could not find title in page")
return
title = title_tag.get_text(strip=True)
short_title = sanitize_title(title)
print(f"Processing series: {title} (ID: {series_id})")
# Find chapters
chapters_div = soup.find('div', id='chapters')
if not chapters_div:
print("Could not find chapters div")
return
chapter_links = chapters_div.find_all('a', href=re.compile(r'/read/'))
if not chapter_links:
print("No chapter links found")
return
# Create temp directory
temp_dir = f"temp_{short_title}"
os.makedirs(temp_dir, exist_ok=True)
for chapter_link in chapter_links:
chapter_url = chapter_link['href']
chapter_id = os.path.basename(chapter_url)
chapter_num = chapter_link.get('aria-label', '').replace('Chapter ', '')
if not chapter_num:
chapter_num = chapter_link.get('title', '').replace('Chapter ', '')
if not chapter_num:
chapter_num = chapter_link.get_text(strip=True).replace('Chapter ', '')
if not chapter_num:
print(f"Could not determine chapter number for {chapter_url}")
continue
chapter_num = chapter_num.zfill(2) # Pad with zeros for consistent sorting
print(f"Processing Chapter {chapter_num} (ID: {chapter_id})")
# Download pages
page_num = 1
while True:
page_filename = f"{page_num:03d}.jpg"
page_url = f"https://example.com/storage/series/webtoon/{series_id}/chapters/{chapter_id}/{page_filename}"
try:
page_response = requests.get(page_url, stream=True)
if page_response.status_code == 404:
break # End of chapter
page_response.raise_for_status()
# Save page
page_path = os.path.join(temp_dir, page_filename)
with open(page_path, 'wb') as f:
for chunk in page_response.iter_content(1024):
f.write(chunk)
page_num += 1
except requests.RequestException as e:
print(f"Error downloading page {page_num}: {e}")
break
# Create CBZ if we got any pages
if page_num > 1:
cbz_filename = f"{short_title}-chapter-{chapter_num}.cbz"
with zipfile.ZipFile(cbz_filename, 'w') as zipf:
for root, _, files in os.walk(temp_dir):
for file in sorted(files):
file_path = os.path.join(root, file)
zipf.write(file_path, os.path.basename(file_path))
print(f"Created {cbz_filename}")
# Clean up temp files
for file in os.listdir(temp_dir):
os.remove(os.path.join(temp_dir, file))
# Remove temp directory
os.rmdir(temp_dir)
print("Download complete!")
if __name__ == "__main__":
series_url = input("Enter the series URL: ")
download_series(series_url)
Important notes about this script:
-
You'll need to install the required packages:
pip install requests beautifulsoup4
-
The script assumes:
- The series ID is the last part of the URL path
- Chapter numbers are sequential and start from 001
- Pages are named with 3-digit numbers (001.jpg, 002.jpg, etc.)
- The script stops when it encounters a 404 error (assuming pages are sequential)
-
The script creates a temporary directory for downloads and cleans up after creating each CBZ file.
-
You may need to adjust the selectors (like the h1 class) to match the actual website structure.
-
The script includes basic error handling but could be enhanced with more robust error recovery.
Would you like me to modify any part of this script to better match your requirements?