Certainly! Below is a Python version of your Kotlin scraper tailored to extract the list of chapters from the specified URL. This implementation uses the requests library for HTTP requests and BeautifulSoup from bs4 for HTML parsing. The code is structured to fit within the my.noveldokusha.scraper.sources package.
Directory Structure
Assuming you're organizing your project with the following structure:
my/
└── noveldokusha/
└── scraper/
└── sources.py
sources.py
# my/noveldokusha/scraper/sources.py
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin, urlparse
from dataclasses import dataclass
from typing import List, Optional
@dataclass
class BookResult:
title: str
url: str
cover_image_url: Optional[str] = None
@dataclass
class ChapterResult:
title: str
url: str
@dataclass
class PagedList:
items: List[BookResult]
index: int
is_last_page: bool
class NovelBinScraper:
"""
A scraper to extract novel information and chapters from NovelBin.
"""
def __init__(self):
self.base_url = "https://novelbin.me/"
self.catalog_url = "https://novelbin.me/sort/novelbin-daily-update"
self.session = requests.Session()
self.session.headers.update({
"User-Agent": (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/58.0.3029.110 Safari/537.3"
)
})
def get_chapter_list(self, book_url: str) -> List[ChapterResult]:
"""
Extracts the list of chapters from the given book URL.
Args:
book_url (str): The URL of the novel's main page.
Returns:
List[ChapterResult]: A list of chapters with their titles and URLs.
"""
# Fetch the main book page
response = self.session.get(book_url)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
# Extract the 'og:url' meta property to get the novel ID
meta_og_url = soup.find('meta', property='og:url')
if not meta_og_url:
raise ValueError("Cannot find og:url meta tag in the book page.")
og_url = meta_og_url.get('content', '')
if not og_url:
raise ValueError("og:url meta tag does not contain content.")
parsed_url = urlparse(og_url)
key_id = parsed_url.path.rstrip('/').split('/')[-1]
# Construct the AJAX URL to fetch chapters
ajax_endpoint = urljoin(self.base_url, "ajax/chapter-archive")
params = {
"novelId": key_id
}
headers = {
"Accept": "*/*",
"X-Requested-With": "XMLHttpRequest",
"Referer": f"{book_url}#tab-chapters-title"
}
# Send the AJAX request to get the chapter list
ajax_response = self.session.get(ajax_endpoint, params=params, headers=headers)
ajax_response.raise_for_status()
ajax_soup = BeautifulSoup(ajax_response.text, 'html.parser')
# Parse the chapters
chapters = []
for a_tag in ajax_soup.select("ul.list-chapter li a"):
title = a_tag.get('title', '').strip()
href = a_tag.get('href', '').strip()
if title and href:
full_url = urljoin(self.base_url, href)
chapters.append(ChapterResult(title=title, url=full_url))
return chapters
def get_book_cover_image_url(self, book_url: str) -> Optional[str]:
"""
Retrieves the cover image URL of the book.
Args:
book_url (str): The URL of the novel's main page.
Returns:
Optional[str]: The URL of the cover image or None if not found.
"""
response = self.session.get(book_url)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
meta_image = soup.find('meta', itemprop='image')
if meta_image:
return meta_image.get('content', None)
return None
def get_book_description(self, book_url: str) -> Optional[str]:
"""
Extracts the description of the book.
Args:
book_url (str): The URL of the novel's main page.
Returns:
Optional[str]: The description text or None if not found.
"""
response = self.session.get(book_url)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
desc_div = soup.find('div', class_='desc-text')
if desc_div:
return desc_div.get_text(strip=True)
return None
def get_catalog_list(self, page: int = 1) -> PagedList:
"""
Retrieves a paginated list of books from the catalog.
Args:
page (int, optional): The page number to retrieve. Defaults to 1.
Returns:
PagedList: A paginated list of books.
"""
params = {}
if page > 1:
params['page'] = str(page)
response = self.session.get(self.catalog_url, params=params)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
# Determine if this is the last page
pagination = soup.select_one("ul.pagination")
is_last_page = True
if pagination:
next_btn = pagination.find('li', class_='next')
if next_btn and 'disabled' not in next_btn.get('class', []):
is_last_page = False
# Extract books
book_elements = soup.select("#list-page div.list-novel .row")
books = []
for element in book_elements:
link = element.select_one("div.col-xs-7 a")
if not link:
continue
title = link.get('title', '').strip()
href = link.get('href', '').strip()
cover_image = element.select_one("div.col-xs-3 > div > img")
cover_url = cover_image.get('data-src', '').strip() if cover_image else ''
if title and href:
full_url = urljoin(self.base_url, href)
books.append(BookResult(title=title, url=full_url, cover_image_url=cover_url))
return PagedList(items=books, index=page - 1, is_last_page=is_last_page)
def search_catalog(self, query: str, page: int = 1) -> PagedList:
"""
Searches the catalog for books matching the query.
Args:
query (str): The search keyword.
page (int, optional): The page number to retrieve. Defaults to 1.
Returns:
PagedList: A paginated list of search results.
"""
params = {'keyword': query}
if page > 1:
params['page'] = str(page)
search_url = urljoin(self.base_url, "search")
response = self.session.get(search_url, params=params)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
# Determine if this is the last page
pagination = soup.select_one("ul.pagination")
is_last_page = True
if pagination:
next_btn = pagination.find('li', class_='next')
if next_btn and 'disabled' not in next_btn.get('class', []):
is_last_page = False
# Extract books
book_elements = soup.select("#list-page div.list-novel .row")
books = []
for element in book_elements:
link = element.select_one("div.col-xs-7 a")
if not link:
continue
title = link.get('title', '').strip()
href = link.get('href', '').strip()
cover_image = element.select_one("div.col-xs-3 > div > img")
cover_url = cover_image.get('data-src', '').strip() if cover_image else ''
if title and href:
full_url = urljoin(self.base_url, href)
books.append(BookResult(title=title, url=full_url, cover_image_url=cover_url))
return PagedList(items=books, index=page - 1, is_last_page=is_last_page)
Usage Example
Here's how you can use the NovelBinScraper class to fetch the list of chapters from the specified novel URL:
# example_usage.py
from my.noveldokusha.scraper.sources import NovelBinScraper
def main():
novel_url = "https://novelbin.me/novel-book/atticuss-odyssey-reincarnated-into-a-playground#tab-chapters-title"
scraper = NovelBinScraper()
try:
# Fetch chapter list
chapters = scraper.get_chapter_list(novel_url)
print(f"Chapters for '{novel_url}':")
for idx, chapter in enumerate(chapters, start=1):
print(f"{idx}. {chapter.title} - {chapter.url}")
# Optionally, fetch book cover image
cover_url = scraper.get_book_cover_image_url(novel_url)
print(f"\nCover Image URL: {cover_url}")
# Optionally, fetch book description
description = scraper.get_book_description(novel_url)
print(f"\nDescription:\n{description}")
# Optionally, fetch catalog list
catalog = scraper.get_catalog_list(page=1)
print(f"\nCatalog Page {catalog.index + 1}:")
for book in catalog.items:
print(f"- {book.title} ({book.url})")
# Optionally, search the catalog
search_results = scraper.search_catalog(query="Odyssey", page=1)
print(f"\nSearch Results for 'Odyssey':")
for book in search_results.items:
print(f"- {book.title} ({book.url})")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
main()
Explanation
-
Data Classes:
BookResult: Represents a book with its title, URL, and optional cover image URL.
ChapterResult: Represents a chapter with its title and URL.
PagedList: Represents a paginated list of books, including the current page index and a flag indicating if it's the last page.
-
NovelBinScraper Class:
- Initialization: Sets up the base URLs and initializes a
requests.Session with a default User-Agent header to mimic a browser.
get_chapter_list Method:
- Fetches the main book page and parses it to extract the
og:url meta tag, which contains the novel ID.
- Constructs an AJAX request to fetch the chapter archive using the extracted novel ID.
- Parses the AJAX response to extract all chapter links and their titles.
- Additional Methods:
get_book_cover_image_url: Extracts the cover image URL from the book page.
get_book_description: Extracts the book description from the book page.
get_catalog_list: Fetches a paginated list of books from the catalog.
search_catalog: Searches the catalog for books matching a query.
-
Usage Example:
- Demonstrates how to instantiate the scraper and use its methods to fetch chapters, cover image, description, catalog list, and perform a search.
- Includes basic error handling to catch and display any exceptions that occur during scraping.
Dependencies
Make sure to install the required Python packages before running the scraper:
pip install requests beautifulsoup4
Notes
- Error Handling: The scraper includes basic error handling using
raise_for_status() to ensure HTTP requests are successful. Additional error checks are in place to handle missing elements in the HTML structure.
- Respect Robots.txt: Before deploying this scraper, ensure that you're complying with the website's
robots.txt and terms of service.
- Rate Limiting: For production use, consider adding rate limiting and retries to handle network issues and avoid overloading the target website.
- Asynchronous Requests: If you require asynchronous scraping for performance reasons, consider using libraries like
aiohttp and BeautifulSoup with asyncio.
This Python implementation should provide a solid foundation for scraping chapter lists and other related data from NovelBin. You can further expand the scraper by implementing additional features and refining the existing methods as needed.