API Reference¶
This page is generated directly from the source docstrings, so it always matches the installed version. The guide pages explain when and why to use each object; this page is the authoritative what.
Public imports
User-facing code should prefer from onecrawler import .... Internal runtime helpers should be imported from their concrete modules only when you are extending OneCrawler itself.
Engines¶
Crawler ¶
Bases: BaseEngine
Crawls a site and returns all content with no filtering.
Supports optional proxy configuration via Settings.proxy for anonymised crawling. Acts as the primary crawler entry-point.
Attributes:
| Name | Type | Description |
|---|---|---|
settings | Settings | Configuration for the crawl. |
strategy | Optional[Any] | The content-extraction strategy in use ( |
browser | Optional[GoogleChrome] | The shared browser instance; set on |
Example
from onecrawler import Crawler, Settings
async with Crawler(Settings()) as crawler:
results = await crawler.run("https://example.com")
print(results)
Streaming:
Initializes the crawler with the given settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
settings | Settings | Configuration for the crawl. | required |
Source code in onecrawler/crawler/crawl.py
start async ¶
Starts the browser and initializes the configured scraping strategy.
Raises:
| Type | Description |
|---|---|
ValueError | If |
Source code in onecrawler/crawler/crawl.py
close async ¶
run async ¶
Crawls url and collects all extracted content.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url | str | The starting URL; the crawl stays within its origin. | required |
filters | Optional[Callable[[dict], bool]] | Predicate applied to each extracted content dict post-extraction, pre-collection; items failing it are dropped. See | None |
Returns:
| Type | Description |
|---|---|
list[dict] | list[dict]: Extracted content dicts, each including its source |
list[dict] |
|
Source code in onecrawler/crawler/crawl.py
stream async ¶
Crawls url, yielding extracted content dicts as they arrive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url | str | The starting URL; the crawl stays within its origin. | required |
filters | Optional[Callable[[dict], bool]] | Predicate applied to each extracted content dict post-extraction, pre-yield; items failing it are dropped. See | None |
Yields:
| Name | Type | Description |
|---|---|---|
dict | AsyncGenerator[dict, None] | An extracted content dict, including its source |
Source code in onecrawler/crawler/crawl.py
LinkExtractor ¶
LinkExtractor(settings: Settings)
Bases: BaseEngine
Engine for extracting links from websites using various strategies.
Supports both 'shallow' (single page) and 'deep' (BFS-based) extraction.
Attributes:
| Name | Type | Description |
|---|---|---|
settings | Settings | Configuration settings for extraction. |
Example
from onecrawler import Settings, LinkExtractor
settings = Settings(link_extraction_strategy="shallow")
async with LinkExtractor(settings) as engine:
links = await engine.run("https://example.com")
print(links)
Streaming:
Source code in onecrawler/crawler/engine.py
start async ¶
Starts the engine and initializes the browser.
Source code in onecrawler/crawler/engine.py
close async ¶
run async ¶
Runs the link extraction for the given URL.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url | str | The starting URL. | required |
Returns:
| Type | Description |
|---|---|
List[str] | List[str]: A list of absolute URLs discovered. |
Raises:
| Type | Description |
|---|---|
ValueError | If an unknown strategy is configured. |
Source code in onecrawler/crawler/engine.py
stream async ¶
Streams discovered links incrementally (deep strategy only).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url | str | The starting URL. | required |
Yields:
| Name | Type | Description |
|---|---|---|
str | AsyncGenerator[str, None] | Discovered absolute URL. |
Raises:
| Type | Description |
|---|---|
AssertionError | If strategy is 'shallow'. |
ValueError | If an unknown strategy is configured. |
Source code in onecrawler/crawler/engine.py
Scraper ¶
Scraper(settings: Settings)
Bases: BaseEngine
Engine for scraping and extracting data from URLs.
Supports: - Heuristic extraction - GenAI extraction - Concurrent scraping - Streaming results
Attributes:
| Name | Type | Description |
|---|---|---|
settings | Settings | Configuration settings for scraping. |
strategy | Optional[Any] | The content-extraction strategy in use ( |
browser | Optional[GoogleChrome] | The shared browser instance; set on |
Example
from onecrawler import Settings, Scraper
async with Scraper(settings) as engine:
result = await engine.run("https://example.com")
print(result)
Streaming:
Source code in onecrawler/crawler/engine.py
start async ¶
Starts the scraper engine.
Source code in onecrawler/crawler/engine.py
close async ¶
stream async ¶
Streams extracted results as they complete, in completion order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link | Union[str, List[str]] | One URL or a list of URLs to scrape. | required |
Yields:
| Name | Type | Description |
|---|---|---|
dict | AsyncGenerator[Any, None] |
|
AsyncGenerator[Any, None] | depends on | |
AsyncGenerator[Any, None] | (a dict, plain text, or a GenAI | |
AsyncGenerator[Any, None] | URLs that fail extraction after retries are silently skipped. |
Source code in onecrawler/crawler/engine.py
run async ¶
Runs the scraper and collects all results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
link | Union[str, List[str]] | One URL or a list of URLs to scrape. | required |
Returns:
| Type | Description |
|---|---|
Union[dict, List[dict], None] | Union[dict, List[dict], None]: A list of ``{"url": str, "result": |
Union[dict, List[dict], None] | Any} |
Union[dict, List[dict], None] | input if some URLs failed extraction); a single such dict (or |
Union[dict, List[dict], None] |
|
Source code in onecrawler/crawler/engine.py
Sitemap discovery¶
SiteMap ¶
SiteMap(settings: Settings)
The high-level orchestrator for site discovery.
Combines robots.txt parsing, common path probing, XML sitemap traversal, and HTML crawling to find all relevant URLs on a site.
Attributes:
| Name | Type | Description |
|---|---|---|
settings | Settings | Configuration settings. |
Initializes SiteMap.
Source code in onecrawler/crawler/map/sitemap.py
run async ¶
Runs the universal sitemap discovery process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url | str | The starting URL. | required |
Returns:
| Type | Description |
|---|---|
List[str] | List[str]: A list of discovered absolute internal URLs. |
Source code in onecrawler/crawler/map/sitemap.py
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 | |
Settings¶
Settings dataclass ¶
Settings(
sitemap: SitemapSettings = SitemapSettings(),
link_extraction_strategy: Literal[
"shallow", "deep"
] = "deep",
link_extraction_limit: int = 50,
include_link_patterns: Optional[List[str]] = None,
exclude_link_patterns: Optional[List[str]] = None,
scraping_strategy: Literal[
"heuristic", "genai", "markdownify"
] = "heuristic",
scraping_output_format: Literal[
"markdown", "json", "xml", "xmltei"
] = "json",
exclude_selectors: Optional[List[str]] = None,
genai: Optional[LLMSettings] = None,
concurrency: int = 10,
max_retries: int = 2,
request_timeout: int = 10,
retry_delay: int = 1,
proxies: Optional[List[ProxySettings]] = None,
proxy_rotation_method: Literal[
"round_robin", "random"
] = "round_robin",
browser_settings: BrowserSettings = BrowserSettings(),
show_progress: bool = True,
logging_level: Optional[
Literal["DEBUG", "INFO", "WARNING", "ERROR"]
] = None,
human_behavior_settings: Optional[
HumanBehaviorSettings
] = None,
)
Central configuration class for OneCrawler.
This class coordinates settings for sitemap crawling, link extraction, content scraping, browser automation, and proxy management.
Attributes:
| Name | Type | Description |
|---|---|---|
sitemap | SitemapSettings | Configuration for sitemap discovery. |
link_extraction_strategy | Literal['shallow', 'deep'] | Strategy for finding links on pages. |
link_extraction_limit | int | Maximum number of valid links to extract per run. |
include_link_patterns | Optional[List[str]] | Wildcard patterns for links to include. |
exclude_link_patterns | Optional[List[str]] | Wildcard patterns for links to exclude. |
scraping_strategy | Literal['heuristic', 'genai', 'markdownify'] | Strategy for content extraction. |
scraping_output_format | str | The desired format for scraped data. |
exclude_selectors | Optional[List[str]] | CSS selectors (e.g. |
genai | Optional[LLMSettings] | Configuration for AI-powered scraping. |
concurrency | int | Number of concurrent workers/pages. |
max_retries | int | Number of retries for failed requests/actions. |
request_timeout | int | Timeout for requests in seconds. |
retry_delay | int | Delay between retries in seconds. |
proxies | Optional[List[ProxySettings]] | Proxies to use. A single proxy is just a one-element list; multiple proxies rotate per |
proxy_rotation_method | Literal['round_robin', 'random'] | Strategy for proxy rotation. |
browser_settings | BrowserSettings | Configuration for the browser instance. |
show_progress | bool | Whether to display tqdm progress bars. |
logging_level | Optional[str] | Log level (e.g., "INFO"). |
human_behavior_settings | Optional[HumanBehaviorSettings] | Human-browsing simulation config. |
create_proxy_pool ¶
Creates a ProxyPool based on the provided proxy settings.
Returns:
| Name | Type | Description |
|---|---|---|
ProxyPool | ProxyPool | An initialized proxy pool. |
Source code in onecrawler/settings/crawler.py
BrowserSettings dataclass ¶
BrowserSettings(
proxy: Optional[ProxySettings] = None,
viewport: Optional[Dict[str, int]] = (
lambda: {"width": 1366, "height": 768}
)(),
screen: Optional[Dict[str, int]] = None,
no_viewport: Optional[bool] = None,
user_agent: Optional[
str
] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
locale: str = "en-US",
timezone_id: str = "Asia/Dhaka",
geolocation: Optional[Dict[str, float]] = None,
permissions: Optional[List[str]] = None,
extra_http_headers: Optional[Dict[str, str]] = None,
java_script_enabled: bool = True,
bypass_csp: bool = True,
ignore_https_errors: bool = True,
offline: bool = False,
storage_state: Optional[str] = None,
base_url: Optional[str] = None,
headless: bool = True,
slow_mo: int = 0,
args: List[str] = (
lambda: [
"--no-sandbox",
"--disable-blink-features=AutomationControlled",
"--disable-dev-shm-usage",
]
)(),
executable_path: Optional[str] = None,
channel: Optional[str] = None,
env: Optional[Dict[str, str]] = None,
wait_until: str = "domcontentloaded",
timeout: int = 30000,
settle_delay: int = 1500,
)
Settings for a browser instance.
Attributes:
| Name | Type | Description |
|---|---|---|
proxy | Optional[ProxySettings] | Proxy configuration. |
viewport | Optional[Dict[str, int]] | The default viewport size for each page. |
screen | Optional[Dict[str, int]] | The screen size. |
no_viewport | Optional[bool] | Whether to disable the default viewport. |
user_agent | Optional[str] | The user agent string to use. |
locale | str | The locale (e.g., "en-US"). |
timezone_id | str | The timezone ID (e.g., "Asia/Dhaka"). |
geolocation | Optional[Dict[str, float]] | The geolocation coordinates. |
permissions | Optional[List[str]] | List of permissions to grant (e.g., ["geolocation"]). |
extra_http_headers | Optional[Dict[str, str]] | Additional HTTP headers to send with every request. |
java_script_enabled | bool | Whether to enable JavaScript. |
bypass_csp | bool | Whether to bypass Content Security Policy. |
ignore_https_errors | bool | Whether to ignore HTTPS errors. |
offline | bool | Whether to simulate being offline. |
storage_state | Optional[str] | Path to a file with the storage state (cookies, localStorage). |
base_url | Optional[str] | Base URL for navigation. |
headless | bool | Whether to run the browser in headless mode. |
slow_mo | int | Slows down Playwright operations by the specified amount of milliseconds. |
args | List[str] | Additional arguments to pass to the browser instance. |
executable_path | Optional[str] | Path to a browser executable to use instead of the bundled one. |
channel | Optional[str] | Browser distribution channel (e.g., "chrome", "msedge"). |
env | Optional[Dict[str, str]] | Environment variables that will be visible to the browser. |
wait_until | str | When to consider navigation finished (e.g., "domcontentloaded"). |
timeout | int | Timeout for browser operations in milliseconds. |
settle_delay | int | Extra time in milliseconds to wait after navigation before capturing the page, letting client-side/JS-rendered content (e.g. prices or listings on SPA sites) hydrate. Defaults to 1500ms so dynamic sites work out of the box; set |
LLMSettings dataclass ¶
LLMSettings(
provider: Literal["google", "openai", "ollama"],
model_name: str,
api_key: Optional[str] = None,
output_schema: Optional[Type[BaseModel]] = None,
base_url: Optional[str] = None,
provider_kwargs: Optional[dict[str, Any]] = None,
timeout: Optional[float] = None,
think: bool = False,
)
Configuration for Generative AI providers and models.
Attributes:
| Name | Type | Description |
|---|---|---|
provider | Literal['google', 'openai', 'ollama'] | The AI service provider. Use "openai" with a custom |
model_name | str | The name of the specific model to use (e.g., "gemini-1.5-flash"). |
api_key | Optional[str] | API key for the provider. Required for the real OpenAI/Gemini endpoints; optional when |
output_schema | Optional[Type[BaseModel]] | Pydantic model for structured output. |
base_url | Optional[str] | Base URL for Ollama, an OpenAI-compatible server, or any custom endpoint. |
provider_kwargs | Optional[dict[str, Any]] | Provider-specific keyword arguments. |
timeout | Optional[float] | Per-request timeout in seconds for the provider's API call. |
think | bool | Ollama only. Whether to let a thinking model (qwen3, deepseek-r1, ...) emit its reasoning trace. Defaults to |
HumanBehaviorSettings dataclass ¶
HumanBehaviorSettings(
min_delay: float = 0.3,
max_delay: float = 1.2,
max_scrolls: int = 50,
scroll_pause: float = 1.0,
min_mouse_moves: int = 5,
max_mouse_moves: int = 15,
mouse_width: int = 1366,
mouse_height: int = 768,
min_mouse_sleep: float = 0.1,
max_mouse_sleep: float = 0.3,
min_mouse_steps: int = 5,
max_mouse_steps: int = 20,
)
Configuration for simulating human interaction with a web page.
Attributes:
| Name | Type | Description |
|---|---|---|
min_delay | float | Minimum delay in seconds between major actions. |
max_delay | float | Maximum delay in seconds between major actions. |
max_scrolls | int | Maximum number of scroll steps per page. |
scroll_pause | float | Pause in seconds between scroll steps. |
min_mouse_moves | int | Minimum number of mouse movements per action. |
max_mouse_moves | int | Maximum number of mouse movements per action. |
mouse_width | int | Width of the area for mouse movement simulation. |
mouse_height | int | Height of the area for mouse movement simulation. |
min_mouse_sleep | float | Minimum sleep time between mouse steps. |
max_mouse_sleep | float | Maximum sleep time between mouse steps. |
min_mouse_steps | int | Minimum steps per mouse movement. |
max_mouse_steps | int | Maximum steps per mouse movement. |
ProxySettings dataclass ¶
Configuration for a single proxy server.
Attributes:
| Name | Type | Description |
|---|---|---|
server | str | The proxy server URL (e.g., "http://myproxy.com:8080"). |
username | Optional[str] | Username for proxy authentication. |
password | Optional[str] | Password for proxy authentication. |
as_playwright ¶
Converts proxy settings to a dictionary format expected by Playwright.
Returns:
| Type | Description |
|---|---|
Dict[str, str] | Dict[str, str]: A dictionary with 'server', 'username', and 'password'. |
Source code in onecrawler/settings/proxy.py
as_requests_proxies ¶
Converts proxy settings to a dictionary format expected by the requests library.
Returns:
| Type | Description |
|---|---|
Dict[str, str] | Dict[str, str]: A dictionary with 'http' and 'https' keys mapping to the proxy URL. |
Source code in onecrawler/settings/proxy.py
Filters¶
Composable predicates over extracted content dicts. Build a filter, then pass it to Crawler.run() / Crawler.stream() as the filters argument.
by_date ¶
by_date(
start: Optional[str] = None,
end: Optional[str] = None,
*,
fields: Sequence[str] = CONTENT_DATE_FIELDS
) -> Callable[[dict], bool]
Filter items by YYYY-MM-DD date range.
Reads the first present field in fields (default: publication date, then filedate). Note filedate is the extraction/download date, so date is checked first to filter by publication rather than crawl time. Items with no parseable date are excluded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start | Optional[str] | Inclusive lower bound, as | None |
end | Optional[str] | Inclusive upper bound, as | None |
fields | Sequence[str] | Content-dict keys to check, in priority order. | CONTENT_DATE_FIELDS |
Returns:
| Type | Description |
|---|---|
Callable[[dict], bool] | Callable[[dict], bool]: A predicate accepting items whose resolved |
Callable[[dict], bool] | date falls within |
Source code in onecrawler/filters/date.py
by_keywords ¶
Keep items whose content contains ANY keyword (case-insensitive).
Reads the item's field (default text); items missing that field are dropped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keywords | Iterable[str] | Keywords to match; matching is case-insensitive. | required |
field | str | Content-dict key to search. | 'text' |
Returns:
| Type | Description |
|---|---|
Callable[[dict], bool] | Callable[[dict], bool]: A predicate accepting items containing at |
Callable[[dict], bool] | least one keyword. |
Source code in onecrawler/filters/keywords.py
by_files ¶
Filter by logical file types: pdf, docx, image, etc.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
types | Iterable[str] | Logical type names from | required |
field | str | Content-dict key holding the URL to check. | CONTENT_URL_FIELD |
Returns:
| Type | Description |
|---|---|
Callable[[dict], bool] | Callable[[dict], bool]: A predicate accepting items whose URL matches |
Callable[[dict], bool] | one of the resolved extensions. |
Source code in onecrawler/filters/files.py
by_extension ¶
by_extension(
extensions: Iterable[str],
*,
field: str = CONTENT_URL_FIELD
) -> Callable[[dict], bool]
Filter by the file extension of the item's URL (field).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
extensions | Iterable[str] | Extensions to allow, with or without a leading dot (e.g. | required |
field | str | Content-dict key holding the URL to check. | CONTENT_URL_FIELD |
Returns:
| Type | Description |
|---|---|
Callable[[dict], bool] | Callable[[dict], bool]: A predicate accepting items whose URL ends |
Callable[[dict], bool] | with one of |
Source code in onecrawler/filters/files.py
by_cosine_similarity ¶
by_cosine_similarity(
query: str,
threshold: float = 0.25,
*,
fields: Sequence[str] = CONTENT_TEXT_FIELDS
) -> Callable[[dict], bool]
Compare query text vs document text using cosine similarity.
Scores against the first present field in fields (default: the body text, then content, then title) so the full document is compared rather than a short title when both exist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query | str | Text to compare each item's content against. | required |
threshold | float | Minimum cosine similarity score (0-1) required to pass. | 0.25 |
fields | Sequence[str] | Content-dict keys to check, in priority order. | CONTENT_TEXT_FIELDS |
Returns:
| Type | Description |
|---|---|
Callable[[dict], bool] | Callable[[dict], bool]: A predicate accepting items scoring at least |
Callable[[dict], bool] |
|
Source code in onecrawler/filters/similarity.py
Composition¶
Combine filters with boolean logic.
AND ¶
Combine filters so an item passes only if ALL of them accept it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*filters | Callable[[dict], bool] | Filter predicates to combine. | () |
Returns:
| Name | Type | Description |
|---|---|---|
FilterChain | A predicate accepting an item only when every filter does. |
Source code in onecrawler/filters/chain.py
OR ¶
Combine filters so an item passes if ANY of them accepts it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*filters | Callable[[dict], bool] | Filter predicates to combine. | () |
Returns:
| Name | Type | Description |
|---|---|---|
FilterChain | A predicate accepting an item when at least one filter does. |
Source code in onecrawler/filters/chain.py
NOT ¶
Negate a filter predicate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
f | Callable[[dict], bool] | The filter predicate to negate. | required |
Returns:
| Type | Description |
|---|---|
| Callable[[dict], bool]: A predicate accepting an item only when | |
| rejects it. |
Warning
Field-dependent filters (e.g. by_keywords, by_date) return False both when an item fails to match and when the item is missing the field entirely (fail-closed). NOT can't tell those apart, so NOT(by_keywords(...)) will include items that have no text field at all, not just items that failed to match. Add an explicit field-presence check first if that distinction matters.
Source code in onecrawler/filters/chain.py
Output writers¶
Helpers for persisting results, exported from onecrawler.utils.writter.
dump_json ¶
dump_json(
data: Any,
filename: str | Path,
indent: int = 2,
ensure_ascii: bool = False,
encoding: str = "utf-8",
) -> None
Write data to filename as a single JSON document.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | Any | The object to serialize. Dataclasses/Pydantic models, | required |
filename | str | Path | Destination file path; overwritten if it exists. | required |
indent | int | Number of spaces used to pretty-print the output. | 2 |
ensure_ascii | bool | If True, escape all non-ASCII characters. | False |
encoding | str | Text encoding used to open | 'utf-8' |
Source code in onecrawler/utils/writter.py
dump_jsonl ¶
dump_jsonl(
data: Any,
filename: str | Path,
ensure_ascii: bool = False,
encoding: str = "utf-8",
) -> None
Write data to filename as JSON Lines (one JSON object per line).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | Any | A list of objects to serialize, one per line. A non-list value is wrapped in a single-item list. | required |
filename | str | Path | Destination file path; overwritten if it exists. | required |
ensure_ascii | bool | If True, escape all non-ASCII characters. | False |
encoding | str | Text encoding used to open | 'utf-8' |
Source code in onecrawler/utils/writter.py
dump_txt ¶
Write text to filename as plain text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text | str | The text content to write. | required |
filename | str | Path | Destination file path; overwritten if it exists. | required |
encoding | str | Text encoding used to open | 'utf-8' |
Source code in onecrawler/utils/writter.py
dump_csv ¶
Write rows to filename as CSV.
The column order follows each key's first appearance across rows, so rows with different key sets still produce one consistent header; missing values in a given row are written as empty cells. Non-dict rows (e.g. dataclasses/Pydantic models) are serialized the same way as dump_json.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rows | list[dict] | The rows to write. A no-op if empty. | required |
filename | str | Path | Destination file path; overwritten if it exists. | required |
encoding | str | Text encoding used to open | 'utf-8' |