* fix: stop response.follow() inheriting the method, params and body
* fix: drop inherited Content-Length in response.follow()
---------
Co-authored-by: Karim shoair <D4Vinci@users.noreply.github.com>
The public FetcherSession methods pop `stealthy_headers` and hand it to
`_make_request` as `stealth`. SessionManager.fetch forwarded the request
kwargs untouched, so `Request(url, stealthy_headers=False)` reached
curl_cffi as an unknown argument, and the request failed with a TypeError
that the default `on_error` swallows. Map it the same way here.
When rules() is empty, or a matching CrawlRule has no callback, SitemapSpider followed each URL without a callback, so Response.follow() inherited _parse_sitemap from the sitemap request. It then parsed every page as a sitemap, and parse() was never called. The spider's parse() is now passed explicitly, as the docs describe.
Compare checkpoint paths as Path objects instead of POSIX string literals,
and read CSV output with read_text() so no file handle stays open when the
TemporaryDirectory is cleaned up (Windows refuses to delete open files).
- Strip a leading BOM before handing a robots.txt body to protego in
RobotsTxtManager and SitemapSpider. Left in place, it glues onto the first
directive, so a file starting with `User-agent: *` loses that whole group
(Disallow, Crawl-delay) and one starting with `Sitemap:` loses the sitemap.
- Strip it from CSV feed text too, so the first column is not keyed as
"\ufefftitle" for spreadsheet exports that start with a BOM.
- Added regression tests for all three paths.
Co-authored-by: Karim shoair <D4Vinci@users.noreply.github.com>
`extract()` fell back to the whole page whenever `scopes` was empty, which
also happens when `restrict_css`/`restrict_xpath` are set but match nothing
on the page. A rule scoped to e.g. `.pagination` then returned every link on
a page without that block (such as the last page), so `CrawlSpider` followed
navigation, footer and external links the rule was meant to exclude.
- Only fall back to the whole page when no restriction is configured.
- Added a regression test for CSS, XPath, and combined restrictions.
Co-authored-by: Karim shoair <D4Vinci@users.noreply.github.com>
* fix: robots.txt fetch failures cached as allow-all
* fix: cache deny-all result after robots.txt fetch failure
Per maintainer feedback on PR #443: instead of returning an
uncached deny-all parser directly from the 5xx/exception branches,
set content to "User-agent: *\nDisallow: /" and let execution fall
through to the existing parse/cache logic. A fetch failure is now
cached the same way as any other outcome, so queued pages on the
same domain reuse the deny-all result instead of re-fetching
robots.txt for each one.
Also trimmed the inline rationale comments in _get_parser down to
the two log.warning lines.
Updated tests in TestFailureCaching to assert caching instead of
no-caching: test_5xx_response_is_cached and
test_fetch_exception_is_cached now expect a single fetch call
across two can_fetch checks. Dropped test_recovers_once_fetch_succeeds
since a failure result no longer retries on the next call.
---------
Co-authored-by: Karim shoair <D4Vinci@users.noreply.github.com>
* fix: include params in the request fingerprint so paginated requests are not deduplicated away
* fix: use curl_cffi's update_url_params so the fingerprint follows the engine's URL rules for fragments, existing keys, and list/bool values
---------
Co-authored-by: Karim shoair <D4Vinci@users.noreply.github.com>
ResponseCacheManager.put() only recognized the flat `dict` shape that
static-engine responses use for `Response.cookies`. Browser engines
(Playwright) populate cookies as a `tuple` of full cookie dicts, so the
isinstance(dict) guard fell through to the `else {}` branch and silently
discarded every cookie before it ever reached the cache file. Replaying a
cached browser-engine response then rebuilt it with cookies={}.
Preserve whichever shape the cookies are in instead of collapsing anything
non-dict to {}: serialize a tuple as a JSON array and a dict as a JSON
object, then restore the tuple shape on read since JSON arrays deserialize
back as `list`.
Add regression tests covering both the browser-engine (tuple) and
static-engine (dict) cookie round-trip through put()/get().
CheckpointManager.save() and ResponseCacheManager.put() write to a temp
file and then move it into place with Path.rename(). On Windows, os.rename
cannot overwrite an existing destination and raises FileExistsError
(WinError 183), so every write after the first one fails: checkpoint
saving raises and breaks resume, while the development response cache
swallows the error and keeps returning the stale entry.
Path.replace() (os.replace) overwrites the destination atomically on every
platform and behaves identically to rename() on POSIX, so this is a no-op
on Linux and macOS and only fixes the broken overwrite on Windows.
Add a regression test for the cache overwrite path; the checkpoint
overwrite is already covered by test_multiple_saves_overwrite.
On force-stop (second Ctrl+C), cancel_scope.cancel() was called BEFORE
_save_checkpoint(). Since cancel_scope.cancel() causes all subsequent
awaits within the scope to raise Cancelled, the checkpoint write was
silently aborted:
1. _save_checkpoint() uses anyio.open_file + rename — both are await
checkpoints that get cancelled immediately
2. self.paused never gets set to True (code after the aborted save)
3. The finally block sees 'not self.paused' and calls cleanup() which
DELETES the previous checkpoint file
Result: a user who ran a long crawl, pressed Ctrl+C twice to force-stop,
loses their entire checkpoint irrecoverably. The old checkpoint (from
periodic saves or a previous graceful pause) is deleted, and the new
one was never written.
Fix: move the cancel_scope.cancel() call AFTER the checkpoint save.
The save completes normally, self.paused is set to True, and only then
does the scope get cancelled to abort in-flight tasks. The finally
block correctly sees paused=True and skips cleanup.
Adds 6 regression tests covering:
- Force-stop checkpoint preservation (core regression)
- Graceful pause still works
- Force-stop checkpoint is loadable
- Normal completion cleanup still works
- Force-stop without checkpoint system
- Existing checkpoint not deleted on force-stop
Previously robots.txt was fetched lazily on the first request per
domain, causing early concurrent requests to each stall waiting for
the same network fetch. The cache is now warmed before the crawl loop
starts, making all subsequent robots.txt lookups a local read.
- RobotsTxtManager gains a prefetch(urls, sid) method that fetches all domains concurrently via a task group
- CrawlerEngine._prefetch_robots_txt() is called after on_start():
uses allowed_domains if configured, otherwise falls back to unique
domains extracted from start_urls
- Mid-crawl domain discovery (not covered by prefetch) still fetches
lazily; two concurrent callbacks on the same new domain can each
trigger a fetch — accepted tradeoff, documented in _get_domain_delay
Files: scrapling/spiders/robotstxt.py, scrapling/spiders/engine.py, tests/spiders/test_engine.py
robots.txt is a domain-level document and does not vary by session.
Keying the cache by (domain, sid) was both wasteful and incorrect —
it caused redundant fetches when the same domain was accessed by different sessions.
- Cache is now keyed by domain string only; all sessions share one entry
- Removed asyncio.Event inflight-deduplication mechanism (superseded by the prefetch approach added in the next commit)
- clear_cache() loses the `sid` parameter (breaking change); clearing a domain now evicts the single shared entry for all sessions
- Updated tests to reflect shared-cache semantics
Files: scrapling/spiders/robotstxt.py, tests/spiders/test_robotstxt.py