citeget.core¶
Core search and download logic for libgen (libgen.vg-family mirrors).
Requires: playwright (with chromium browser installed).
Install browsers: python -m playwright install chromium
The flow:
Construct search URL with query + topic
Load page in headless Chromium (JS-rendered table)
Parse results table into list of dicts
For each result to download: a. Visit /ads.php to get session key b. Download file from /get.php
Mirror configuration¶
Libgen mirrors rotate domains often, and a mirror can also be unreachable
because the local network/DNS blocks it (e.g. resolving it to 127.0.0.1).
search() therefore tries several mirrors in order and raises
MirrorUnreachableError with an actionable message if none respond.
Override the mirror list without editing code:
CITEGET_LIBGEN_MIRRORS— comma-separated base URLs (highest precedence)CITEGET_LIBGEN_BASE_URL— a single base URLor pass
base_url=/mirrors=tosearch()/search_and_download()
Only libgen.vg-family mirrors (JS #tablelibgen layout) are compatible with
this parser; the older libgen.is/.rs/.st forks use different HTML.
Functions
|
Probe each configured mirror and report which ones are healthy. |
|
Download the best match for a specific title, falling through on failure. |
|
Download a single result. |
|
Download multiple results. |
|
Acquire one copy of a specific book. |
|
Search a libgen mirror and return a list of result dicts. |
|
Search libgen and download matching results in one shot. |
Exceptions
Raised when no libgen mirror could be reached. |
- exception citeget.core.MirrorUnreachableError[source]¶
Bases:
RuntimeErrorRaised when no libgen mirror could be reached.
Distinct from an empty result set: this means every candidate mirror failed to connect (down, moved, or blocked by local DNS/network), so the caller gets an actionable message instead of a raw Playwright stack trace.
- citeget.core.check_mirrors(*, mirrors=None, query='design of everyday things', topic='books', timeout=45000, table_timeout=20000, headless=True, verbose=False)[source]¶
Probe each configured mirror and report which ones are healthy.
Mirror domains rotate, so the default list goes stale on its own schedule. This turns the resulting “citeget is broken” into the actionable “your mirror list needs updating”, and gives you the working list to pass to
CITEGET_LIBGEN_MIRRORS.- Parameters:
mirrors (
tuple|list|None) – Mirrors to probe; defaults to the configured list.query (
str) – Search terms to probe with. Should be something with results.topic (
str) – Libgen topic to search.timeout (
int) – Page navigation timeout in ms.table_timeout (
int) – How long to wait for the results table, in ms.headless (
bool) – Headless browser mode.verbose (
bool) – Print each result as it is probed.
- Return type:
- Returns:
One dict per mirror with keys
mirror,ok,results,elapsed_msanderror, in the order probed.
- citeget.core.download_best(results, *, title, authors=None, download_dir='.', max_candidates=5, page=None, timeout=60000, delay=1.0, headless=True, try_mirrors=True, verbose=False, validate=True, policy=None, **rank_kwargs)[source]¶
Download the best match for a specific title, falling through on failure.
Ranks results against the title and author actually wanted (see
citeget.rank) and downloads them in that order until one validates. Falling through matters as much as ranking does: libgen catalogues excerpts, front-matter samples and reviews under the full work’s title, and the next candidate is usually the real thing.Candidates are deliberately not deduplicated by format here — when the PDF of a work turns out to be an excerpt, its EPUB often is not.
- Parameters:
title (
str) – The title actually wanted.authors (
str|None) – The author(s) wanted, if known — a strong disambiguating signal.download_dir (
str) – Where to save the file.max_candidates (
int) – How many ranked candidates to try before giving up.page – Optional Playwright page to reuse.
timeout (
int) – Per-download timeout in ms.delay (
float) – Seconds between page loads (rate limiting).headless (
bool) – Headless browser mode (ignored whenpageis given).try_mirrors (
bool) – Try external mirror URLs when the primary path fails.verbose (
bool) – Print progress and the reason each candidate was rejected.validate (
bool) – Check that what arrived is really the requested file.policy (
Optional[ValidationPolicy]) – Validation policy; defaults tociteget.validate.BOOK_POLICY, which also rejects excerpts.**rank_kwargs – Forwarded to
citeget.rank.score_result()(format_preference,language,weights,size_bounds,decoy_pattern).
- Return type:
- Returns:
Path to the downloaded file, or None if no candidate produced one.
- citeget.core.download_one(result, *, download_dir='.', page=None, timeout=60000, delay=1.0, try_mirrors=True, verbose=False, validate=True, policy=None)[source]¶
Download a single result. Returns the saved file path, or None on failure.
Tries the primary libgen download path (ads.php -> get.php) first. If that fails and
try_mirrorsis True, attempts external mirrors (Anna’s Archive, library.lol, etc.).Every path that can return a file routes through
citeget.validatefirst, so an HTML page or a truncated transfer is reported as a failure rather than saved under the book’s name. An existing file is re-validated before being accepted as a cached success, so a stub left by an earlier failure cannot make that failure permanent.If
pageis provided (a Playwright Page object), reuse it. Otherwise, creates a new browser session (slower but standalone).- Parameters:
result (
dict) – A result dict fromsearch().download_dir (
str) – Where to save the file.page – Optional Playwright page to reuse.
timeout (
int) – Download timeout in ms.delay (
float) – Seconds to wait between page loads (rate limiting).try_mirrors (
bool) – Try external mirror URLs on primary failure.verbose (
bool) – Print diagnostic info on failures.validate (
bool) – Check that what arrived is really the requested file.policy (
Optional[ValidationPolicy]) – Validation policy; defaults tociteget.validate.DEFAULT_POLICY. Passciteget.validate.BOOK_POLICYwhen the download should be a complete book, to also reject excerpts and front-matter samples.
- Return type:
- Returns:
Path to the downloaded file, or None if download failed.
- citeget.core.download_results(results, *, download_dir='.', max_downloads=0, delay=2.0, headless=True, timeout=60000, verbose=True, distinct=True, validate=True, policy=None)[source]¶
Download multiple results. Returns list of (result, filepath) tuples.
- Parameters:
results (
list) – List of result dicts fromsearch().download_dir (
str) – Where to save files.max_downloads (
int) – Max number to download (0 = all).delay (
float) – Seconds between downloads (rate limiting).headless (
bool) – Run browser in headless mode.timeout (
int) – Per-download timeout in ms.verbose (
bool) – Print progress.distinct (
bool) – Collapse rows that are the same work in different file formats, somax_downloads=5means five different works rather than five copies of one. Set False for the raw result order.validate (
bool) – Check that each download really is the requested file.policy (
Optional[ValidationPolicy]) – Validation policy (seeciteget.validate).
- Return type:
- Returns:
List of (result_dict, filepath_or_None) tuples.
- citeget.core.get_book(title, *, authors=None, download_dir='.', query=None, topic='books', max_candidates=5, results_per_page=50, search_attempts=2, headless=True, timeout=45000, delay=1.0, verbose=True, validate=True, policy=None, base_url=None, mirrors=None, **rank_kwargs)[source]¶
Acquire one copy of a specific book. The “get me this book” entry point.
Searches, ranks the results against title and authors, and downloads the best candidate that validates as a complete book — as opposed to
search_and_download(), which takes libgen’s own ordering.Simple case:
from citeget import get_book path = get_book("Crossing the Chasm", authors="Geoffrey A. Moore", download_dir="~/books")- Parameters:
title (
str) – The book’s title.authors (
str|None) – The author(s), if known. Strongly improves matching, since libgen titles alone are noisy.download_dir (
str) – Where to save the file.query (
str|None) – Override the search string sent to libgen. Defaults to the title plus the first author’s surname.topic (
str) – Libgen topic to search (“books”, “fiction”, “articles”, …).max_candidates (
int) – How many ranked candidates to try before giving up.results_per_page (
int) – How many results to fetch to rank.search_attempts (
int) – How many times to re-run a search that came back empty before accepting “not found”. Libgen returns a spurious empty result set often enough that a single empty answer is weak evidence.headless (
bool) – Headless browser mode.timeout (
int) – Page load timeout in ms.delay (
float) – Seconds between page loads (rate limiting).verbose (
bool) – Print progress.validate (
bool) – Check that what arrived is really the requested book.policy (
Optional[ValidationPolicy]) – Validation policy; defaults tociteget.validate.BOOK_POLICY.mirrors (
tuple|list|None) – Explicit ordered list of mirror base URLs to try.**rank_kwargs – Forwarded to
citeget.rank.score_result().
- Return type:
- Returns:
Path to the downloaded file, or None if nothing usable was found.
- Raises:
MirrorUnreachableError – if no candidate mirror could be reached.
- citeget.core.search(query, *, topic='books', topics=None, results_per_page=100, headless=True, timeout=45000, table_timeout=20000, attempts_per_mirror=2, retry_backoff=2.0, no_table_confirmations=2, base_url=None, mirrors=None)[source]¶
Search a libgen mirror and return a list of result dicts.
Tries each candidate mirror in order and uses the first one that is reachable, retrying a mirror that merely timed out before moving on. If every mirror fails, raises
MirrorUnreachableErrorwith a message that says which failure mode it was, rather than a raw browser stack trace. A mirror that loads but shows no results table is not on its own taken as “no results”: libgen serves the same page shape for a query with no matches and for a page whose table has not rendered, so a second mirror has to agree before[]is returned.- Parameters:
query (
str) – Search terms.topic (
str) – What to search for — “books”, “articles”, “fiction”, “comics”, “magazines”, or “standards”. Used whentopicsis None.topics (
tuple|list|None) – Multiple topics to search simultaneously, e.g.("books", "fiction", "articles"). Overridestopic.results_per_page (
int) – How many results per page (25, 50, or 100).headless (
bool) – Run browser in headless mode (default True).timeout (
int) – Page navigation timeout in ms.table_timeout (
int) – How long to wait, after the DOM is ready, for the results table to be rendered. Also bounds how long an empty result set takes to report.attempts_per_mirror (
int) – How many times to try a mirror whose page timed out before failing over to the next one. Hard connection failures are never retried.retry_backoff (
float) – Seconds to wait before a retry, multiplied by the attempt number.no_table_confirmations (
int) – How many mirrors must load without a results table before the query is reported as having no results.base_url (
str|None) – Force a single mirror (e.g.https://libgen.vg). Overrides env vars and the default list.mirrors (
tuple|list|None) – Explicit ordered list of mirror base URLs to try. Overridesbase_url, env vars, and the default list.
- Returns:
title, authors, publisher, year, language, pages, size, extension, doi, series, md5, file_id, libgen_href, mirrors, and
base_url(the mirror the result came from, so the download step can resolve the same mirror’s relative links).- Return type:
- Raises:
MirrorUnreachableError – if no candidate mirror could be reached.
- citeget.core.search_and_download(query, *, topic='books', download_dir='.', max_downloads=5, results_per_page=100, delay=2.0, headless=True, timeout=30000, verbose=True, distinct=True, validate=True, policy=None, base_url=None, mirrors=None)[source]¶
Search libgen and download matching results in one shot.
This is the main convenience function. It runs the search, then downloads up to
max_downloadsresults intodownload_dir.- Parameters:
query (
str) – Search terms.topic (
str) – “books”, “articles”, “fiction”, etc.download_dir (
str) – Where to save files.max_downloads (
int) – Max number to download (default 5, 0 = all).results_per_page (
int) – Results per search page.delay (
float) – Seconds between downloads.headless (
bool) – Headless browser mode.timeout (
int) – Timeout in ms for page loads.verbose (
bool) – Print progress.distinct (
bool) – Count distinct works rather than file formats towardsmax_downloads. Libgen lists one edition once per format, so without thismax_downloads=5returns five copies of one book.validate (
bool) – Check that each download really is the requested file.policy (
Optional[ValidationPolicy]) – Validation policy (seeciteget.validate).base_url (
str|None) – Force a single mirror. Overrides env vars and the default list.mirrors (
tuple|list|None) – Explicit ordered list of mirror base URLs to try.
- Return type:
To acquire one copy of a specific book rather than the top N rows, use
get_book(), which ranks results against the title and author you asked for.- Return type:
- Returns:
List of (result_dict, filepath_or_None) tuples.
- Raises:
MirrorUnreachableError – if no candidate mirror could be reached.