| import os | |
| import time | |
| import requests | |
| from bs4 import BeautifulSoup | |
| import gradio as gr | |
| import tempfile | |
| from urllib.parse import urljoin, urlparse, parse_qs | |
| import re | |
| from collections import defaultdict | |
| import zipfile | |
| def sanitize_filename(name): | |
| """Remove invalid characters from filenames.""" | |
| safe_name = re.sub(r'[\\/*?:"<>|]', "", name).strip() | |
| safe_name = safe_name[:150] # Limit length | |
| return safe_name if safe_name else "Unknown" | |
| def detect_series_name(title): | |
| """ | |
| Try to extract series name from post title. | |
| Handles patterns like: | |
| - "Series Name - Chapter 123" | |
| - "Series Name Chapter 123" | |
| - "SSCOTE 126: Title" | |
| - "DxD Chapter 5" | |
| - "1-2" (novel-chapter format) | |
| """ | |
| # Pattern 1: "Series - Chapter X" or "Series: Chapter X" | |
| match = re.match(r'^(.+?)\s*[-:]\s*(?:Chapter|Ch\.?)\s+\d+', title, re.IGNORECASE) | |
| if match: | |
| return match.group(1).strip() | |
| # Pattern 2: "ACRONYM Chapter X" (like "DxD Chapter 5", "BSCOTE 3") | |
| match = re.match(r'^([A-Z]{2,}(?:\s+[A-Z]{2,})?)\s+(?:Chapter|Ch\.?)?\s*\d+', title) | |
| if match: | |
| return match.group(1).strip() | |
| # Pattern 3: "Novel-Chapter" format (like "1-2", "16-35") | |
| match = re.match(r'^\d+-\d+$', title) | |
| if match: | |
| return "Numbered Series" | |
| # Pattern 4: Extract series name before chapter indicator | |
| match = re.match(r'^(.+?)\s+(?:Chapter|Ch\.?)\s+\d+', title, re.IGNORECASE) | |
| if match: | |
| return match.group(1).strip() | |
| # Pattern 5: Series name with "!" at the end | |
| match = re.match(r'^(.+!)\s*[-:]?\s*(?:Chapter|Ch\.?)?\s*\d*', title) | |
| if match: | |
| return match.group(1).strip() | |
| # Default: Take first significant part before delimiter | |
| parts = re.split(r'\s*[-:]\s*', title) | |
| if parts: | |
| return parts[0].strip() | |
| return "Uncategorized" | |
| def extract_kemono_posts_from_page(page_url, headers): | |
| """Extract all post links from a single Kemono page.""" | |
| try: | |
| response = requests.get(page_url, headers=headers, timeout=15) | |
| response.raise_for_status() | |
| # Check if it's an error page | |
| if "404" in response.text or "No posts found" in response.text or len(response.text) < 500: | |
| return None, "Error page detected" | |
| soup = BeautifulSoup(response.text, 'html.parser') | |
| # Kemono uses <article> tags or specific divs for posts | |
| # Common selectors: article.post-card, div.post-card, a with class containing 'post' | |
| post_links = [] | |
| # Try multiple selectors for Kemono structure | |
| for article in soup.find_all('article'): | |
| link_tag = article.find('a', href=True) | |
| if link_tag: | |
| full_url = urljoin(page_url, link_tag['href']) | |
| if '/post/' in full_url: | |
| post_links.append(full_url) | |
| # Alternative: direct links to posts | |
| if not post_links: | |
| for a_tag in soup.find_all('a', href=True): | |
| if '/post/' in a_tag['href']: | |
| full_url = urljoin(page_url, a_tag['href']) | |
| if full_url not in post_links: | |
| post_links.append(full_url) | |
| return post_links, None | |
| except Exception as e: | |
| return None, str(e) | |
| def paginate_kemono_creator(base_url, headers, progress=gr.Progress()): | |
| """ | |
| Paginate through all pages of a Kemono creator using ?o=0, ?o=50, etc. | |
| Returns all post links. | |
| """ | |
| all_posts = [] | |
| offset = 0 | |
| page_num = 1 | |
| while True: | |
| # Construct URL with offset | |
| if '?' in base_url: | |
| page_url = f"{base_url}&o={offset}" | |
| else: | |
| page_url = f"{base_url}?o={offset}" | |
| progress(0, desc=f"Scanning page {page_num} (offset {offset})...") | |
| post_links, error = extract_kemono_posts_from_page(page_url, headers) | |
| if error or post_links is None or len(post_links) == 0: | |
| # Reached the end | |
| break | |
| all_posts.extend(post_links) | |
| offset += 50 | |
| page_num += 1 | |
| # Small delay to avoid rate limiting | |
| time.sleep(0.3) | |
| return all_posts | |
| def scrape_kemono_post(post_url, headers): | |
| """Scrape a single Kemono post and return title and content.""" | |
| try: | |
| response = requests.get(post_url, headers=headers, timeout=15) | |
| response.raise_for_status() | |
| soup = BeautifulSoup(response.text, 'html.parser') | |
| # Extract title | |
| title = "Untitled" | |
| title_tag = soup.find('h1', class_='post__title') | |
| if not title_tag: | |
| title_tag = soup.find('h1') | |
| if title_tag: | |
| title = title_tag.get_text(strip=True) | |
| # Extract content | |
| lines = [] | |
| # Kemono uses div.post__content or similar | |
| content_div = soup.find('div', class_='post__content') | |
| if not content_div: | |
| # Try alternative selectors | |
| content_div = soup.find('div', {'class': re.compile('content|post-content|body')}) | |
| if content_div: | |
| # Process content | |
| for br in content_div.find_all('br'): | |
| br.replace_with('\n') | |
| # Extract paragraphs | |
| for p in content_div.find_all(['p', 'div']): | |
| text = p.get_text(strip=True) | |
| if text and len(text) > 10: # Filter out very short lines | |
| lines.append(text) | |
| # If no paragraphs found, get all text | |
| if not lines: | |
| raw_text = content_div.get_text(separator='\n', strip=True) | |
| for paragraph in raw_text.split('\n'): | |
| clean_para = paragraph.strip() | |
| if clean_para and len(clean_para) > 10: | |
| lines.append(clean_para) | |
| return title, lines, None | |
| except Exception as e: | |
| return None, None, str(e) | |
| def extract_links_from_main_page(main_url, headers): | |
| """Fetches the main novel page and extracts all chapter links and the novel title.""" | |
| try: | |
| response = requests.get(main_url, headers=headers, timeout=15) | |
| response.raise_for_status() | |
| soup = BeautifulSoup(response.text, 'html.parser') | |
| # --- EXTRACT THE TITLE --- | |
| title = "Compiled_Novel" | |
| # Most novel sites (like Novelhall) place the main title in an <h1> tag | |
| h1_tag = soup.find('h1') | |
| if h1_tag: | |
| title = h1_tag.get_text(strip=True) | |
| elif soup.title: | |
| title = soup.title.get_text(strip=True) | |
| # Target the specific container for all chapters on Novelhall | |
| morelist_div = soup.find('div', id='morelist') | |
| links = [] | |
| if morelist_div: | |
| # Find all anchor <a> tags inside the list | |
| for a_tag in morelist_div.find_all('a', href=True): | |
| # Ensure the link is an absolute URL | |
| full_url = urljoin(main_url, a_tag['href']) | |
| links.append(full_url) | |
| return links, title, None | |
| except Exception as e: | |
| return [], None, f"Failed to extract links from the main page: {e}" | |
| def scrape_novel(input_mode, input_text, progress=gr.Progress()): | |
| if not input_text.strip(): | |
| return None, "Error: No input provided." | |
| headers = { | |
| 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36' | |
| } | |
| links = [] | |
| novel_title = "Compiled_Novel" # Fallback default title | |
| is_kemono = False | |
| # ========================================== | |
| # 1. DETERMINE INPUT MODE & GET LINKS | |
| # ========================================== | |
| if input_mode == "Kemono Creator Page": | |
| is_kemono = True | |
| creator_url = input_text.strip() | |
| progress(0, desc="Extracting all posts from Kemono creator...") | |
| links = paginate_kemono_creator(creator_url, headers, progress) | |
| if not links: | |
| return None, "Error: Could not find any posts. Ensure it is a valid Kemono creator page." | |
| # Extract creator name from URL for folder name | |
| parsed = urlparse(creator_url) | |
| path_parts = parsed.path.strip('/').split('/') | |
| if len(path_parts) >= 2: | |
| novel_title = f"{path_parts[0]}_{path_parts[1]}" | |
| elif input_mode == "Main Novel Page URL (Novelhall)": | |
| main_url = input_text.strip() | |
| progress(0, desc="Extracting links from main page...") | |
| links, extracted_title, err = extract_links_from_main_page(main_url, headers) | |
| if err: | |
| return None, err | |
| if not links: | |
| return None, "Error: Could not find any chapter links. Ensure it is a valid Novelhall main page." | |
| # Override the default title with the extracted one | |
| if extracted_title: | |
| novel_title = extracted_title | |
| else: | |
| # Default: Process the Textbox as a list of links | |
| links = [line.strip() for line in input_text.split('\n') if line.strip()] | |
| if not links: | |
| return None, "Error: No links to process." | |
| # ========================================== | |
| # 2. SCRAPE BASED ON SITE TYPE | |
| # ========================================== | |
| if is_kemono: | |
| # Group posts by series | |
| series_data = defaultdict(list) # {series_name: [(title, content), ...]} | |
| for idx, link in progress.tqdm(enumerate(links, 1), total=len(links), desc="Downloading Posts"): | |
| try: | |
| title, content_lines, error = scrape_kemono_post(link, headers) | |
| if error: | |
| series_data["Errors"].append((f"Error at {link}", [error])) | |
| continue | |
| if title and content_lines: | |
| # Detect series name | |
| series = detect_series_name(title) | |
| series_data[series].append((title, content_lines)) | |
| # Rate limiting | |
| if idx < len(links): | |
| time.sleep(0.2) | |
| except Exception as e: | |
| series_data["Errors"].append((f"Error at {link}", [str(e)])) | |
| # ========================================== | |
| # 3. CREATE SEPARATE FILES FOR EACH SERIES | |
| # ========================================== | |
| output_dir = tempfile.mkdtemp() | |
| zip_path = os.path.join(tempfile.gettempdir(), f"{sanitize_filename(novel_title)}_novels.zip") | |
| with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf: | |
| for series_name, posts in series_data.items(): | |
| if not posts: | |
| continue | |
| # Sort posts by title to maintain order | |
| posts.sort(key=lambda x: x[0]) | |
| # Compile text for this series | |
| series_text = "" | |
| for title, content in posts: | |
| series_text += f"{'='*80}\n" | |
| series_text += f"{title}\n" | |
| series_text += f"{'='*80}\n\n" | |
| series_text += '\n\n'.join(content) | |
| series_text += "\n\n\n" | |
| # Save to file | |
| filename = f"{sanitize_filename(series_name)}.txt" | |
| file_path = os.path.join(output_dir, filename) | |
| with open(file_path, 'w', encoding='utf-8') as f: | |
| f.write(series_text) | |
| # Add to zip | |
| zipf.write(file_path, filename) | |
| total_series = len([s for s in series_data.keys() if s != "Errors"]) | |
| return zip_path, f"Success! Extracted {len(links)} posts grouped into {total_series} series. Download the ZIP file." | |
| else: | |
| # Original Novelhall/Novelbin scraping | |
| compiled_text = "" | |
| for idx, link in progress.tqdm(enumerate(links, 1), total=len(links), desc="Downloading Chapters"): | |
| try: | |
| response = requests.get(link, headers=headers, timeout=15) | |
| response.raise_for_status() | |
| soup = BeautifulSoup(response.text, 'html.parser') | |
| lines = [] | |
| # --- Fallback: Grab novel title from the first chapter if using the links list --- | |
| if idx == 1 and novel_title == "Compiled_Novel": | |
| if soup.title: | |
| # Page titles are usually formatted like "Chapter 1 - Novel Title - Site" | |
| page_title = soup.title.get_text(strip=True) | |
| parts = page_title.split('-') | |
| if len(parts) >= 2: | |
| novel_title = parts[1].strip() | |
| else: | |
| novel_title = page_title.strip() | |
| # --- FUTURE SITES CAN BE ADDED HERE --- | |
| if 'novelhall.com' in link: | |
| header_div = soup.find('div', class_='single-header') | |
| if header_div and header_div.find('h1'): | |
| lines.append(header_div.find('h1').get_text(strip=True)) | |
| content_div = soup.find('div', id='htmlContent') | |
| if content_div: | |
| for br in content_div.find_all('br'): | |
| br.replace_with('\n') | |
| raw_text = content_div.get_text(separator='\n', strip=True) | |
| for paragraph in raw_text.split('\n'): | |
| clean_para = paragraph.strip() | |
| if clean_para: | |
| lines.append(clean_para) | |
| else: | |
| lines.append(f"Content missing for {link}") | |
| elif 'novelbin.com' in link: | |
| content_div = soup.find('div', id='chr-content') | |
| if content_div: | |
| h4 = content_div.find('h4') | |
| if h4: | |
| lines.append(h4.get_text(strip=True)) | |
| for p in content_div.find_all('p'): | |
| text = p.get_text(strip=True) | |
| if text: | |
| lines.append(text) | |
| else: | |
| lines.append(f"Content missing for {link}") | |
| else: | |
| lines.append(f"Unsupported site for link: {link}") | |
| # Compile lines into a chapter block | |
| chapter_text = '\n\n'.join(lines) | |
| compiled_text += chapter_text + '\n\n\n' | |
| except requests.exceptions.HTTPError as e: | |
| if response.status_code == 403: | |
| compiled_text += f"Error processing chapter {idx} ({link}): 403 Forbidden (Blocked by bot protection)\n\n\n" | |
| else: | |
| compiled_text += f"Error processing chapter {idx} ({link}): {e}\n\n\n" | |
| except Exception as e: | |
| compiled_text += f"Error processing chapter {idx} ({link}): {e}\n\n\n" | |
| # ========================================== | |
| # 3. DOWNLOAD SPEED REGULATOR | |
| # ========================================== | |
| if idx < len(links): | |
| # Speed set to 5 requests per second (0.2s delay) | |
| time.sleep(0.2) | |
| # ========================================== | |
| # 4. SAVE FILE WITH THE NOVEL TITLE | |
| # ========================================== | |
| safe_title = sanitize_filename(novel_title) | |
| # Use the system's temp directory, but dictate the exact file name | |
| output_dir = tempfile.gettempdir() | |
| file_path = os.path.join(output_dir, f"{safe_title}.txt") | |
| # Write the compiled file | |
| with open(file_path, 'w', encoding='utf-8') as f: | |
| f.write(compiled_text) | |
| return file_path, f"Success! Extracted and downloaded {len(links)} chapters as '{safe_title}.txt'." | |
| # ========================================== | |
| # GRADIO WEB INTERFACE | |
| # ========================================== | |
| with gr.Blocks(theme=gr.themes.Soft()) as app: | |
| gr.Markdown("# ๐ Enhanced Web Novel Scraper") | |
| gr.Markdown(""" | |
| **Supports:** | |
| - ๐ฅ **Kemono** (Auto-paginated, groups by series, downloads as ZIP) | |
| - ๐ **Novelhall** (High Speed) | |
| - ๐ **Novelbin** | |
| **For Kemono:** Just paste the creator's main page URL (e.g., `https://kemono.su/patreon/user/12345`) | |
| """) | |
| with gr.Row(): | |
| with gr.Column(): | |
| # Radio button to let the user pick the mode | |
| input_mode = gr.Radio( | |
| choices=["Kemono Creator Page", "Main Novel Page URL (Novelhall)", "List of Chapter Links"], | |
| value="Kemono Creator Page", | |
| label="What are you scraping?" | |
| ) | |
| links_input = gr.Textbox( | |
| lines=10, | |
| label="Paste your Input Here", | |
| placeholder="https://kemono.su/patreon/user/12345 (or novelhall URL, or list of links)" | |
| ) | |
| scrape_btn = gr.Button("Scrape & Compile", variant="primary") | |
| with gr.Column(): | |
| status_output = gr.Textbox(label="Status", interactive=False) | |
| file_output = gr.File(label="Download Compiled Novel(s)") | |
| gr.Markdown(""" | |
| ### ๐ How it works: | |
| **Kemono Mode:** | |
| 1. Automatically paginates through all pages (?o=0, ?o=50, ?o=100...) | |
| 2. Extracts all posts | |
| 3. Groups posts by detected series name | |
| 4. Creates separate .txt files for each series | |
| 5. Returns everything in a ZIP file | |
| **Novelhall/Novelbin Mode:** | |
| - Paste main page URL or list of chapter links | |
| - Downloads all chapters into one file | |
| """) | |
| # Connect the button to the function | |
| scrape_btn.click( | |
| fn=scrape_novel, | |
| inputs=[input_mode, links_input], | |
| outputs=[file_output, status_output] | |
| ) | |
| if __name__ == "__main__": | |
| app.launch() | |
Xet Storage Details
- Size:
- 18.5 kB
- Xet hash:
- c04e3b8d691777f73c36260d7608d57a1f3799f89768d20889f70332abf4be9a
ยท
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.