Commit Graph

534 Commits

Author SHA1 Message Date
Karim shoair 8e4e59e13e Merge branch 'dev' into fix/page-content-infinite-loop 2026-03-17 22:08:47 +02:00
Karim shoair 4c07b294ae Merge branch 'dev' into fix/preserve-http-method-on-retry 2026-03-17 22:04:57 +02:00
Karim shoair 27f306259e Merge branch 'dev' into fix/page-content-infinite-loop 2026-03-17 21:55:26 +02:00
Karim shoair 136c389787 fix(Texthandler): Replace get_all with getall to match the Selector class 2026-03-17 21:53:17 +02:00
karesansui 5bf921b308 fix: preserve HTTP method across retries in spider session
SessionManager.fetch() pops `method` from `_session_kwargs`,
which mutates the original request dict. When the engine retries
a blocked request via request.copy(), the copy no longer has
`method`, so it defaults to GET.

Steps to reproduce:
1. Yield Request(url, method="POST", data=...)
2. Target returns a response that triggers is_blocked()
3. Engine retries via request.copy() → second fetch uses GET

Fix: copy the kwargs dict before popping, so the original
request stays intact.
2026-03-17 00:53:52 +09:00
haosenwang1018 d3c251c1ab fix: add max retry limit to _get_page_content to prevent infinite loop
Both _get_page_content and _get_async_page_content use a while-True
loop that retries page.content() on PlaywrightError with no upper
bound. If the page is in a permanently broken state (crashed tab,
closed context), this loops forever and hangs the process.

Replace with a bounded for-loop (default 10 retries = 5s), returning
an empty string if all attempts fail. This preserves the existing
retry behavior for the transient Windows issue (playwright#16108)
while preventing hangs.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-15 17:53:23 +08:00
haosenwang1018 a31763afde fix: replace bare raise with return False in _restore_from_checkpoint
When _checkpoint_system_enabled is False, the method uses a bare
`raise` with no active exception, which causes RuntimeError at
runtime. The method's docstring says it returns False when restoration
is not possible, so return False is the correct behavior.

The caller in crawl() currently guards with `if
self._checkpoint_system_enabled`, but the method's own contract
should be self-consistent.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-15 17:52:57 +08:00
Karim shoair f80743a97b style: remove unused import 2026-03-09 00:35:06 +02:00
Karim shoair a929de6ca4 fix: update code and docstrings to remove the old google referer logic 2026-03-09 00:25:19 +02:00
Karim shoair 27409927a3 build: pump up deps and browsers versions 2026-03-08 23:57:10 +02:00
Karim shoair b0c8448f81 Merge branch 'dev' into fix/google-referrer-spoof 2026-03-08 19:01:20 +02:00
Andrew Barnes 68b9e128bc fix: return bare Google URL in referer instead of search query
Real browsers send `https://www.google.com/` as the Referer header
when clicking search results, not the full search URL with query
parameters. The previous format was a fingerprinting signal that
the referer was spoofed.

Closes #172
2026-03-08 11:32:04 -04:00
Matt Hillebrand 5806b8e014 - Add pre-compiled XPath text selector
- Avoid recursion
2026-03-07 17:11:39 -08:00
Matt Hillebrand 5457a697fa fix: Selector.get_all_text() doesn't get all text #167
- Updated text extraction using recursion
- Added new unit test
2026-03-07 17:11:39 -08:00
Karim shoair c8e1d8d75d fix(type hints): use correct import for Python < 3.12 (Fixes #163 ) 2026-03-05 16:45:10 +02:00
Karim shoair 37f5c48a5f build: pump up the version
Co-Authored-By: Christian Rost <chr@baltic-online.de>
2026-03-03 23:09:36 +02:00
Karim shoair 1839506622 fix(browsers): make flag concatenation type-safe
Better implementation of #157 that's accepted by pyright/mypy.
Thanks to @rostchri .

Co-Authored-By: Christian Rost <chr@baltic-online.de>
2026-03-03 23:08:15 +02:00
Karim shoair e34651d887 fix(stealth): improve stealth mode by removing unnecessary scripts
It doesn't add anything to the table as before (it might turn out I was wrong and add them again lol)
2026-02-27 03:50:14 +02:00
Karim shoair b50e8f050f fix(mcp): make mcp use less tokens by striping useless tags 2026-02-27 03:39:48 +02:00
Karim shoair d750fec468 fix(solver): Solve CF faster and handle websites that show captcha twice 2026-02-27 02:32:21 +02:00
Karim shoair a8359a4878 build: pump version up and the deps 2026-02-27 00:32:25 +02:00
Karim shoair 921314c314 fix: complete MCP schema validation for remaining bare array types
- Fix params (Dict|List|Tuple → Dict), urls (Tuple[str,...] → List[str]),
- Renamed _NormalizeCredentials/_ContentTranslator to snake_case.
- Also, raise a ValueError on invalid credentials instead of returning None silently.
2026-02-27 00:28:44 +02:00
Karim shoair 6c12c196ac Merge branch 'dev' into fix/mcp-schema-auth-cookies 2026-02-26 23:54:18 +02:00
Robin Ede b77a1b9419 fix: make MCP get schemas validator-safe
Use JSON-object input types for cookies and basic-auth fields in get and bulk_get so strict MCP schema validators can register tools reliably.

Normalize auth dictionaries to the tuple format expected by fetchers to preserve runtime behavior.
2026-02-23 19:49:39 -06:00
RinZ27 aa90dda439 fix: improve regex precision for Cloudflare challenge detection 2026-02-18 14:02:31 +07:00
Karim shoair b19fa5e694 fix(checkpoint): correct error message 2026-02-15 04:36:43 +02:00
Karim shoair 02b11c535e fix(spiders): corrections and removal of dead code 2026-02-15 04:25:32 +02:00
Karim shoair 93bcb1681b style: docstrings corrections for accuracy 2026-02-15 03:57:14 +02:00
Karim shoair ba4d33337f fix: make browser fetchers type hints always present 2026-02-15 01:03:15 +02:00
Karim shoair 0ab54852c4 fix: use more accurate naming for proxy rotation strategy
It can be considered the simplest form of round robin since we don't have weights or anything (as was originally planned), but let's change it to avoid confusion or useless debates. Here goes nothing
2026-02-14 23:19:54 +02:00
Karim shoair e785cf26ce fix(parser)!: Optimize parser for repeated operations 2026-02-14 03:34:13 +02:00
Karim shoair 2eea66dad1 style(spiders): Lower the default number of concurrent requests 2026-02-13 17:32:17 +02:00
Karim shoair a62330d2f1 fix: add typed overloads to Selectors.get() for proper default type inference
Type checkers now correctly infer the return type based on the default value:
- .get() → TextHandler | None
- .get("") → TextHandler | str
- .get(0) → TextHandler | int
2026-02-13 17:30:55 +02:00
Karim shoair 0489923b06 build: pump up the version status 2026-02-10 21:53:00 +02:00
Karim shoair 4e3829fced style: expose ProxyRotator class to the public API 2026-02-10 21:20:07 +02:00
Karim shoair 16852cb1ac style: Use shorter and more accurate naming for constants 2026-02-07 16:37:47 +02:00
Karim shoair e777342741 build: pump up version and deps 2026-02-07 16:30:32 +02:00
Karim shoair 5ec929435b style: Fix all mypy errors and add type hints to untyped function bodies
**Resolved all 65 mypy errors across 14 files and added type annotations to all previously untyped function bodies. Final result: 0 errors with --check-untyped-defs enabled, all 454 tests pass.**

`scrapling/core/_types.py`

  - Removed broken Self = object fallback — now requires typing_extensions for Python < 3.11

`scrapling/core/storage.py`

  - Fixed str/bytes mismatch in _get_hash() — used separate _identifier_bytes variable instead of reassigning from str to bytes

`scrapling/core/custom_types.py`

  - split() return type: Union[List, "TextHandlers"] → list[Any] (avoids LSP violation with parent list[str])
  - format() kwargs: **kwargs: str → **kwargs: object (matches parent str.format signature)
  - AttributesHandler.__init__: Added mapping: Any = None, **kwargs: Any and -> None
  - json_string property: Added -> bytes return type

`scrapling/core/mixins.py`

  - Changed self: "Selector" to self: Any on all mixin methods (mypy can't handle forward-reference self types on non-subclass mixins)
  - Added Dict[str, int] annotation for counter variable
  - Removed unused TYPE_CHECKING / Selector imports

`scrapling/parser.py (~30 errors)`

  - Added body: str | bytes pre-annotation for dual-type if/elif assignment
  - Used Dict[str, Any] kwargs dict for HTMLParser(...) to bypass incomplete lxml stubs missing default_doctype
  - Changed base_url=url or None → base_url=url or "" (avoids str | None vs str | bytes)
  - bool(adaptive) to guarantee bool type for __adaptive_enabled
  - Declared __text: Optional[TextHandler], __tag: Optional[str], __attributes: Optional[AttributesHandler] at top of __init__
  - cast(List, ...) for all XPath() call results (_find_all_elements, _find_all_elements_with_spaces)
  - Added Dict[float, List[Any]] for score_table, Dict[str, Any] for attributes
  - Changed score, checks = 0, 0 → score: float = 0; checks: int = 0 (two locations)
  - Renamed target → target_element in save() to avoid variable redefinition with different types
  - Wrapped node_text.clean() / .lower() in TextHandler(...) to preserve type

`scrapling/engines/_browsers/_page.py`

  - Added PageInfo[SyncPage] | PageInfo[AsyncPage] union type annotation to page_info variable

`scrapling/engines/_browsers/_validators.py`

  - Convert method_kwargs (TypedDict) to plain Dict[str, Any] before dynamic key access

`scrapling/engines/_browsers/_base.py`

  - Added _config declaration to BaseSessionMixin
  - Used cast(StealthConfig, self._config) in __generate_stealth_options to access stealth-only attributes
  - Added Tuple[str, ...] annotation for flags
  - Removed redundant narrower StealthConfig type annotation on self._config in StealthySessionMixin.__validate__
  - Widened SyncSession and AsyncSession fields (playwright, context, browser) to Any to support both playwright and patchright types
  - Added -> None to both start() methods

`scrapling/engines/_browsers/_stealth.py`

  - Added Optional, ProxyType imports
  - Annotated proxy: Optional[ProxyType] in both sync/async fetch loops
  - Annotated outer_box: Any at first declaration, removed duplicate type annotations in subsequent branches
  - Added -> None to sync and async start()
  - Added config: Any parameter type to _initialize_context
  - Removed redundant self.context: AsyncBrowserContext re-annotations in conditional branches

`scrapling/engines/_browsers/_controllers.py`

  - Added Optional, ProxyType imports
  - Annotated proxy: Optional[ProxyType] in both sync/async fetch loops
  - Added -> None to async start()
  - Removed redundant self.context: AsyncBrowserContext re-annotations

`scrapling/spiders/request.py`

  - Added Optional import, typed _fp: Optional[bytes] = None
  - Removed redundant body: bytes re-annotation

`scrapling/spiders/session.py`

  - Used separate client variable instead of reassigning session = session._client (avoids type incompatibility and fixes a bug where session._make_request was called instead of client._make_request)
  - Added -> None to SessionManager.__init__

`scrapling/engines/toolbelt/convertor.py`

  - Added list[Response] annotation for history in both sync/async methods

`scrapling/engines/static.py`

  - FetcherClient.__init__ and AsyncFetcherClient.__init__: Added **kwargs: Any and -> None

`scrapling/core/shell.py`

  - Wrapped re_sub(...) result in TextHandler(...) to maintain correct type
  - Added -> None to CurlParser.__init__
  - Added full type signature to create_wrapper, replaced wrapper.__signature__ = ... with setattr(wrapper, "__signature__", ...) to satisfy mypy
  - Added Callable to imports
2026-02-07 16:30:00 +02:00
Karim shoair 66476d42be feat(browsers): Add option to block requests to specific domains 2026-02-07 01:26:21 +02:00
Karim shoair d00c34ee7f style(parser): Improve the type hint for find_by_text and find_by_regex 2026-02-06 03:19:00 +02:00
Karim shoair 05f62fba81 fix(response): Force the body of the response to always be bytes 2026-02-06 03:14:23 +02:00
Karim shoair aa7a95fb70 feat(parser)!: Make all selection return selector objects by default
- The strings/Texthandlers are only returned by `get`/`getall`/`extract`/`extract_first`. This makes the type checking/autocompletion experience consistent.
- Removed `css_first` and `xpath_first` since it doesn't make sense to leave them now.
- Made the type hints more accurate in multiple places.
2026-02-06 02:43:51 +02:00
Karim shoair f88502718f feat(proxy control): Force a proxy at request level at any given point
And merge request's meta with response's meta
2026-02-02 14:26:52 +02:00
Karim shoair ef8c5bc7d6 feat(spiders/fetchers): Adding proxy rotation logic and change retry logic
- User passes a single proxy to the browser session, and it will keep using the same context. Pass a proxy manager that automatically refreshes the IP with each proxy, and you get speed but sacrifice some stealth.

- User imports the proxy rotator class and passes proxies to it and a rotation strategy (Round robin by default). Then pass the instance to the session class, which will create a context and a tab for each proxy returned by the rotator. This way, you sacrifice speed a bit, but you get maximum stealth since each context is created with the proxy that will be used.

- Normal requests use what you pass without issues, of course.

- All errors are retried now, and proxies are rotated on retries automatically.
2026-02-02 00:16:22 +02:00
Karim shoair 65f1a23358 fix(browsers): Improve stealth and speed by adjusting flags 2026-01-29 00:58:04 +02:00
Karim shoair 0c3d359b46 fix(browsers): disable autoplay for all browsers 2026-01-29 00:57:30 +02:00
Karim shoair 90c52c45c7 feat(parser): replacing tldextract with tld library
This might break the adaptive data users have for websites BUT:
1. tld uses ~3.7x less memory during extraction operations (1.5 MB vs 5.7 MB).
2. tld uses ~56% less memory on import (5.2 MB vs 11.9 MB).
3. Zero dependencies (vs 3 for tldextract).

In return, it's 30ms slower for extracting 5000 URLs, which is negligible. Also, the type hints aren't always accurate, but it's fine; I corrected them.
2026-01-23 00:00:48 +02:00
Karim shoair 5dbbd84b3d fix(requests): return the cached fingerprint on second call 2026-01-20 20:28:13 +02:00
Karim shoair 122923c80e feat(spiders/requests): Use a reliable method for fingerprint generation 2026-01-20 20:21:42 +02:00
Karim shoair 5aa178a76e style: update post requests type hints to be more accurate 2026-01-20 18:27:52 +02:00