🕷️ The BEST Web Scraping framework that handles everything from a single request to a full-scale crawl! Don't be shy, join here: https://discord.gg/EMgGbDceNQ and follow here for daily tips and tricks: https://x.com/Scrapling_dev
Python aiai-scrapingautomationcrawlercrawlingcrawling-pythondatadata-extractionmcpmcp-serverplaywrightpythonscrapingselectorsstealthweb-scraperweb-scrapingweb-scraping-pythonwebscrapingxpath
docs: Move changelog to the website with translations
Karim shoair330d2e685ac2
diff --git a/CHANGELOG.md b/docs/changelog.mdsimilarity index 82%rename from CHANGELOG.mdrename to docs/changelog.mdindex a608a82..8606d04 100644--- a/CHANGELOG.md+++ b/docs/changelog.md@@ -1,31 +1,42 @@-# Changelog+---+title: "Scrapling changelog"+description: "Release notes for Scrapling, including new features, fixes, and breaking changes."+---++# Changelog {#changelog}All notable changes to Scrapling, taken from the [GitHub releases](https://github.com/D4Vinci/Scrapling/releases).-## [v0.4.15](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.15) - 2026-08-23+## [v0.4.15](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.15) - 2026-08-23 {#v0.4.15}**One of the biggest releases this year: a reworked MCP server, RAG-ready Markdown in one line, an improved Cloudflare solver, and browser tabs that stay open for automation 🚀**-> [!WARNING]-> **This release introduces breaking changes to the MCP server. Check the [breaking changes](https://scrapling.readthedocs.io/en/latest/ai/mcp-server.html#breaking-changes) section before updating.**+!!! warning "Warning"++ **This release introduces breaking changes to the MCP server. Check the [breaking changes](https://github.com/D4Vinci/Scrapling/blob/v0.4.15/docs/ai/mcp-server.md#breaking-changes) section before updating.**-### 🚀 New Stuff and quality of life changes+### 🚀 New Stuff and quality of life changes {#v0.4.15-new-stuff-and-quality-of-life-changes}-- **Browser tabs now stay open and get reused across requests** (Check the [docs](https://scrapling.readthedocs.io/en/latest/fetching/dynamic.html#session-management)):+- **Browser tabs now stay open and get reused across requests** (Check the [docs](fetching/stealthy.md#session-management)):- All browser sessions keep their tabs after a request, and the next request reuses a free tab instead of opening a new one.- Every request re-applies its own settings (timeouts, headers, resource blocking) to the tab it gets, so nothing leaks between requests.- Tabs that hit an error are closed and replaced, and the new `close_pages()` method closes every open tab.- The page you fetched stays loaded, so a `page_setup` function on the next request runs on it before navigating away. That's the building block for chaining automation across requests.-- **Turn any page into clean, LLM-ready Markdown with `Response.markdown()`** (Check the [docs](https://scrapling.readthedocs.io/en/latest/ai/building-rag-systems.html)):++- **Turn any page into clean, LLM-ready Markdown with `Response.markdown()`** (Check the [docs](ai/building-rag-systems.md)):+```pythonfrom scrapling.fetchers import Fetchermarkdown = Fetcher.get("https://example.com").markdown(main_content_only=True)```+- Scripts, styles, and hidden prompt-injection content are always stripped first, the same cleaning the MCP server does.- Pass `css_selector` to convert only the elements you need.- Available through the new `rag` extra (`pip install "scrapling[rag]"`), which the `ai`/`shell`/`all` extras include too.-- **New `SiteToMarkdownSpider` template to crawl a whole website into a Markdown corpus for RAG pipelines** (Check the [docs](https://scrapling.readthedocs.io/en/latest/ai/building-rag-systems.html)):++- **New `SiteToMarkdownSpider` template to crawl a whole website into a Markdown corpus for RAG pipelines** (Check the [docs](ai/building-rag-systems.md)):+```pythonfrom scrapling.spiders import SiteToMarkdownSpider@@ -38,46 +49,50 @@ All notable changes to Scrapling, taken from the [GitHub releases](https://githuresult = DocsSpider().start()result.items.to_jsonl("docs.jsonl")```+- Yields one item per page with `url`/`title`/`markdown`, and the optional `output_dir` writes one Markdown file per page.- `max_pages` caps the crawl, and since it builds on `CrawlSpider`, overriding `rules()` gives you full control over which links get followed.-- **The MCP server is reworked (breaking)** (Check the [breaking changes](https://scrapling.readthedocs.io/en/latest/ai/mcp-server.html#breaking-changes) and the [docs](https://scrapling.readthedocs.io/en/latest/ai/mcp-server.html)):++- **The MCP server is reworked (breaking)** (Check the [breaking changes](https://github.com/D4Vinci/Scrapling/blob/v0.4.15/docs/ai/mcp-server.md#breaking-changes) and the [docs](ai/mcp-server.md)):- The 13 tools are now split into two modes: one-shot tools (`fetch`, `bulk_fetch`, `stealthy_fetch`, `bulk_stealthy_fetch`) that always launch their own browser and show their real defaults, and session tools that work through a session opened once.- The new `session_fetch` tool fetches through a browser session, while `open_session` now holds the browser-level settings only and returns the session's effective settings for the AI agent.- The `get` tool is renamed to `make_request`, and it now supports any HTTP method.- The new `open_request_session` and `session_make_request` tools give the AI persistent HTTP sessions that keep cookies and the browser fingerprint between requests.- This also ends fetches resetting the session's settings, first fixed by @Yigtwxx in [#418](https://github.com/D4Vinci/Scrapling/pull/418).-- **The MCP server's HTTP transport now requires authentication and binds to localhost by default (breaking)** by @yamantaka-singh in [#414](https://github.com/D4Vinci/Scrapling/pull/414) (Fixes [#413](https://github.com/D4Vinci/Scrapling/issues/413), check the [docs](https://scrapling.readthedocs.io/en/latest/ai/mcp-server.html#authentication)):++- **The MCP server's HTTP transport now requires authentication and binds to localhost by default (breaking)** by @yamantaka-singh in [#414](https://github.com/D4Vinci/Scrapling/pull/414) (Fixes [#413](https://github.com/D4Vinci/Scrapling/issues/413), check the [docs](ai/mcp-server.md#authentication)):- Pass `--auth-token` (or the `SCRAPLING_MCP_AUTH_TOKEN` environment variable) to require a bearer token, or `--no-auth` to serve it unauthenticated on purpose.- Pass `--host 0.0.0.0` to accept connections from the network.-### 🐛 Bug Fixes+### 🐛 Bug Fixes {#v0.4.15-bug-fixes}- **Cloudflare Turnstile/Interstitial solving now works regardless of the browser locale, and no longer loops forever on interactive challenges in headless mode**. Stealth pages also stop crashing mid-solve, with contributions by @subediparas5 in [#412](https://github.com/D4Vinci/Scrapling/pull/412). (Fixes [#411](https://github.com/D4Vinci/Scrapling/issues/411) and [#422](https://github.com/D4Vinci/Scrapling/issues/422))- **Fixed `find`/`find_all` with `class_` silently missing multi-class elements** by @yetval in [#410](https://github.com/D4Vinci/Scrapling/pull/410), **and blank `class_` values and unescaped CSS string values** by @yamantaka-singh in [#417](https://github.com/D4Vinci/Scrapling/pull/417).- **Fixed cached responses in `development_mode` losing the request meta on replay** by @Yigtwxx in [#419](https://github.com/D4Vinci/Scrapling/pull/419).- **Fixed HTTP requests with `retries` below 1 failing without sending the request** by @Yigtwxx in [#420](https://github.com/D4Vinci/Scrapling/pull/420).-### Docs+### Docs {#v0.4.15-docs}-- **The website sections are restructured**: a new "Using with AI" section holds the MCP server, the new [Agent skill](https://scrapling.readthedocs.io/en/latest/ai/agent-skill.html) page, and the [Building RAG systems](https://scrapling.readthedocs.io/en/latest/ai/building-rag-systems.html) guide, and the BeautifulSoup migration guide moved next to the Scrapy integration under "Integrations and migrations".-- **Added a [CHANGELOG.md](https://github.com/D4Vinci/Scrapling/blob/main/CHANGELOG.md)** to the repository with the notes of every release so far.+- **The website sections are restructured**: a new "Using with AI" section holds the MCP server, the new [Agent skill](ai/agent-skill.md) page, and the [Building RAG systems](ai/building-rag-systems.md) guide, and the BeautifulSoup migration guide moved next to the Scrapy integration under "Integrations and migrations".+- **Added a [changelog](changelog.md)** to the repository with the notes of every release so far.-## [v0.4.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.14) - 2026-08-10+## [v0.4.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.14) - 2026-08-10 {#v0.4.14}**A quick maintenance release to fix installation with `uv` 🔧**-### 🐛 Bug Fixes+### 🐛 Bug Fixes {#v0.4.14-bug-fixes}- **Fixed `uv` refusing to install v0.4.13 by default and silently falling back to an older version**. The previous release required a prerelease version of `curl_cffi`, which `uv` doesn't allow unless explicitly enabled.All dependencies now resolve to stable releases. (Fixes [#407](https://github.com/D4Vinci/Scrapling/issues/407))-## [v0.4.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.13) - 2026-08-09+## [v0.4.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.13) - 2026-08-09 {#v0.4.13}**A new update bringing feed spiders and a smarter MCP server 🎉**-### 🚀 New Stuff and quality of life changes+### 🚀 New Stuff and quality of life changes {#v0.4.13-new-stuff-and-quality-of-life-changes}++- **New feed spider templates**. `XMLFeedSpider` iterates over the nodes of any XML feed (RSS, Atom, product feeds, etc.), and `CSVFeedSpider` iterates over CSV rows as dictionaries. Both decompress gzipped feeds automatically. (Check the [docs](spiders/generic-templates.md))-- **New feed spider templates**. `XMLFeedSpider` iterates over the nodes of any XML feed (RSS, Atom, product feeds, etc.), and `CSVFeedSpider` iterates over CSV rows as dictionaries. Both decompress gzipped feeds automatically. (Check the [docs](https://scrapling.readthedocs.io/en/latest/spiders/generic-templates.html))```pythonfrom scrapling.spiders import XMLFeedSpider@@ -90,26 +105,28 @@ All dependencies now resolve to stable releases. (Fixes [#407](https://github.coresult = RSSSpider().start()```-- **Upgraded the MCP server to MCP SDK v2 and made it smarter**. The server now ships instructions that teach your AI agent how to use the tools efficiently; every tool declares annotations so clients like Claude Code can auto-approve the read-only ones; tool descriptions are leaner to save tokens; and the server advertises its version and logo to MCP clients. (Check the [docs](https://scrapling.readthedocs.io/en/latest/ai/mcp-server.html))++- **Upgraded the MCP server to MCP SDK v2 and made it smarter**. The server now ships instructions that teach your AI agent how to use the tools efficiently; every tool declares annotations so clients like Claude Code can auto-approve the read-only ones; tool descriptions are leaner to save tokens; and the server advertises its version and logo to MCP clients. (Check the [docs](ai/mcp-server.md))- **Added a `scrapling-mcp` command** that maps directly to `scrapling mcp`, so registering Scrapling with MCP clients and registries that expect a single command is now a one-liner.- **Unpinned Playwright/Patchright and browser versions**. The generated browser User-Agent now always matches the exact Chromium version your installed Playwright/Patchright drives, so Scrapling no longer pins their versions and you can upgrade them freely. Run `scrapling install --force` after updating to refresh the browsers.-### 🐛 Bug Fixes+### 🐛 Bug Fixes {#v0.4.13-bug-fixes}- **Fixed importing Scrapling crashing with a `browserforge` ValueError** when the fingerprints data package lags behind the browser versions. (Fixes [#394](https://github.com/D4Vinci/Scrapling/issues/394), [#396](https://github.com/D4Vinci/Scrapling/issues/396), and [#400](https://github.com/D4Vinci/Scrapling/issues/400))- **Fixed the MCP bulk browser tools mis-sizing their page pools**, which made `bulk_fetch` fail on batches of more than 50 URLs and `bulk_stealthy_fetch` fetch all URLs through a single tab, by @Yigtwxx in [#393](https://github.com/D4Vinci/Scrapling/pull/393).-### Project+### Project {#v0.4.13-project}- **New [AI Contribution Policy](https://github.com/D4Vinci/Scrapling/blob/main/AI_POLICY.md)**: AI-assisted contributions are welcome but must be disclosed in the PR or issue; submissions that look like undisclosed AI output get labeled and closed.-## [v0.4.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.12) - 2026-07-26+## [v0.4.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.12) - 2026-07-26 {#v0.4.12}**A release focused on making your spiders smarter about the websites they crawl**-### 🚀 New Stuff and quality of life changes+### 🚀 New Stuff and quality of life changes {#v0.4.12-new-stuff-and-quality-of-life-changes}++- **Spiders can now tune their own speed with AutoThrottle.** Instead of guessing a `download_delay` that's either too slow or gets you banned, the spider measures how fast each website answers and adjusts the delay of every domain on its own. When a website starts blocking or rate-limiting you, it doubles the delay (or waits exactly what the `Retry-After` header asks for) until that stops, then speeds back up. Your `download_delay` and any robots.txt `Crawl-delay` are still respected as the minimum. (Check the [docs](spiders/advanced.md#autothrottle))-- **Spiders can now tune their own speed with AutoThrottle.** Instead of guessing a `download_delay` that's either too slow or gets you banned, the spider measures how fast each website answers and adjusts the delay of every domain on its own. When a website starts blocking or rate-limiting you, it doubles the delay (or waits exactly what the `Retry-After` header asks for) until that stops, then speeds back up. Your `download_delay` and any robots.txt `Crawl-delay` are still respected as the minimum. (Check the [docs](https://scrapling.readthedocs.io/en/latest/spiders/advanced.html#autothrottle))```pythonclass MySpider(Spider):name = "adaptive"@@ -120,14 +137,16 @@ All dependencies now resolve to stable releases. (Fixes [#407](https://github.coautothrottle_block_backoff = True```-- **Export your results to CSV and XML**, next to the JSON/JSONL exporters you already had. Items that don't all share the same keys are still exported without losing anything, and nested values are written as JSON. (Check the [docs](https://scrapling.readthedocs.io/en/latest/spiders/getting-started.html))+- **Export your results to CSV and XML**, next to the JSON/JSONL exporters you already had. Items that don't all share the same keys are still exported without losing anything, and nested values are written as JSON. (Check the [docs](spiders/getting-started.md))+```pythonresult = MySpider().start()result.items.to_csv("products.csv")result.items.to_xml("products.xml")```-- **The MCP server can now require authentication**, so you can safely expose it instead of keeping it on your own machine. Any request without the token is rejected, and you can also restrict which hostnames the server answers to. (Check the [docs](https://scrapling.readthedocs.io/en/latest/ai/mcp-server.html))+- **The MCP server can now require authentication**, so you can safely expose it instead of keeping it on your own machine. Any request without the token is rejected, and you can also restrict which hostnames the server answers to. (Check the [docs](ai/mcp-server.md))+```bashscrapling mcp --http --auth-token "$(openssl rand -hex 32)"```@@ -136,7 +155,7 @@ All dependencies now resolve to stable releases. (Fixes [#407](https://github.co- **Published Docker images are now tagged with their release version** instead of only `latest`, so you can pin the exact version you want, by @JanRK in [#384](https://github.com/D4Vinci/Scrapling/pull/384).-### 🐛 Bug Fixes+### 🐛 Bug Fixes {#v0.4.12-bug-fixes}- **Fixed cached responses losing all their cookies** when the response came from a browser engine, which silently broke any session or auth logic relying on them while using the spiders' development mode, by @amitvijapur in [#379](https://github.com/D4Vinci/Scrapling/pull/379). (Fixes [#376](https://github.com/D4Vinci/Scrapling/issues/376))@@ -144,17 +163,18 @@ All dependencies now resolve to stable releases. (Fixes [#407](https://github.co- **Fixed a misleading error message in the storage system** and removed a dead call left after inserts, by @fix2015 in [#377](https://github.com/D4Vinci/Scrapling/pull/377).-### Performance+### Performance {#v0.4.12-performance}- **`get_all_text()` is now O(nodes)** instead of walking up the ancestors of every single text node, which makes it around 5-6x faster on deeply nested pages, by @yetval in [#378](https://github.com/D4Vinci/Scrapling/pull/378).-## [v0.4.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.11) - 2026-07-12+## [v0.4.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.11) - 2026-07-12 {#v0.4.11}**A solid update bringing the first platform spider template, a faster parser, and important fixes 🎉**-### 🚀 New Stuff and quality of life changes+### 🚀 New Stuff and quality of life changes {#v0.4.11-new-stuff-and-quality-of-life-changes}++- **Added `ShopifySpider`, the first platform spider template!** Extract every product from any Shopify-powered store through its JSON API without touching the website's HTML. Subclass it, set the store's domain, and you are done (Check the [docs](spiders/platform-templates.md))-- **Added `ShopifySpider`, the first platform spider template!** Extract every product from any Shopify-powered store through its JSON API without touching the website's HTML. Subclass it, set the store's domain, and you are done (Check the [docs](https://scrapling.readthedocs.io/en/latest/spiders/platform-templates/))```pythonfrom scrapling.spiders import ShopifySpider@@ -163,26 +183,29 @@ All dependencies now resolve to stable releases. (Fixes [#407](https://github.coresult = MyStore().start()```+- **Added `--executable-path` to the CLI browser commands**. Both `scrapling extract fetch` and `scrapling extract stealthy-fetch` now accept a custom Chromium-compatible browser executable, and fall back to the `SCRAPLING_EXECUTABLE_PATH` environment variable when the option isn't passed, bringing full parity with the MCP server (Solves [#371](https://github.com/D4Vinci/Scrapling/issues/371))+```bashscrapling extract fetch "https://example.com" page.html --executable-path "/path/to/chromium"```-### 🤖 Quality of life changes++### 🤖 Quality of life changes {#v0.4.11-quality-of-life-changes}- **Made `find_by_text` and `find_by_regex` up to ~2x faster** when `first_match` is enabled (the default) by wrapping elements lazily so the search stops at the first match, by @yetval in [#370](https://github.com/D4Vinci/Scrapling/pull/370)- **Updated the benchmarks with the new numbers against the latest versions of all libraries.**- **Updated contribution rules**-### 🐛 Bug Fixes+### 🐛 Bug Fixes {#v0.4.11-bug-fixes}- **Fixed the MCP server's fetch tools crashing on pages containing control characters** with the error `All strings must be XML compatible`, by @yetval in [#368](https://github.com/D4Vinci/Scrapling/pull/368) (Fixes [#366](https://github.com/D4Vinci/Scrapling/issues/366))-## [v0.4.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.10) - 2026-07-04+## [v0.4.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.10) - 2026-07-04 {#v0.4.10}**A new update with a brand-new Scrapy integration and a batch of community fixes 🎉**-### 🚀 New Stuff and quality of life changes+### 🚀 New Stuff and quality of life changes {#v0.4.10-new-stuff-and-quality-of-life-changes}-- **Added a Scrapy integration** so you can use Scrapling's parsing API inside your existing Scrapy projects without rewriting them. Put the `scrapling_response` decorator on any spider callback, and the response it receives becomes a Scrapling `Response` while Scrapy keeps handling the crawling (Check the [docs](https://scrapling.readthedocs.io/en/latest/integrations/scrapy/)):+- **Added a Scrapy integration** so you can use Scrapling's parsing API inside your existing Scrapy projects without rewriting them. Put the `scrapling_response` decorator on any spider callback, and the response it receives becomes a Scrapling `Response` while Scrapy keeps handling the crawling (Check the [docs](integrations/scrapy.md)):```pythonimport scrapy@@ -202,28 +225,28 @@ All dependencies now resolve to stable releases. (Fixes [#407](https://github.co- **The MCP server can now use a custom Chromium-compatible browser** for all browser-based tools. Set it once with `scrapling mcp --executable-path "/path/to/chromium"` or the `SCRAPLING_EXECUTABLE_PATH` environment variable, or per request with the `executable_path` argument, by @samrusani in [#360](https://github.com/D4Vinci/Scrapling/pull/360) (Solves [#347](https://github.com/D4Vinci/Scrapling/issues/347))- **Updated all browsers and fingerprints**. Run `scrapling install --force` after updating to refresh them.-### 🐛 Bug Fixes+### 🐛 Bug Fixes {#v0.4.10-bug-fixes}- **Fixed garbled text (mojibake) from browser fetchers on non-UTF-8 websites** by @yehudalevy-collab in [#365](https://github.com/D4Vinci/Scrapling/pull/365) (Fixes [#364](https://github.com/D4Vinci/Scrapling/issues/364)).- **Fixed `LinkExtractor` not filtering compound file extensions like `.tar.gz`** by @renbkna in [#359](https://github.com/D4Vinci/Scrapling/pull/359) (Fixes [#349](https://github.com/D4Vinci/Scrapling/issues/349)).- **Fixed paused crawls losing their in-flight requests from checkpoints, so resuming no longer skips them** by @yetval in [#358](https://github.com/D4Vinci/Scrapling/pull/358).- **Fixed spiders calculating wrong crawl delays from robots.txt `Request-rate` directives** through the Protego upgrade, with tests aligned by @Disaster-Terminator in [#355](https://github.com/D4Vinci/Scrapling/pull/355).-### Docs+### Docs {#v0.4.10-docs}- **Clarified how `init_script` interacts with Patchright's isolated execution context in stealth mode** by @mturac in [#353](https://github.com/D4Vinci/Scrapling/pull/353) (Solves [#350](https://github.com/D4Vinci/Scrapling/issues/350)).- **Added the [skills.sh](https://skills.sh/D4Vinci/Scrapling) install method for the agent skill** by @ob-aion in [#363](https://github.com/D4Vinci/Scrapling/pull/363).-## [v0.4.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.9) - 2026-06-07+## [v0.4.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.9) - 2026-06-07 {#v0.4.9}**A maintenance update packed with community-reported fixes 🛠️**-### 🚀 New Stuff and quality of life changes+### 🚀 New Stuff and quality of life changes {#v0.4.9-new-stuff-and-quality-of-life-changes}- **Updated all browsers and fingerprints**. Run `scrapling install --force` after updating to refresh them.- **Added a `--version` flag to the CLI** by @ETM-Code in [#303](https://github.com/D4Vinci/Scrapling/pull/303) (Solves [#299](https://github.com/D4Vinci/Scrapling/issues/299))-### 🐛 Bug Fixes+### 🐛 Bug Fixes {#v0.4.9-bug-fixes}- **Fixed the session-level `proxy` argument being silently ignored in HTTP sessions**, which could leak your real IP (Solves [#295](https://github.com/D4Vinci/Scrapling/issues/295)). Note that mixing a session-level `proxy` with a per-request `proxies` argument (or vice versa) now raises an error instead of one being silently dropped.- **Fixed browser navigations failing when combining `init_script` with `user_data_dir`** (Solves [#294](https://github.com/D4Vinci/Scrapling/issues/294)).@@ -232,19 +255,19 @@ All dependencies now resolve to stable releases. (Fixes [#407](https://github.co- **Fixed spiders' checkpoint and cache saving crashing on Windows** by @MrStarkEG in [#344](https://github.com/D4Vinci/Scrapling/pull/344).- **Fixed incorrect similarity scoring in `find_similar` for elements with mismatched attribute counts** (Solves [#322](https://github.com/D4Vinci/Scrapling/issues/322)).-### Docs+### Docs {#v0.4.9-docs}- **Clarified that the default installation includes the parser engine only**, and the fetchers/spiders need the extras (Solves [#343](https://github.com/D4Vinci/Scrapling/issues/343)).- **Fixed the Docker image name in the remaining examples** by @evanclan in [#315](https://github.com/D4Vinci/Scrapling/pull/315).- **Fixed a broken link in the contribution guide** by @Bortlesboat in [#320](https://github.com/D4Vinci/Scrapling/pull/320).-## [v0.4.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.8) - 2026-05-11+## [v0.4.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.8) - 2026-05-11 {#v0.4.8}**A big spider update that takes the crawling framework to the next level 🕷️**-### 🚀 New Stuff and quality of life changes+### 🚀 New Stuff and quality of life changes {#v0.4.8-new-stuff-and-quality-of-life-changes}-- **Added a `LinkExtractor` primitive** in `scrapling.spiders.LinkExtractor` to pull URLs out of a `Response`. There are a lot of controls (Check the [docs](https://scrapling.readthedocs.io/en/latest/spiders/generic-templates.html))+- **Added a `LinkExtractor` primitive** in `scrapling.spiders.LinkExtractor` to pull URLs out of a `Response`. There are a lot of controls (Check the [docs](spiders/generic-templates.md))```pythonfrom scrapling.spiders import LinkExtractor@@ -252,7 +275,7 @@ All dependencies now resolve to stable releases. (Fixes [#407](https://github.coextractor = LinkExtractor(allow=r"/posts/", deny_domains=["ads.example.com"])```-- **Added `CrawlSpider` and `CrawlRule`** generic spider templates so you no longer have to hand-write the same "follow links matching this pattern" boilerplate. Override `rules()` to return a list of `CrawlRule` objects, each pairing a `LinkExtractor`. (Check the [docs](https://scrapling.readthedocs.io/en/latest/spiders/generic-templates.html))+- **Added `CrawlSpider` and `CrawlRule`** generic spider templates so you no longer have to hand-write the same "follow links matching this pattern" boilerplate. Override `rules()` to return a list of `CrawlRule` objects, each pairing a `LinkExtractor`. (Check the [docs](spiders/generic-templates.md))```pythonfrom scrapling.spiders import CrawlSpider, CrawlRule, LinkExtractor@@ -275,7 +298,7 @@ All dependencies now resolve to stable releases. (Fixes [#407](https://github.co}```-- **Added a `SitemapSpider` template** that seeds a crawl directly from a sitemap, or `robots.txt` URLs. Handles gzip-compressed sitemaps, and a lot of controls and options. URLs are dispatched via the crawl rules as shown above for **CrawlSpider**. (Check the [docs](https://scrapling.readthedocs.io/en/latest/spiders/generic-templates.html))+- **Added a `SitemapSpider` template** that seeds a crawl directly from a sitemap, or `robots.txt` URLs. Handles gzip-compressed sitemaps, and a lot of controls and options. URLs are dispatched via the crawl rules as shown above for **CrawlSpider**. (Check the [docs](spiders/generic-templates.md))```pythonfrom scrapling.spiders import SitemapSpider, CrawlRule, LinkExtractor@@ -297,69 +320,75 @@ All dependencies now resolve to stable releases. (Fixes [#407](https://github.co- **Updated all browsers and fingerprints**. Run a new `scrapling install --force` after updating to refresh the browsers and fingerprints.-### 🐛 Bug Fixes+### 🐛 Bug Fixes {#v0.4.8-bug-fixes}- **Fixed `Fetcher.configure(...)` not applying to per-request calls**. Same fix applied to `AsyncFetcher`.- **Fixed incorrect request fingerprinting that caused duplicate requests in spiders** by @yetval in [#255](https://github.com/D4Vinci/Scrapling/pull/255).- **Fixed the Adaptive scraping engine staying silent on weak matches.** Combined with the threshold change above, you now get a warning instead of a misleading "best guess" element when relocation fails.-### Docs+### Docs {#v0.4.8-docs}- **Refreshed older code examples** across the documentation to match the current version.- **Improved the code copy-paste experience** on the docs site and trimmed the agent skill so it uses fewer tokens per invocation.-## [v0.4.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.7) - 2026-04-17+## [v0.4.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.7) - 2026-04-17 {#v0.4.7}**A focused update bringing eyes to your AI agents 📸**-### 🚀 New Stuff and quality of life changes+### 🚀 New Stuff and quality of life changes {#v0.4.7-new-stuff-and-quality-of-life-changes}- **Added a `screenshot` MCP tool** that captures a page and returns it as a real MCP `ImageContent` block so the model can actually see it. The tool requires an open browser session, so you call `open_session` first (either `dynamic` or `stealthy`) and pass the `session_id` here. Supports PNG and JPEG, full-page captures, JPEG quality, and the usual readiness controls (`wait`, `wait_selector`, `network_idle`, `timeout`). (implements [#244](https://github.com/D4Vinci/Scrapling/issues/244))- **Added a custom `session_id` parameter to `open_session`** so you can name sessions meaningfully (`"search"`, `"checkout"`) instead of the random 12-character hex default. By @hauntedhost in [#243](https://github.com/D4Vinci/Scrapling/pull/243)-### 🐛 Bug Fixes+### 🐛 Bug Fixes {#v0.4.7-bug-fixes}- **Fixed `FetcherSession` state corruption and a lazy session close crash**. By @yetval in [#245](https://github.com/D4Vinci/Scrapling/pull/245)- **Fixed `TypeError: Session.request() got an unexpected keyword argument 'block_ads'`** when using the CLI's `--ai-targeted` flag with HTTP commands. By @voidborne-d in [#249](https://github.com/D4Vinci/Scrapling/pull/249) (Fixes [#247](https://github.com/D4Vinci/Scrapling/issues/247))-### Translations+### Translations {#v0.4.7-translations}- **Added a Brazilian Portuguese README translation** By @rgomids in [#250](https://github.com/D4Vinci/Scrapling/pull/250)-## [v0.4.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.6) - 2026-04-13+## [v0.4.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.6) - 2026-04-13 {#v0.4.6}**A focused update on browser stealth, privacy, and developer experience 🔒**-### 🚀 New Stuff and quality of life changes+### 🚀 New Stuff and quality of life changes {#v0.4.6-new-stuff-and-quality-of-life-changes}- **Added built-in ad blocking** for browser fetchers. Pass `block_ads=True` to block requests to ~3,500 known ad and tracker domains at the route interception level -- no DNS, no TCP, instant abort. Can be combined with `blocked_domains` for custom lists. The MCP server and CLI `--ai-targeted` mode enable this automatically to save tokens and speed up page loads.+```pythonpage = StealthyFetcher.fetch('https://example.com', block_ads=True)```+- **Added DNS-over-HTTPS support** to prevent DNS leaks when using proxies. Pass `dns_over_https=True` to route DNS queries through Cloudflare's DoH, so your real location isn't exposed through DNS resolution even when your HTTP traffic goes through a proxy.+```pythonpage = StealthyFetcher.fetch('https://example.com', proxy='http://proxy:8080', dns_over_https=True)```+- **Added `page_setup` callback** for browser fetchers. A function that runs before `page.goto()`, letting you register event listeners, routes, or scripts that must be set up before the page navigates. Pairs with `page_action` (which runs after navigation). (Solves [#237](https://github.com/D4Vinci/Scrapling/issues/237))+```pythondef capture_websockets(page):page.on("websocket", lambda ws: print(f"WS: {ws.url}"))page = DynamicFetcher.fetch('https://example.com', page_setup=capture_websockets)```+- **Added `--block-ads` and `--dns-over-https` CLI options** to both `fetch` and `stealthy-fetch` commands.-### 🐛 Bug Fixes+### 🐛 Bug Fixes {#v0.4.6-bug-fixes}- **Fixed `Seconds` type alias** rejecting float values. Passing `wait=1.5` or `timeout=500.0` to browser fetchers would fail with a type error because the type alias incorrectly treated `float` as metadata instead of a type. by @kuishou68 in [#240](https://github.com/D4Vinci/Scrapling/pull/240)- **Fixed duplicate ID segments in full-path selector generation**. Elements with `id` attributes had their selector appended twice when generating full CSS/XPath paths, producing selectors like `body > #main > #main > #target > #target`. Also fixed full-path XPath emitting bare `[@id='x']` predicates (invalid XPath) instead of `*[@id='x']`. by @sjhddh in [#241](https://github.com/D4Vinci/Scrapling/pull/241)- **Fixed missing shell signature parameters**. The interactive shell was missing `blocked_domains`, `block_ads`, `retries`, `retry_delay`, `capture_xhr`, `executable_path`, and `dns_over_https` from its function signatures.-## [v0.4.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.5) - 2026-04-07+## [v0.4.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.5) - 2026-04-07 {#v0.4.5}**A focused update with one big quality-of-life feature for spider developers and a couple of important fixes 🎉**-### 🚀 New Stuff and quality of life changes+### 🚀 New Stuff and quality of life changes {#v0.4.5-new-stuff-and-quality-of-life-changes}- **Spider Development Mode**: Iterating on a spider's `parse()` logic used to mean re-hitting the target servers on every run, which is slow, noisy, and a great way to get rate-limited while you're still figuring out your selectors. The new development mode caches every response to disk on the first run and replays them from disk on every subsequent run, so you can tweak your callbacks and re-run as many times as you want without making a single network request. Enable it with one class attribute:@@ -373,91 +402,91 @@ All dependencies now resolve to stable releases. (Fixes [#407](https://github.coyield {"title": response.css("title::text").get("")}```- The cache lives in `.scrapling_cache/{spider.name}/` by default and can be redirected anywhere with `development_cache_dir`. Two new stat counters, `cache_hits` and `cache_misses`, let you see how the cache performed. Cache replay bypasses `download_delay`, rate limiting, and the blocked-request retry path so iteration is as fast as the disk allows. Don't ship a spider with `development_mode = True` -- it's a development tool, not a production cache. See the [docs](https://scrapling.readthedocs.io/en/latest/spiders/advanced.html#development-mode) for the full story.+ The cache lives in `.scrapling_cache/{spider.name}/` by default and can be redirected anywhere with `development_cache_dir`. Two new stat counters, `cache_hits` and `cache_misses`, let you see how the cache performed. Cache replay bypasses `download_delay`, rate limiting, and the blocked-request retry path so iteration is as fast as the disk allows. Don't ship a spider with `development_mode = True` -- it's a development tool, not a production cache. See the [docs](spiders/advanced.md#development-mode) for the full story.- **Safer redirects by default**: `follow_redirects` now defaults to `"safe"` across all HTTP fetchers, the MCP server, and the shell. Redirects are still followed, but ones targeting internal/private IPs (loopback, private networks, link-local) are rejected. This protects you from SSRF when scraping user-supplied URLs. Pass `follow_redirects="all"` to get the old behavior, or `False` to disable redirects entirely.-### 🐛 Bug Fixes+### 🐛 Bug Fixes {#v0.4.5-bug-fixes}- **Force-stop no longer loses your checkpoint**: Pressing Ctrl+C twice (force-stop) on a spider with `crawldir` enabled used to race against the checkpoint write -- the cancel scope would tear down the task before the pickle finished, leaving `paused=False` and triggering the cleanup path that *deletes* the previous checkpoint. The result was that force-stopping a long crawl could lose all the progress you were trying to save. The engine now writes the checkpoint **before** calling `cancel_scope.cancel()`, so a force-stop always preserves the latest pending state. By @voidborne-d in [#230](https://github.com/D4Vinci/Scrapling/pull/230).-## [v0.4.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.4) - 2026-04-05+## [v0.4.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.4) - 2026-04-05 {#v0.4.4}**A new update with important spider improvements and bug fixes 🎉**-### 🚀 New Stuff and quality of life changes+### 🚀 New Stuff and quality of life changes {#v0.4.4-new-stuff-and-quality-of-life-changes}- **Added robots.txt compliance to the Spider framework** with a new `robots_txt_obey` option. When enabled, the spider will automatically fetch and respect robots.txt rules before crawling, including `Disallow`, `Crawl-delay`, and `Request-rate` directives. Robots.txt files are fetched concurrently and cached per domain for the entire crawl. By @AbdullahY36 in [#226](https://github.com/D4Vinci/Scrapling/pull/226)- **Added robots.txt cache pre-warming** so all start_urls domains have their robots.txt fetched and parsed before the crawl loop begins, avoiding delays on the first request to each domain.- **Added a new `robots_disallowed_count` stat** to `CrawlStats` to track how many requests were blocked by robots.txt rules during a crawl.-Check it out on the website from [here](https://scrapling.readthedocs.io/en/latest/spiders/getting-started.html#robotstxt-compliance)+Check it out on the website from [here](spiders/getting-started.md#robotstxt-compliance)-### 🐛 Bug Fixes+### 🐛 Bug Fixes {#v0.4.4-bug-fixes}- **Fixed a critical MRO issue with `ProxyRotator`** where the `_build_context_with_proxy` stub was shadowing the real implementation from child classes, causing proxy rotation to always raise `NotImplementedError` (Fixes [#215](https://github.com/D4Vinci/Scrapling/issues/215)). Thanks @yetval- **Fixed a page pool leak** when using per-request proxy rotation with browser sessions. Pages created inside temporary contexts were not removed from the pool on cleanup, leading to stale references accumulating over time. By @yetval in [#223](https://github.com/D4Vinci/Scrapling/pull/223)- **Fixed a missing type assertion** in the static fetcher where `curl_cffi` could return `None` from `session.request()`, causing downstream errors.-### Other+### Other {#v0.4.4-other}- Updated dependencies, so expect the latest fingerprints and other stuff.- Added `protego` as a new dependency under the `fetchers` optional group for robots.txt parsing.-## [v0.4.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.3) - 2026-03-30+## [v0.4.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.3) - 2026-03-30 {#v0.4.3}**A new update with many important changes 🎉**-### 🚀 New Stuff and quality of life changes-- **Added a new MCP tool** to open a persistent normal/stealthy browser to keep using it with the rest of the tools, and another new tool to close it. ([Examples](https://scrapling.readthedocs.io/en/latest/ai/mcp-server.html?h=Using+Persistent+Sessions#examples))+### 🚀 New Stuff and quality of life changes {#v0.4.3-new-stuff-and-quality-of-life-changes}+- **Added a new MCP tool** to open a persistent normal/stealthy browser to keep using it with the rest of the tools, and another new tool to close it. ([Examples](https://github.com/D4Vinci/Scrapling/blob/v0.4.3/docs/ai/mcp-server.md#examples))- **Added a new MCP tool** to list all existing browser sessions. Aimed to be used with the new tools.-- **Added a new option to browser sessions** to automatically collect all background requests that happen during a request (Solves [#159](https://github.com/D4Vinci/Scrapling/pull/159)) [[Examples](https://scrapling.readthedocs.io/en/latest/fetching/dynamic.html#capturing-xhrfetch-requests)].+- **Added a new option to browser sessions** to automatically collect all background requests that happen during a request (Solves [#159](https://github.com/D4Vinci/Scrapling/pull/159)) [[Examples](https://github.com/D4Vinci/Scrapling/blob/v0.4.3/docs/fetching/dynamic.md#capturing-xhrfetch-requests)].- **Added a new sanitizer** to protect the MCP server from common Prompt Injection attacks by removing hidden/invisible content.- **Added a new commandline option** called `--ai-targeted` to the Web Scraping commands to make content targeted to AI and safe against common Prompt Injection attacks like the MCP server.- **Added a new option to browser sessions** called `executable_path` to allow setting a custom browser path (Solves [#202](https://github.com/D4Vinci/Scrapling/pull/202))- **Refactored** the MCP server code to be easily maintained and unified all tools to be async.- **Refactored** the CLI commands code to be easily maintained and shorter by 210 lines.-### 🐛 Bug Fixes+### 🐛 Bug Fixes {#v0.4.3-bug-fixes}- A fix to preserve HTTP method across retries in spider session by @karesansui-u in [#201](https://github.com/D4Vinci/Scrapling/pull/201)- Added a max retry limit to getting page content to prevent infinite loop by @haosenwang1018 & @D4Vinci in [#197](https://github.com/D4Vinci/Scrapling/pull/197)- Replace bare `raise` with `return False` in `_restore_from_checkpoint` by @haosenwang1018 in [#196](https://github.com/D4Vinci/Scrapling/pull/196)- Replaced `get_all` with `getall` in `Texthandler` to match the Selector class.-### Coverage/tests improvement+### Coverage/tests improvement {#v0.4.3-coverage-tests-improvement}- Added `_normalize_credentials` edge case coverage tests by @Bortlesboat in [#192](https://github.com/D4Vinci/Scrapling/pull/192)- Added save/retrieve round-trip and core storage coverage tests by @haosenwang1018 in [#193](https://github.com/D4Vinci/Scrapling/pull/193)- Added coverage for `TextHandler` regex paths and `TextHandlers.re()` by @haosenwang1018 in [#194](https://github.com/D4Vinci/Scrapling/pull/194)- Added edge case tests for `filter`, `iterancestors`, and `find_similar` by @awanawana in [#200](https://github.com/D4Vinci/Scrapling/pull/200)-### Agent Skill improvement+### Agent Skill improvement {#v0.4.3-agent-skill-improvement}- Fixed broken markdown links in skill references by @yetval in [#204](https://github.com/D4Vinci/Scrapling/pull/204)- Improved the skill structure to be more acceptable by [Clawhub](https://clawhub.ai/d4vinci/scrapling-official) validation.- Forced the skill to use the `--ai-targeted` commandline option when scraping through commandline commands.-### Docs improvement+### Docs improvement {#v0.4.3-docs-improvement}- Added Korean README translation by @greatsk55 in [#187](https://github.com/D4Vinci/Scrapling/pull/187)- CJK Latin spacing fixes for the Chinese and Japanese READMEs.- Fixed broken links from the old website design.-## [v0.4.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.2) - 2026-03-08+## [v0.4.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.2) - 2026-03-08 {#v0.4.2}**A new maintenance update with important changes**-#### Bug fixes+#### Bug fixes {#v0.4.2-bug-fixes}- The function `get_all_text()` now captures tail text nodes. This will make the MCP server and commands see text that was missed before ([#168](https://github.com/D4Vinci/Scrapling/pull/168)). Thanks @mhillebrand- Referer now returns a bare Google url instead of a Google search URL. The previous logic was incorrect and may have produced a fingerprinting signal ([#179](https://github.com/D4Vinci/Scrapling/pull/179)). Thanks @Bortlesboat- Fixed an issue with extra flags concatenation in all browsers. Thanks @rostchri- Fixed a type hints issue with Python versions below 3.12 that caused it to crash. (Solves [#163](https://github.com/D4Vinci/Scrapling/issues/163))-#### Other+#### Other {#v0.4.2-other}- Added an Agent Skill for Claude Code / OpenClaw and other AI agentic tools.- Added the Agent Skill to Clawhub.- Updates all browsers and Playwright versions to the latest.- Added a French translation to the main README file.-## [v0.4.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.1) - 2026-02-27+## [v0.4.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.1) - 2026-02-27 {#v0.4.1}**A new update with many important changes**-### 🚀 New Stuff and quality of life changes+### 🚀 New Stuff and quality of life changes {#v0.4.1-new-stuff-and-quality-of-life-changes}- **Improved regex precision** for Cloudflare challenge detection (Thanks to @Rinz27 [#133](https://github.com/D4Vinci/Scrapling/pull/133))- **Improved the speed and efficiency** of the Cloudflare solver. Now it is nearly twice as fast.- **Improved the Cloudflare solver** to handle the case where websites sometimes show the Cloudflare page twice before redirecting to the main website.@@ -469,14 +498,13 @@ Check it out on the website from [here](https://scrapling.readthedocs.io/en/late- Added a new code snippet to show how to install the browsers deps through code instead of using the commandline to allow easier automation.- Improved all workflows by using the latest actions versions (Thanks to @salmanmkc [#143](https://github.com/D4Vinci/Scrapling/pull/143)/[#144](https://github.com/D4Vinci/Scrapling/pull/144))-## [v0.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4) - 2026-02-15+## [v0.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4) - 2026-02-15 {#v0.4}-**The biggest release of Scrapling yet — introducing the Spider framework, proxy rotation, and major parser improvements**+**The biggest release of Scrapling yet - introducing the Spider framework, proxy rotation, and major parser improvements**This release brings a fully async spider/crawling framework, intelligent proxy management, and significant API changes that make Scrapling more powerful and consistent. Please review the breaking changes section carefully before upgrading.-🕷️ Spider Framework-============+### 🕷️ Spider Framework {#v0.4-spider-framework}A new async crawling framework built on top of `anyio` for structured, large-scale scraping:@@ -493,6 +521,7 @@ class MySpider(Spider):MySpider().start()```+- **Scrapy-like Spider API**: Define spiders with `start_urls`, async `parse` callbacks, `Request`/`Response` objects, and priority queue.- **Concurrent Crawling**: Configurable concurrency limits, per-domain throttling, and download delays.- **Multi-Session Support**: Unified interface for HTTP requests, and stealthy headless browsers in a single spider - route requests to different sessions by ID. Supports lazy session initialization.@@ -504,22 +533,22 @@ MySpider().start()- **Detailed crawl stats**: track requests, responses, bytes, status codes, proxies, per-domain/session breakdowns, log level counts, and more.- **uvloop support**: Pass `use_uvloop=True` to `spider.start()` for faster async execution when available.-A new section has been added to the website with the Full details. Click [here](https://scrapling.readthedocs.io/en/latest/spiders/architecture.html)+A new section has been added to the website with the Full details. Click [here](spiders/architecture.md)-🔄 Proxy Rotation-============+### 🔄 Proxy Rotation {#v0.4-proxy-rotation}* New `ProxyRotator` class with thread-safe rotation. Works with all fetchers and sessions:+```pythonfrom scrapling import ProxyRotatorrotator = ProxyRotator(["http://proxy1:8080", "http://proxy2:8080"])Fetcher.get(url, proxy_rotator=rotator)```+* **Custom rotation strategies**: Make your own proxy rotation logic* **Per-request proxy override**: Pass `proxy=` to any individual `get()`/`post()`/`fetch()` call to override the session proxy for that request.-🌐 Browser Fetcher Improvements-============+### 🌐 Browser Fetcher Improvements {#v0.4-browser-fetcher-improvements}* **Domain blocking**: New `blocked_domains` parameter on `DynamicFetcher`/`StealthyFetcher` to block requests to specific domains (subdomains matched automatically).* **Automatic retries**: Browser fetchers now retry on failure with `retries` (default: 3) and `retry_delay` (default: 1s) parameters. Includes proxy-aware error detection.@@ -528,16 +557,14 @@ A new section has been added to the website with the Full details. Click [here](* **No autoplay**: Browser sessions are now blocking autoplay content, which caused issues before.* **Speed**: Improved stealth and speed by adjusting browser flags.-🔧 Bug Fixes & Improvements-============+### 🔧 Bug Fixes & Improvements {#v0.4-bug-fixes-improvements}- **Parser optimization**: Optimized the parser for repeated operations, improving performance.- **Errored pages**: Fixed a bug that caused the browser to not close when pages gave errors.- **Empty body**: Handle responses with empty body.- **Playwright loop**: Solving an issue with leaving the Playwright loop open when CDP connection fails- **Type safety**: Fixed all mypy errors and added type hints across untyped function bodies. Added mypy and pyright to the CI workflow.-⚠️ Breaking Changes-============+### ⚠️ Breaking Changes {#v0.4-breaking-changes}* **`css_first`/`xpath_first` removed**: Use `css('.selector').first`, `css('.selector')[0]`, or `css('.selector').get()` instead.* **All selection now returns `Selectors`**: `css('::text')`, `xpath('//text()')`, `css('::attr(href)')`, and `xpath('//@href')` now return `Selectors` (wrapping text nodes in `Selector` objects with `tag="#text"`) instead of `TextHandlers`. This makes the API consistent across all selection methods and the type hints.@@ -546,24 +573,23 @@ A new section has been added to the website with the Full details. Click [here](* **`Selectors.first`/`.last`**: Safe accessors that return `Selector | None` instead of raising `IndexError`.* **Internal constants renamed**: `DEFAULT_FLAGS` → `DEFAULT_ARGS`, `DEFAULT_STEALTH_FLAGS` → `STEALTH_ARGS`, `HARMFUL_DEFAULT_ARGS` → `HARMFUL_ARGS`, `DEFAULT_DISABLED_RESOURCES` → `EXTRA_RESOURCES`.-🔨 Other Changes-============+### 🔨 Other Changes {#v0.4-other-changes}* **Dependency changes**: Replaced `tldextract` with `tld`, removed internal `_html_utils.py` in favor of `w3lib.html.replace_entities`, added `typing_extensions` as a hard requirement.* **Docs overhaul**: Full switch from MkDocs to Zensical, new spider documentation section, updated all existing pages, and added new API references.-## [v0.3.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.14) - 2026-01-03+## [v0.3.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.14) - 2026-01-03 {#v0.3.14}**A minor maintenance update to fix issues that happened with some devices in v0.3.13**- Disabled the incognito mode in `StealthyFetcher` and its session classes since it made cookies not persistent across pages on Windows devices. It didn't happen on MacOS and Linux (Fixes [#123](https://github.com/D4Vinci/Scrapling/issues/123), thanks to @frugality4121 for bringing it up and to @gembleman for pointing out the solution).- Pinned down the last version of browserforge to solve the issue with old header models for users with an already old browserforge version.-## [v0.3.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.13) - 2026-01-01+## [v0.3.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.13) - 2026-01-01 {#v0.3.13}**This is a big update with many improvements across many places, but also many breaking changes for good reasons. Please read the below before updating**-* For many reasons, we decided that from now on, we will stop using Camoufox entirely, and we might switch back to it in the future if its development continues. If you prefer to continue using Camoufox as before this release, there are instructions for that in this [section](https://scrapling.readthedocs.io/en/latest/fetching/stealthy/#using-camoufox-as-an-engine).+* For many reasons, we decided that from now on, we will stop using Camoufox entirely, and we might switch back to it in the future if its development continues. If you prefer to continue using Camoufox as before this release, there are instructions for that in this [section](https://github.com/D4Vinci/Scrapling/blob/v0.3.13/docs/fetching/stealthy.md#using-camoufox-as-an-engine).* Previously, we were using patchright in the stealth mode inside `DynamicFetcher` and its session classes. Now we removed the stealth mode from them and started using patchright inside `StealthyFetcher` and its session classes, with A LOT of improvements, as you will see, improving the stealth overall on top of patchright.@@ -571,14 +597,14 @@ A new section has been added to the website with the Full details. Click [here](This will also shorten the installation time of the `scrapling install` command, reduce the size of the Docker image, improve test smoothness in GitHub's CI, and make scrapling less confusing for new users.-### Breaking changes+### Breaking changes {#v0.3.13-breaking-changes}1. The `stealth` argument was removed from the `DynamicFetcher` class and its session class, while the `hide_canvas` argument was moved to the `StealthyFetcher` and its session classes.2. The `disable_webgl` argument has been moved from `DynamicFetcher` to the `StealthyFetcher` class and renamed as `allow_webgl`. All session classes as well.3. The `StealthyFetcher` class is now basically the new stealthy version of `DynamicFetcher`, so the following arguments are removed: `block_images`, `humanize`, `addons`, `os_randomize`, `disable_ads`, and `geoip`. I tried to replicate them in Chromium, but each had its own problem. This might change with upcoming releases before v0.4.Now to the good news, we have improved and fixed a lot of stuff :)-### Improvements+### Improvements {#v0.3.13-improvements}- You already know that the `StealthyFetcher` class and its session classes are now 101% faster than before, but now also the `DynamicFetcher` class and its session class are 20% faster.- Cloudflare's solver algorithm has been improved over before now to finish faster and handle more cases. Also, thanks to the new refactor, expect the solver to solve the captcha twice as fast!- All fetchers now use less memory.@@ -586,25 +612,25 @@ Now to the good news, we have improved and fixed a lot of stuff :)- The Docker image is now 60% smaller.- The whole documentation website has been updated with the new stuff. At the same time, it was made more explicit, many sections were shortened, more examples were added, missing arguments were included, the API reference section was updated with graphs, and many other improvements were made. The Website now loads 130% faster, uses less data, and is better for SEO.-### Fixes+### Fixes {#v0.3.13-fixes}- Added the arguments that were missing before in the Web Scraping shell shortcuts and made them more accurate.- Fixed the issue where the `google_search` argument was creating a Google referrer even if the URL is a localhost/IP.-## [v0.3.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.12) - 2025-12-18+## [v0.3.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.12) - 2025-12-18 {#v0.3.12}-### What's Changed+### What's Changed {#v0.3.12-what-s-changed}- Added a new argument to `DynamicSession`/`AsyncDynamicSession` classes called `timezone_id`, which allows you to set the timezone of the browser so that it matches the timezone of the Proxy/VPN you are using. That way, the websites can't detect that you are using a proxy through the timezone mismatch technique.- Improved the automated conversion of response to JSON.- Renamed the internal function `__create__` to `start` inside fetchers' session classes to make it easier to use them outside the `with` context.- Updated `curl_cffi` and other deps to the latest versions.-## [v0.3.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.11) - 2025-12-03+## [v0.3.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.11) - 2025-12-03 {#v0.3.11}-### What's Changed+### What's Changed {#v0.3.11-what-s-changed}- Added a better logic for handling timeout errors when the `network_idle` argument is used on an unstable website (websites with media playing, etc.)- Fixed the autocompletion for the `stealthy_fetch` shortcut in the Web Scraping Shell-## [v0.3.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.10) - 2025-11-26+## [v0.3.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.10) - 2025-11-26 {#v0.3.10}**A maintenance update with many significant changes and possible breaking changes**@@ -614,60 +640,62 @@ Now to the good news, we have improved and fixed a lot of stuff :)- **Pumped up** the version for the Maxmind database, which will improve the `geoip` argument for `StealthyFetcher` and its session classes.- **Updated** all used browser versions to the latest available ones.- **BREAKING** - all fetchers had gone through a big refactor, which resulted in some interesting things that might break your code:- 1. Scrapling codebase is now smaller by ~750 lines and many changes which would make maintenance very much easier in the future and use a bit less resources.- 2. The validation for all fetchers and their session classes became much faster, which will reflect on their overall speed.- 3. To achieve this, now all fetchers can't accept standard arguments other than the `url` argument; the rest of the arguments must be keyword-arguments so your code must be like `Fetcher.get('https://google.com', stealthy_headers=True)` not `Fetcher.get('https://google.com', True)` if you were doing that for some reason!- 4. An annoying difference between browser-based fetchers and their session classes since v0.3 was that the argument used to pass custom parser settings per request was called `custom_config`, while it was named `selector_config` in the session classes. This refactor allowed us to unify the naming to `selector_config` without breaking your code, so the main one is now `selector_config` with backward compatibility for the `custom_config` argument. The autocompletion support will be available only for the `selector_config` argument.- 5. Also, to achieve all of this, we had to make the type hints of the fetchers' functions dynamically generated, so if you don't get a proper autocompletion in your IDE, make sure you are using a modern version of it. We have tested almost all known IDEs/editors.+ 1. Scrapling codebase is now smaller by ~750 lines and many changes which would make maintenance very much easier in the future and use a bit less resources.+ 2. The validation for all fetchers and their session classes became much faster, which will reflect on their overall speed.+ 3. To achieve this, now all fetchers can't accept standard arguments other than the `url` argument; the rest of the arguments must be keyword-arguments so your code must be like `Fetcher.get('https://google.com', stealthy_headers=True)` not `Fetcher.get('https://google.com', True)` if you were doing that for some reason!+ 4. An annoying difference between browser-based fetchers and their session classes since v0.3 was that the argument used to pass custom parser settings per request was called `custom_config`, while it was named `selector_config` in the session classes. This refactor allowed us to unify the naming to `selector_config` without breaking your code, so the main one is now `selector_config` with backward compatibility for the `custom_config` argument. The autocompletion support will be available only for the `selector_config` argument.+ 5. Also, to achieve all of this, we had to make the type hints of the fetchers' functions dynamically generated, so if you don't get a proper autocompletion in your IDE, make sure you are using a modern version of it. We have tested almost all known IDEs/editors.> We have also updated all benchmark tables with the current numbers against the latest versions of all alternative libraries.-## [v0.3.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.9) - 2025-11-17+## [v0.3.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.9) - 2025-11-17 {#v0.3.9}**A new update with many important changes**-### 🚀 New Stuff and quality of life changes+### 🚀 New Stuff and quality of life changes {#v0.3.9-new-stuff-and-quality-of-life-changes}- Now the `impersonate` argument in `Fetcher` and `FetcherSession` can accept a list of browsers that the library will choose a random browser from them with each request.+```pythonfrom scrapling.fetchers import FetcherSessionwith FetcherSession(impersonate=['chrome', 'firefox', 'safari']) as s:s.get('https://github.com/D4Vinci/Scrapling')```+- A new argument to the `clean` method in `TextHandler` to remove html entities from the current text easily.- Huge improvements to the documentation with more precise explanations of many parts and automatic translations of the main `README.md` file.-### 🐛 Bug Fixes+### 🐛 Bug Fixes {#v0.3.9-bug-fixes}- Fixed a big issue with retrieving responses from browser-based fetchers. Now, there is intelligent content type detection that ensures `response.body` contains the rendered browser content only if the content is HTML; otherwise, it contains the raw content of the last request made. This allows you to download binary files and text-based files without having to find them wrapped in HTML tags, while being able to retrieve the rendered content you want from the website when fetching it.-### 🔨 Misc+### 🔨 Misc {#v0.3.9-misc}- Updated the contributing guide to make it clearer and easier.- Add a new workflow to enforce code quality tools (Same ones used as pre-commit hooks).-## [v0.3.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.8) - 2025-10-27+## [v0.3.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.8) - 2025-10-27 {#v0.3.8}**A new update with many important changes**-### 🚀 New Stuff and quality of life changes+### 🚀 New Stuff and quality of life changes {#v0.3.8-new-stuff-and-quality-of-life-changes}- For all browser-based fetchers: websites that never finish loading their requests won't crash the code now if you used `network_idle` with them.- The logic for collecting/checking for page content in browser-based fetchers has been changed to make browsers more stable on Windows systems now, as Linux/MacOS (All this difference in behaviour is because of Playwright's different implementation on Windows systems).- Refactored all the validation logic, which made all requests done from all browser-based fetchers faster by 8-15%- A New option called `extra_flags` has been added to `DynamicFetcher` and its session to allow users to add custom Chrome flags to the existing ones while launching the browser.- Reverted the route logic for catching responses (changed in the last version) to use the old routing version when `page_action` is used. This was added to collect the latest version of a page's content in case `page_action` changes it without making a request. (Thanks for @gembleman to pointing it in [#100](https://github.com/D4Vinci/Scrapling/issues/100) and [#102](https://github.com/D4Vinci/Scrapling/pull/102) )-### 🐛 Bug Fixes+### 🐛 Bug Fixes {#v0.3.8-bug-fixes}- Fixed a typo in `load_dom` in DynamicSession's async_fetch- Fixed an issue with Cloudflare solver that made the solver wait forever for embedded captchas that don't disappear after solving. Now it will wait for the captcha to disappear for 30 seconds, then assume it's the type that doesn't disappear (Fixes #100 )-### 🔨 Misc+### 🔨 Misc {#v0.3.8-misc}- Now the Docker image is automatically pushed to Dockerhub and GitHub's container registry for user convenience.-- Added a [new documentation page](https://scrapling.readthedocs.io/en/latest/tutorials/external/) to show how to use Scrapeless browser with Scrapling.+- Added a [new documentation page](https://github.com/D4Vinci/Scrapling/blob/v0.3.8/docs/tutorials/external.md) to show how to use Scrapeless browser with Scrapling.-## [v0.3.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.7) - 2025-10-12+## [v0.3.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.7) - 2025-10-12 {#v0.3.7}**A new update with many important changes**-### 🚀 New Stuff and quality of life changes+### 🚀 New Stuff and quality of life changes {#v0.3.7-new-stuff-and-quality-of-life-changes}- Reworked `solve_cloudflare` argument in `StealthyFetcher` to make it able to solve all kinds of custom implementations of Turnstile.- Refactored the entire codebase to be acceptable by Pyright, so expect a flawless IDE experience now with all software and many bugs solved.- Refactored the requests logic to be cleaner and faster (Also solves #97 )@@ -675,101 +703,106 @@ with FetcherSession(impersonate=['chrome', 'firefox', 'safari']) as s:- Added a new customization option `additional_args` to `Dynamic fetcher` and its session class to enable the user to pass extra arguments to Playwright's context, as we had with `StealthyFetcher` before.- The route logic for collecting the last navigation response for all browsers has been improved, which allows the raw responses to be passed to the parser before being processed by the browsers as before. This will be very helpful with text/JSON responses.-### 🐛 Bug Fixes+### 🐛 Bug Fixes {#v0.3.7-bug-fixes}- The rework of the route logic solved an issue with retrieving the content of unstable websites on some Windows devices.- All the refactors that happened in this version solved a lot of bugs along the way that were hard to spot before, and weird autocompletion issues with some IDEs.- Many fixes to the documentation website-## [v0.3.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.6) - 2025-10-01+## [v0.3.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.6) - 2025-10-01 {#v0.3.6}-### 🚀 New Stuff-- Improved the `solve_cloudflare` argument in `StealthyFetcher` and its session classes to be able to solve all types of both Turnstile and interstitial Cloudflare challenges 🎉+### 🚀 New Stuff {#v0.3.6-new-stuff}+- Improved the `solve_cloudflare` argument in `StealthyFetcher` and its session classes to be able to solve all types of both Turnstile and interstitial Cloudflare challenges 🎉- Now the MCP server has the option to use `Streamable HTTP`, so you can easily expose the server.- Added Docker support, so now an image is built and pushed to Docker Hub automatically with each release (contains all browsers)-### 🐛 Bug Fixes+### 🐛 Bug Fixes {#v0.3.6-bug-fixes}- Fixed an encoding issue with the parser that happened in some cases (the famous `invalid start byte` error)- Restructured multiple parts of the library to fix some memory leaks, so now enjoy noticably lower memory usage based on your config (Also solves #92 )- Improved type annotation in many parts of the code so you can have a better IDE experience (Also solves #93 )-## [v0.3.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.5) - 2025-09-20+## [v0.3.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.5) - 2025-09-20 {#v0.3.5}**Necessary release that fixes multiple issues**-### 🚀 New Stuff+### 🚀 New Stuff {#v0.3.5-new-stuff}- All browser-based fetchers (`DynamicFetcher`/`StealthyFetcher`/...) and their session classes are now fetching websites 15-20%:- 1. Page management is now much faster due to the logic improvement by @AbdullahY36 in #87- 2. Optimized the validation logic overall and improved page creation for sync fetches, which together introduced a lot of speed improvements+ 1. Page management is now much faster due to the logic improvement by @AbdullahY36 in #87+ 2. Optimized the validation logic overall and improved page creation for sync fetches, which together introduced a lot of speed improvements- Big improvements to the stealth mode in `DynamicFetcher` and its session classes by replacing `rebrowser-playwright` with `PatchRight`:- 1. Before this update, `rebrowser-playwright` was turned off when you enabled `stealth` and `real_chrome` because they weren't doing well together, but now we don't have this issue with `PatchRight`- 2. You can now interact with Closed-Shadow Roots since `PatchRight` can handle them automatically.+ 1. Before this update, `rebrowser-playwright` was turned off when you enabled `stealth` and `real_chrome` because they weren't doing well together, but now we don't have this issue with `PatchRight`+ 2. You can now interact with Closed-Shadow Roots since `PatchRight` can handle them automatically.-### 🐛 Bug Fixes+### 🐛 Bug Fixes {#v0.3.5-bug-fixes}- Fixed a bug that happens while using the `re` method from the `Selectors` class.- Fixed a bug with `uncurl` and `curl2fetcher` commands in the Web Scraping Shell that made curl's `--data-raw` flag parse incorrectly.- Fixed a bug with the `view` command in the Web Scraping Shell that depended on the website's encoding to happen.- Fixed a bug with content converting that affected the `mcp` mode and `extract` commands.-### New Contributors+### New Contributors {#v0.3.5-new-contributors}- @AbdullahY36 made their first contribution in #87-## [v0.3.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.4) - 2025-09-16+## [v0.3.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.4) - 2025-09-16 {#v0.3.4}**Necessary release that fixes multiple issues**-### 🚀 New Stuff+### 🚀 New Stuff {#v0.3.4-new-stuff}- Added all the fetchers session classes to the interactive shell to be available right away without import.-### 🐛 Bug Fixes+### 🐛 Bug Fixes {#v0.3.4-bug-fixes}- Added a workaround for a bug with the Playwright API on Windows that happened while retrieving content while solving Cloudflare.- Fixed an encoding issue with the `view` command in the interactive shell- Fixed a bug with the `max_pages` argument in `AsyncStealthySession` that was crashing the code.- Fixed an issue that happened with the last updates that made the `html_content` and `prettify` properties in the `Selector` class return bytes, depending on the encoding. Both are returning strings as they were.-## [v0.3.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.3) - 2025-09-15+## [v0.3.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.3) - 2025-09-15 {#v0.3.3}- Removed the logic that is removing the default browser tab on browser-based fetchers since it caused a crashing error (Not happening on Mac, only managed to produce on Windows and Linux)-## [v0.3.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.2) - 2025-09-15+## [v0.3.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.2) - 2025-09-15 {#v0.3.2}Release Notes for v0.3.2-### 🚀 New Stuff+### 🚀 New Stuff {#v0.3.2-new-stuff}-- **Optional fetcher dependencies**: All fetchers are now part of optional dependency groups, reducing core package size. So the base `scrapling` module is now the parser only, and to use the fetchers or the commandline options, you have to do: `pip install "scrapling[fetchers]"`. Check out the detailed installation instructions from [here](https://scrapling.readthedocs.io/en/latest/#installation)-- **Per-page configuration in sessions**: Session classes for browser fetchers now support individual configuration per page in sessions. All fetch-level parameters are now validated like session-level ones. More details on the documentation website [here](https://scrapling.readthedocs.io/en/latest/fetching/dynamic/#full-list-of-arguments)+- **Optional fetcher dependencies**: All fetchers are now part of optional dependency groups, reducing core package size. So the base `scrapling` module is now the parser only, and to use the fetchers or the commandline options, you have to do: `pip install "scrapling[fetchers]"`. Check out the detailed installation instructions from [here](index.md#installation)+- **Per-page configuration in sessions**: Session classes for browser fetchers now support individual configuration per page in sessions. All fetch-level parameters are now validated like session-level ones. More details on the documentation website [here](fetching/stealthy.md#full-list-of-arguments)<br>Example:+```pythonwith StealthySession(headless=True, solve_cloudflare=True) as session:page = session.fetch('https://nopecha.com/demo/cloudflare', google_search=False)```+- **Improved browser-based fetchers**- - A new option to control whether to wait for JavaScript execution to finish in pages or not (it's enabled by default now, as it was before)- ```python- with DynamicSession(headless=True, disable_resources=False, network_idle=True) as session:- page = session.fetch('https://quotes.toscrape.com/', load_dom=False)- ```- - The Stealth mode is now more reliable in `DynamicFetcher` and its session classes.- - Both `DynamicFetcher` and `StealthyFetcher` are now using fewer resources (Automatically finding and closing the default tab opened by Persistent contexts in Playwright API)- - Fixed a vital logic bug in browser-based fetchers' pages rotation - previous pages are now replaced with fresh ones. (Tabs that get reused in rotation are possibly contaminated from previous settings used on them)- - `StealthyFetcher` and its session classes are now slightly faster (5%)+ - A new option to control whether to wait for JavaScript execution to finish in pages or not (it's enabled by default now, as it was before)++ ```python+ with DynamicSession(headless=True, disable_resources=False, network_idle=True) as session:+ page = session.fetch('https://quotes.toscrape.com/', load_dom=False)+ ```++ - The Stealth mode is now more reliable in `DynamicFetcher` and its session classes.+ - Both `DynamicFetcher` and `StealthyFetcher` are now using fewer resources (Automatically finding and closing the default tab opened by Persistent contexts in Playwright API)+ - Fixed a vital logic bug in browser-based fetchers' pages rotation - previous pages are now replaced with fresh ones. (Tabs that get reused in rotation are possibly contaminated from previous settings used on them)+ - `StealthyFetcher` and its session classes are now slightly faster (5%)- **Enhanced `.body` property**: Now returns the passed content as-is without processing, enabling file downloads and handling non-HTML requests. Below is an example of downloading a photo:+```pythonfrom scrapling.fetchers import Fetcher- page = Fetcher.get('https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/poster.png')- with open(file='poster.png', mode='wb') as f:- f.write(page.body)+ page = Fetcher.get('https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/poster.png')+ with open(file='poster.png', mode='wb') as f:+ f.write(page.body)```-### 🐛 Bug Fixes+### 🐛 Bug Fixes {#v0.3.2-bug-fixes}- **Encoding issues resolved**: Fixed multiple encoding problems that happened with some websites in parser, mcp mode, and extract commands (Also solves #80 and #81)- **Faster parsing**: Due to many changes here and there, the library is now faster, and it's reflected in the updated benchmarks-### 🔨 Misc+### 🔨 Misc {#v0.3.2-misc}- **Updated benchmarks**: Refreshed performance benchmarks to compare the current speed improvements to the latest versions of similar libraries- **Refactored a lot of the code and replaced dead code with better implementations**: Fewer code, cleaner code, easier maintenance@@ -780,46 +813,47 @@ Release Notes for v0.3.2- **Code style improvements**: Applied new ruff rules across all files.- **Pre-commit hooks**: Updated pre-commit configuration.-### 🎯 Breaking Changes+### 🎯 Breaking Changes {#v0.3.2-breaking-changes}- Removed `max_pages` parameter from sync `StealthySession` to match `DynamicSession` (it's meaningless to have in the sync version)-## [v0.3.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.1) - 2025-09-02+## [v0.3.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.1) - 2025-09-02 {#v0.3.1}1. Fixed an issue with scrapling installation when you install it without the `shell` extra (#76 )2. Added a new argument to all browser-based fetchers and their session classes to add a JS file to be executed on page creation (#56) :+```pythonfrom scrapling.fetchers import StealthyFetcherStealthyFetcher.fetch('https://example.com', init_script="/absolute/path/to/js/script.js")```-## [v0.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3) - 2025-09-01+## [v0.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3) - 2025-09-01 {#v0.3}-🎉 **Major Release — Complete Architecture Overhaul**+🎉 **Major Release - Complete Architecture Overhaul**Scrapling v0.3 represents the most significant update in the project's history, featuring a complete architectural rewrite, considerable performance improvements, and powerful new features, including AI integration and interactive Web Scraping shell capabilities.This release includes multiple breaking changes; please review the release notes carefully.-### 🚀 Major New Features+### 🚀 Major New Features {#v0.3-major-new-features}-#### Session-Based Architecture+#### Session-Based Architecture {#v0.3-session-based-architecture}- **New Session Classes**: Complete rewrite introducing persistent session support- - `FetcherSession` - HTTP requests with persistent state management that works with both sync and async code- - `DynamicSession`/`AsyncDynamicSession` - Browser automation while keeping the browser open till you finish- - `StealthySession`/`AsyncStealthySession` - Stealth browsing while keeping the browser open till you finish+ - `FetcherSession` - HTTP requests with persistent state management that works with both sync and async code+ - `DynamicSession`/`AsyncDynamicSession` - Browser automation while keeping the browser open till you finish+ - `StealthySession`/`AsyncStealthySession` - Stealth browsing while keeping the browser open till you finish- **Async Browser Tabs Management**: A new pool of tabs feature through the `max_pages` argument that rotates browser tabs for concurrent browser fetches- **Concurrent Sessions**: Run multiple isolated sessions simultaneouslyRefer to the `Fetching` section on the website for more details.-#### A lot of new stealth/anti-bot Capabilities-- **🤖 Cloudflare Solver**: Automatic [Cloudflare Turnstile challenge solving](https://scrapling.readthedocs.io/en/latest/fetching/stealthy/#cloudflare-protection-bypass) in `StealthyFetcher` and its session classes-- **Browser fingerprint impersonation**: Mimic real browsers' TLS fingerprints, version-matching browser headers, HTTP/3 support, and more with the all-new [Fetcher](https://scrapling.readthedocs.io/en/latest/fetching/static/) class+#### A lot of new stealth/anti-bot Capabilities {#v0.3-a-lot-of-new-stealth-anti-bot-capabilities}+- **🤖 Cloudflare Solver**: Automatic [Cloudflare Turnstile challenge solving](fetching/stealthy.md#cloudflare-and-stealth-options) in `StealthyFetcher` and its session classes+- **Browser fingerprint impersonation**: Mimic real browsers' TLS fingerprints, version-matching browser headers, HTTP/3 support, and more with the all-new [Fetcher](fetching/static.md) class- **Improved stealth mode**: The stealth mode for `DynamicFetcher` and its session classes is now more robust and reliable (AKA `PlayWrightFetcher`)-#### AI Integration & MCP Server+#### AI Integration & MCP Server {#v0.3-ai-integration-mcp-server}- **Built-in MCP Server**: Model Context Protocol server for AI-assisted web scraping- **6 Powerful Tools**: `get`, `bulk_get`, `fetch`, `bulk_fetch`, `stealthy_fetch`, `bulk_stealthy_fetch`- **Smart Content Extraction**: Convert web pages/elements to Markdown, HTML, or extract a clean version of the text content@@ -828,43 +862,43 @@ Refer to the `Fetching` section on the website for more details.- **Proxy Support**: Use proxies for anonymity and geo-targeting- **Browser Impersonation**: Mimic real browsers with TLS fingerprinting, real browser headers matching that version, and more- **Parallel Processing**: Scrape multiple URLs concurrently for efficiency-- [and more...](https://scrapling.readthedocs.io/en/latest/ai/mcp-server/)+- [and more...](ai/mcp-server.md)-#### New Interactive Web Scraping Shell+#### New Interactive Web Scraping Shell {#v0.3-new-interactive-web-scraping-shell}- **A New Shell**: Custom IPython shell with many smart Built-in Shortcuts like `get`, `post`, `put`, `delete`, `fetch`, and `stealthy_fetch`- **Smart Page Management**: New commands `page` and `pages` to automatically store the current page and history for all requests done through the shell-- **Curl Integration**: Convert browser DevTools curl commands with `uncurl` and `curl2fetcher` functions to `Fetcher` requests-- [and more...](https://scrapling.readthedocs.io/en/latest/cli/interactive-shell/)+- **Curl Integration**: Convert browser DevTools curl commands with `uncurl` and `curl2fetcher` functions to `Fetcher` requests+- [and more...](cli/interactive-shell.md)-#### Scrape from the terminal without programming+#### Scrape from the terminal without programming {#v0.3-scrape-from-the-terminal-without-programming}- **New Extract Commands**: Terminal-based scraping without programming- - `scrapling extract get/post/put/delete` - Simple HTTP requests- - `scrapling extract fetch` - Dynamic content scraping- - `scrapling extract stealthy-fetch` - Anti-bot bypass+ - `scrapling extract get/post/put/delete` - Simple HTTP requests+ - `scrapling extract fetch` - Dynamic content scraping+ - `scrapling extract stealthy-fetch` - Anti-bot bypass- **Downloads web pages** and saves their content to files.- **Converts HTML to readable formats** like Markdown, keeps it as HTML, or just extracts the text content of the page.- **Supports custom CSS selectors** to extract specific parts of the page.- **Handles HTTP requests and fetching through browsers.**- **Highly customizable** with custom headers, cookies, proxies, and the rest of the options. Almost all the options available through the code are also accessible through the terminal.-- [and more...](https://scrapling.readthedocs.io/en/latest/cli/extract-commands/)+- [and more...](cli/extract-commands.md)-### 🔧 Technical Improvements+### 🔧 Technical Improvements {#v0.3-technical-improvements}-#### Performance Enhancements+#### Performance Enhancements {#v0.3-performance-enhancements}- **Fetcher is now 4 times faster** - Yes you have read it right!- **DynamicFetcher is now ~60% faster** - A much faster version depending on your config (especially stealth mode)- **StealthyFetcher is now 20–30% faster** - Using the new structure, and starting to use our implementation instead of `Camoufox` Python interface- **50%+ combined speed gains** across core selection methods (`find_by_text`, `find_similar`, `find_by_regex`, `relocate`, etc.) 🚀- **~10% CSS/XPath first methods speed increase** - `css_first` and `xpath_first` are now faster than `css` and `xpath`- **40% faster `get_all_text()` method** for content extraction-- **20% speed improvement** in adaptive element relocation-- **Navigation properties optimization** — Properties like `next`, `previous`, `below_elements`, and more are now noticeably faster+- **20% speed improvement** in adaptive element relocation+- **Navigation properties optimization** - Properties like `next`, `previous`, `below_elements`, and more are now noticeably faster- **5x faster text cleaning** operations- **Memory efficiency improvements** with optimized imports and reduced overhead- **⚡ Lightning-fast imports**: Reduced startup time with optimized module loading-- **Better benchmarks**: All the speed improvements Scrapling got made it much faster than before, compared to other libraries (1775x faster than BeautifulSoup and 5.1x faster than AutoScraper, check [benchmarks](https://scrapling.readthedocs.io/en/latest/benchmarks/))+- **Better benchmarks**: All the speed improvements Scrapling got made it much faster than before, compared to other libraries (1775x faster than BeautifulSoup and 5.1x faster than AutoScraper, check [benchmarks](benchmarks.md))-#### Architecture/Code Quality, and Quality of life+#### Architecture/Code Quality, and Quality of life {#v0.3-architecture-code-quality-and-quality-of-life}- **Persistent Context**: All browser-based fetchers now use persistent context by default. (Solves #64 too)- **Using msgspec to validate all browser-based fetchers very fast** before running the requests, so now it's easier to debug errors.- **All cookies** returned from fetchers are now matching the format accepted by the same fetcher. So you can retrieve cookies and pass them again to all fetchers and their session classes.@@ -875,12 +909,12 @@ Refer to the `Fetching` section on the website for more details.- **Cleaner Codebase**: Removed dead code and optimized core functions 🧹- **🚀 Backward Compatibility**: Added shortcuts to maintain compatibility with older code-### Breaking Changes+### Breaking Changes {#v0.3-breaking-changes}-#### Minimum Python Version+#### Minimum Python Version {#v0.3-minimum-python-version}- **Python 3.10+ Required**: Dropped support for Python 3.9 and below-#### Class and Method Naming+#### Class and Method Naming {#v0.3-class-and-method-naming}These renamings are intended to improve clarity and consistency, particularly for new users.- **`Adaptor` → `Selector`**: Core parsing class renamed (But still can be imported as `Adaptor` for backward compatibility)@@ -892,9 +926,9 @@ These renamings are intended to improve clarity and consistency, particularly fo- **⚠️ `text/body` → `content`**: Selector constructor parameter is now accepting both `str` and `bytes` format- **`PlayWrightFetcher` → `DynamicFetcher`**: Browser automation class renamed (But still can be imported as `PlayWrightFetcher` for backward compatibility)- **DynamicFetcher doesn't have the NSTBrowser logic/arguments anymore** since it's pointless to leave this logic now anyway.-- **StealthyFetcher's headless argument can't accept 'virtual' as an argument anymore** since we are not using Camoufox's library right now in anything other than getting the browser installation path and the rest of the launch options+- **StealthyFetcher's headless argument can't accept 'virtual' as an argument anymore** since we are not using Camoufox's library right now in anything other than getting the browser installation path and the rest of the launch options-### 🐛 Bug Fixes+### 🐛 Bug Fixes {#v0.3-bug-fixes}- Fixed nested children counting in ignored tags for `get_all_text` (#61)- Fixed the issue with installation due to spaces in Python's executable path (#57)@@ -904,32 +938,32 @@ These renamings are intended to improve clarity and consistency, particularly fo- Fixed `referer` and `google_search` argument conflicts- Fixed async stealth script injection problems-## [v0.2.99](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.99) - 2025-04-08+## [v0.2.99](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.99) - 2025-04-08 {#v0.2.99}**This is an essential update for everyone to fully enjoy Scrapling as it's intended.**-### What's changed-#### New full documentation website-- Yup, finally 😄 Check it out from [here](https://scrapling.readthedocs.io/en/latest/)-#### Unified import logic for fetchers+### What's changed {#v0.2.99-what-s-changed}+#### New full documentation website {#v0.2.99-new-full-documentation-website}+- Yup, finally 😄 Check it out from [here](index.md)+#### Unified import logic for fetchers {#v0.2.99-unified-import-logic-for-fetchers}- Now you can import all fetchers with `from scrapling.fetchers import Fetcher, AsyncFetcher, StealthyFetcher, PlayWrightFetcher`, then use them directly like `page = Fetcher.get(...)` without initialization.<br/> This replaces this old import `from scrapling.defaults import Fetcher, AsyncFetcher, StealthyFetcher, PlayWrightFetcher`.-#### Breaking change: automatch is now turned off by default-- Now there's new logic to enable automatch from fetchers or other parsing options. Check out the [documentation page](https://scrapling.readthedocs.io/en/latest/fetching/choosing/#parser-configuration-in-all-fetchers) for details.+#### Breaking change: automatch is now turned off by default {#v0.2.99-breaking-change-automatch-is-now-turned-off-by-default}+- Now there's new logic to enable automatch from fetchers or other parsing options. Check out the [documentation page](fetching/choosing.md#parser-configuration-in-all-fetchers) for details.> Old imports and logic are left usable with a warning for backward compatibility.-#### New options added to fetchers+#### New options added to fetchers {#v0.2.99-new-options-added-to-fetchers}- Now, both `StealthyFetcher` and `PlayWrightFetcher` have a new argument while fetching called `wait`. This makes the fetcher wait/sleep for a specific period (milliseconds) before closing the page and returning the response to you.- Now `StealthyFetcher` methods `fetch` and `async_fetch` have the argument `additional_arguments` to be passed to Camoufox as additional settings, which takes higher priority than Scrapling's settings (#54 )-#### Bugs squashed+#### Bugs squashed {#v0.2.99-bugs-squashed}- Fixed a bug in `async_fetch` in both `StealthyFetcher` and `PlayWrightFetcher` classes, with catching redirections.**_Thanks for all your support and donations!_**-## [v0.2.98](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.98) - 2025-03-17+## [v0.2.98](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.98) - 2025-03-17 {#v0.2.98}**This is an essential update for everyone to enjoy Scrapling as it's intended fully**-### What's changed-#### Various memory usage and speed optimizations+### What's changed {#v0.2.98-what-s-changed}+#### Various memory usage and speed optimizations {#v0.2.98-various-memory-usage-and-speed-optimizations}- All selection methods' memory usage is ~40% of previous memory usage and the speed slightly increased.- Implemented Lazy loading for all submodules of the library so now what you use is what you load, for example:Before the update this import `from scrapling import Adaptor` was using `30-40mb` of RAM because it loaded all fetchers and stuff with it too, now it uses `~1.2mb`.@@ -938,55 +972,55 @@ Before the update this import `from scrapling import Adaptor` was using `30-40mb**_Thanks for all your support and donations!_**-## [v0.2.97](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.97) - 2025-03-15+## [v0.2.97](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.97) - 2025-03-15 {#v0.2.97}**This is an essential update for everyone to fully enjoy Scrapling as it's intended**-### What's changed-#### Lower memory usage and small speed increase across all Fetchers.+### What's changed {#v0.2.97-what-s-changed}+#### Lower memory usage and small speed increase across all Fetchers. {#v0.2.97-lower-memory-usage-and-small-speed-increase-across-all-fetchers}- With new limitations across the library over caching size you will notice significantly lower memory usage than before while doing large numbers of requests/operations.- Refactored big parts of the fetchers to easier maintainability and small speed increase.-#### Bugs fixed+#### Bugs fixed {#v0.2.97-bugs-fixed}- Fixed a bug in `TextHandler` where importing it alone and passing a non-string value converts it to an empty string. Now anything passed to `TextHandler` is automatically converted to a string before being converted to `TextHandler`, this is forced on any value passed -- `TextHandler` as the name implies is intended to work with strings only after all! (#45 )- Fixed a bug where the `retries` arguments weren't taken into account in most AsyncFetcher methods.-#### Miscellaneous+#### Miscellaneous {#v0.2.97-miscellaneous}- Update type hints for most arguments in all fetchers to be clearer and more accurate.**_Thanks for all your support and donations!_**-## [v0.2.96](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.96) - 2025-03-05+## [v0.2.96](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.96) - 2025-03-05 {#v0.2.96}**This is an essential update for everyone to fully enjoy Scrapling as it's intended**-### What's changed+### What's changed {#v0.2.96-what-s-changed}1. Added the `-f` option to `scrapling install` to force reinstall browser dependencies. I recommend you do `scrapling install -f` now to enjoy the big speed performance `StealthyFetcher` just got with the new Camoufox browser version :)2. Fixed a bug in `TextHandler` where slicing returned `TextHandlers` instead of `TextHandler` and fixed the type hint there (#41 )3. Fixed an issue where `scrapling install` might in some instances drop the user into a Python shell!-## [v0.2.95](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.95) - 2025-02-25+## [v0.2.95](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.95) - 2025-02-25 {#v0.2.95}**This is an essential update for everyone to fully enjoy Scrapling as it's intended**-### What's changed+### What's changed {#v0.2.95-what-s-changed}1. Fixed a bug in `Fetcher` that made headers generated by the `stealthy_headers` argument overwrite some of the headers provided by the user like `Accept` (#39 )2. Improved the headers generation logic a bit so it should give a slight speed boost.-## [v0.2.94](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.94) - 2025-02-22+## [v0.2.94](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.94) - 2025-02-22 {#v0.2.94}**This is an essential update for everyone to fully enjoy Scrapling as it's intended**-### What's changed+### What's changed {#v0.2.94-what-s-changed}1. Added the `history` property to all fetchers to show redirections (#32 )2. Fixed the logic of the `case_sensitive` argument logic for all `re`/`re_first`. This may make your code return different results if you were using it (but you probably deserve it because you noticed it wasn't working as intended and didn't open an issue LOL)3. Updated dependencies and enabled `coop` back again in the Camoufox engine (StealthyFetcher).-## [v0.2.93](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.93) - 2025-01-31+## [v0.2.93](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.93) - 2025-01-31 {#v0.2.93}**This is an essential update for everyone to fully enjoy Scrapling as it's intended**-### What's changed+### What's changed {#v0.2.93-what-s-changed}1. The return type is now consistent across all the parser engine so you will always get a return type as one of these `Adaptor`, `Adaptors`, `TextHandler`, `TextHandlers`, `None`, and a list in case you have mixed results like combined CSS selector. This allows a better coding experience with minimum manual type checking, makes the library more stable, and makes chaining methods always possible.2. Most of the parser engine especially the `Adaptor` class got refactored to a cleaner version and most importantly a faster version. So now almost all the methods/properties, especially the searching methods, got a speed increase between 5-40%. Some methods got bigger speed boosts like `find_by_regex` got a ~60% speed boost! The automatch feature got a small ~5% speed boost.3. Fixed logic bugs with the `find_all`/`find` methods that made the passed filters used in OR fashion and other times as an AND. So now all elements returned need to fulfill all filters you pass.@@ -996,37 +1030,39 @@ Before the update this import `from scrapling import Adaptor` was using `30-40mb7. StealthyFetcher is now a bit faster and more stealthy. Also, now it's possible to click Captchas in iframes like **Cloudflare Turnstile**.8. The auto-completion and type hints improved a lot in nearly half the library. Especially `Adaptor`, `TextHandler`, and `TextHandlers`.9. Now slicing `TextHandler`, accessing by index, or using the `split` method returns another `TextHandler` instead of the standard Python string. Now almost all standard string operations/methods return other `Texthandler` instead of standard string to make chaining methods/functions always possible.-10. Fixed some small bugs and typos. For example, the Fetcher async_put was doing post request instead of put request 😶🌫️+10. Fixed some small bugs and typos. For example, the Fetcher async_put was doing post request instead of put request 😶🌫️11. Improved the README a bit till I finish the documentation website.This was supposed to be a small update till version 0.3 but thought to make it better.-## [v0.2.92](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.92) - 2024-12-26+## [v0.2.92](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.92) - 2024-12-26 {#v0.2.92}-### What's changed+### What's changed {#v0.2.92-what-s-changed}- Now response returned by browser-based fetchers uses more reliable data sources in cases where the page loaded uses many Iframes.- **Now installing `Scrapling` is made even easier, you install it with pip then run `scrapling install` in the terminal and you are ready!**- Fixed an inaccurate type hint in the parser.-## [v0.2.91](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.91) - 2024-12-19+## [v0.2.91](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.91) - 2024-12-19 {#v0.2.91}-### What's changed+### What's changed {#v0.2.91-what-s-changed}- Fixed a bug where the logging fetch logging sentence was showing in the first request only.- The default behavior for Playwright API while browsing a page is returning the first response that fulfills the load state given to the `goto` method `["load", "domcontentloaded", "networkidle"]` so if a website has a wait page like Cloudflare's one that redirects you to the real website afterward, Playwright will return the first status code which in this case would be something like 403. This update solves this issue for both `PlaywrightFetcher` and `StealthyFetcher` as both are using Playwright API so the result depends on Playwright's default behavior no more.- Added support for proxies that use SOCKS proxies in the `Fetcher` class.- Fixed the type hint for the `wait_selector_state` argument so now it will show the accurate values you should use while auto-completing.-## [v0.2.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.9) - 2024-12-16+## [v0.2.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.9) - 2024-12-16 {#v0.2.9}-### What's changed-##### New features+### What's changed {#v0.2.9-what-s-changed}+##### New features {#v0.2.9-new-features}1. Introducing the **long-awaited** async support for Scrapling! Now you have the `AsyncFetcher` class version of `Fetcher`, and both `StealthyFetcher` and `PlayWrightFetcher` have a new method called `async_fetch` with the same options.+```python>> from scrapling import StealthyFetcher>> page = await StealthyFetcher().async_fetch('https://www.browserscan.net/bot-detection') # the async version of fetch>> page.status == 200True```+2. Now the `StealthyFetcher` class has the `geoip` argument in its fetch methods which when enabled makes the class automatically use IP's longitude, latitude, timezone, country, and locale, then spoof the WebRTC IP address. It will also calculate and spoof the browser's language based on the distribution of language speakers in the target region.3. Added the `retries` argument to `Fetcher`/`AsyncFetcher` classes so now you can set the number of retries of each request done by `httpx`.4. Added the `url_join` method to `Adaptor` and Fetchers which takes a relative URL and joins it with the current URL to generate an absolute full URL!@@ -1039,14 +1075,15 @@ Example:>> from scrapling.defaults import Fetcher>> Fetcher.get('https://books.toscrape.com/index.html')[2024-12-16 13:33:36] INFO: Fetched (200) <GET https://books.toscrape.com/index.html> (referer: https://www.google.com/search?q=toscrape)- >>+ >>```+8. Now using all standard string methods on a `TextHandler` like `.replace()` will result in another `TextHandler`. It was returning the standard string before.9. Big improvements to speed across the library and improvements to stealth in Fetchers classes overall.10. Added dummy functions like `extract_first`\`extract` which returns the same result as the parent. These functions are added only to make it easy to copy code from Scrapy/Parsel to Scrapling when needed as these functions are used there!11. Due to refactoring a lot of the code and using caching at the right positions, now doing requests in bulk will have a big speed increase.-##### Breaking changes+##### Breaking changes {#v0.2.9-breaking-changes}- Now the support for Python 3.8 has been dropped. (Mainly because Playwright stopped supporting it but it was a problematic version anyway)- The `debug` argument has been removed from all the library, now if you want to set the library to debugging, do this after importing the library:@@ -1055,103 +1092,109 @@ Example:>>> logging.getLogger("scrapling").setLevel(logging.DEBUG)```-##### Bugs Squashed+##### Bugs Squashed {#v0.2.9-bugs-squashed}1. Now WebGL is enabled by default as a lot of protections are checking if it's enabled now.2. Some mistakes and typos in the docs/README.-##### Quality of life changes+##### Quality of life changes {#v0.2.9-quality-of-life-changes}1. All logging is now unified under the logger name `scrapling` for easier and cleaner control. We were using the root logger before.2. Restructured the tests folder into a cleaner structure and added tests for the new features. All the tests were rewritten to a cleaner version and more tests were added for higher coverage.3. Refactored a big part of the code to be cleaner and easier to maintain.> All these changes were part of the changes I decided before to add with 0.3 but decided to add them here because it will be some time till the next version. Now the next step is to finish the detailed documentation website and then work on version 0.3-## [v0.2.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.8) - 2024-11-30+## [v0.2.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.8) - 2024-11-30 {#v0.2.8}-### What's changed+### What's changed {#v0.2.8-what-s-changed}- This is a small update that includes some must-have quality-of-life changes to the code and fixed a typo in the main README file (#20)-## [v0.2.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.7) - 2024-11-26+## [v0.2.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.7) - 2024-11-26 {#v0.2.7}-### What's changed-##### New features+### What's changed {#v0.2.7-what-s-changed}+##### New features {#v0.2.7-new-features}- Now if you used the `wait_selector` argument with `StealthyFetcher` and `PlayWrightFetcher` classes, Scrapling will wait again for the JS to fully load and execute like normal. If you used the `network_idle` argument, Scrapling will wait for it again too after waiting for all of that. If the states are all fulfilled then no waiting happens, of course.- Now you can enable and disable ads on `StealthyFetcher` with the `disable_ads` argument. This is enabled by default and it installs the `ublock origin` addon.- Now you can set the locale used by `PlayWrightFetcher` with the `locale` argument. The default value is still `en-US`.- Now the basic requests done through `Fetcher` can accept proxies in this format `http://username:password@localhost:8030`.- The stealth mode improved a bit for `PlayWrightFetcher`.-##### Bugs Squashed/Improvements+##### Bugs Squashed/Improvements {#v0.2.7-bugs-squashed-improvements}1. Now enabling proxies on the `PlayWrightFetcher` class is not tied to the `stealth` mode being on or off (Thanks to [@AbdullahY36](https://github.com/AbdullahY36) for pointing that out)2. Now the `ResponseEncoding` tests if the encoding returned from the response can be used with the page or not. If the returned encoding triggered an error, Scrapling defaults to `utf-8`-## [v0.2.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.6) - 2024-11-24+## [v0.2.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.6) - 2024-11-24 {#v0.2.6}-### What's changed-##### New features+### What's changed {#v0.2.6-what-s-changed}+##### New features {#v0.2.6-new-features}- Now the `PlayWrightFetcher` can use the real browser directly with the `real_chrome` argument passed to the `PlayWrightFetcher.fetch` function but this requires you to have Chrome browser installed. Scrapling will launch an instance of your Chrome browser and you can use most of the options as normal. (Before you only had the `cdp_url` argument to do so)- Pumped up the version of headers generated for real browsers.-##### Bugs Squashed+##### Bugs Squashed {#v0.2.6-bugs-squashed}1. Turns out the format of the browser headers generated by `BrowserForge` was outdated which made Scrapling detected by some protections so now `BrowserForge` is only used to generate real useragent.2. Now the `hide_canvas` argument is turned off by default as it's being detected by Google's ReCaptcha.-## [v0.2.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.5) - 2024-11-23+## [v0.2.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.5) - 2024-11-23 {#v0.2.5}-### What's changed+### What's changed {#v0.2.5-what-s-changed}-##### Bugs Squashed+##### Bugs Squashed {#v0.2.5-bugs-squashed}- Handled an error that happens with the 'wait_selector' argument if it resolved to more than 1 element. This affects the `StealthyFetcher` and the `PlayWrightFetcher` classes.- Fixed the encoding type in cases where the `content_type` header gets value with parameters like `charset` (Thanks to @andyfcx for [#12](https://github.com/D4Vinci/Scrapling/issues/12) )-##### Quality of life+##### Quality of life {#v0.2.5-quality-of-life}- Added more tests to cover new parts of the code and made tests run in threads.- I updated the docs strings to be readable correctly on Sphinx's apidoc or similar tools.-##### New Contributors+##### New Contributors {#v0.2.5-new-contributors}- @andyfcx made their first contribution at [#13 ](https://github.com/D4Vinci/Scrapling/pull/13)-## [v0.2.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.4) - 2024-11-20+## [v0.2.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.4) - 2024-11-20 {#v0.2.4}-### What's changed+### What's changed {#v0.2.4-what-s-changed}-##### Bugs Squashed+##### Bugs Squashed {#v0.2.4-bugs-squashed}- Fixed a bug when retrieving response bytes after using the `network_idle` argument in both the `StealthyFetcher` and `PlayWrightFetcher` classes. <br/> That was causing the following error message:- ```-Response.body: Protocol error (Network.getResponseBody): No resource with given identifier found-```++ ```+ Response.body: Protocol error (Network.getResponseBody): No resource with given identifier found+ ```+- The PlayWright API sometimes returns empty status text with responses, so now `Scrapling` will calculate it manually if that happens. This affects both the `StealthyFetcher` and `PlayWrightFetcher` classes.-## [v0.2.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.3) - 2024-11-19+## [v0.2.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.3) - 2024-11-19 {#v0.2.3}-### What's changed+### What's changed {#v0.2.3-what-s-changed}-##### Bugs Squashed+##### Bugs Squashed {#v0.2.3-bugs-squashed}- Fixed a bug with pip installation that prevented the stealth mode on PlayWright Fetcher from working entirely.-## [v0.2.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.2) - 2024-11-16+## [v0.2.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.2) - 2024-11-16 {#v0.2.2}-### What's changed-##### New features+### What's changed {#v0.2.2-what-s-changed}+##### New features {#v0.2.2-new-features}- Now if you don't want to pass arguments to the generated `Adaptor` object and want to use the default values, you can use this import instead for cleaner code+```python>> from scrapling.default import Fetcher, StealthyFetcher, PlayWrightFetcher>> page = Fetcher.get('https://example.com', stealthy_headers=True)```- Otherwise++ Otherwise+```python>> from scrapling import Fetcher, StealthyFetcher, PlayWrightFetcher>> page = Fetcher(auto_match=False).get('https://example.com', stealthy_headers=True)```-##### Bugs Squashed+##### Bugs Squashed {#v0.2.2-bugs-squashed}1. Fixed a bug with the `Response` object introduced with patch v0.2.1 yesterday that happened with some cases of nested selecting/parsing.-## [v0.2.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.1) - 2024-11-15+## [v0.2.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.1) - 2024-11-15 {#v0.2.1}-### What's changed-##### New features+### What's changed {#v0.2.1-what-s-changed}+##### New features {#v0.2.1-new-features}1. Now the `Response` object returned from all fetchers is the same as the `Adaptor` object except it has these added attributes: `status`, `reason`, `cookies`, `headers`, and `request_headers`. All `cookies`, `headers`, and `request_headers` are always of type `dictionary`. <br/>So your code can now become like:+```python>> from scrapling import Fetcher>> page = Fetcher().get('https://example.com', stealthy_headers=True)@@ -1159,7 +1202,9 @@ Response.body: Protocol error (Network.getResponseBody): No resource with given200>> products = page.css('.product')```- Instead of before++ Instead of before+```python>> from scrapling import Fetcher>> fetcher = Fetcher().get('https://example.com', stealthy_headers=True)@@ -1168,62 +1213,67 @@ Response.body: Protocol error (Network.getResponseBody): No resource with given>> page = fetcher.adaptor>> products = page.css('.product')```- But I have left the `.adaptor` property working for backward compatibility.++ But I have left the `.adaptor` property working for backward compatibility.+2. Now both the `StealthyFetcher` and `PlayWrightFetcher` classes can take a `proxy` argument with the fetch method which accepts a string or a dictionary.3. Now the `StealthyFetcher` class has the `os_randomize` argument with the `fetch` method. If enabled, Scrapling will randomize the OS fingerprints used. The default is Scrapling matching the fingerprints with the current OS.-##### Bugs Squashed+##### Bugs Squashed {#v0.2.1-bugs-squashed}1. Fixed a bug that happens while passing headers with the `Fetcher` class.2. Fixed a bug with parsing JSON responses passed from the fetcher-type classes.-##### Quality of life changes+##### Quality of life changes {#v0.2.1-quality-of-life-changes}1. The text functionality behavior was to try to remove HTML comments before returning the text but that induced errors in some cases and made the code more complicated than needed. Now it has reverted to the default lxml behavior, **you will notice a slight speed increase to all operations that counts on elements' text like selectors**. Now if you want Scrapling to remove HTML comments from elements before returning the text to avoid the weird text-splitting behavior that's in lxml/parsel/scrapy, just keep the `keep_comments` argument set to True as it is by default.-## [v0.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2) - 2024-11-11+## [v0.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2) - 2024-11-11 {#v0.2}-### What's changed-##### New features+### What's changed {#v0.2-what-s-changed}+##### New features {#v0.2-new-features}1. Introducing the `Fetchers` feature with 3 new main types to make Scrapling fetch pages for you with a LOT of options!- - The `Fetcher` class for basic HTTP requests- - The `StealthyFetcher` class is a completely stealthy fetcher that uses a [stealthy modified version of Firefox](https://github.com/daijro/camoufox).- - The `PlayWrightFetcher` class that allows doing browser-based requests with Vanilla PlayWright, PlayWright with stealth mode made by me, Real browsers through CDP, and [NSTBrowser](https://app.nstbrowser.io/r/1vO5e5)'s [docker browserless](https://hub.docker.com/r/nstbrowser/browserless)!+ - The `Fetcher` class for basic HTTP requests+ - The `StealthyFetcher` class is a completely stealthy fetcher that uses a [stealthy modified version of Firefox](https://github.com/daijro/camoufox).+ - The `PlayWrightFetcher` class that allows doing browser-based requests with Vanilla PlayWright, PlayWright with stealth mode made by me, Real browsers through CDP, and [NSTBrowser](https://app.nstbrowser.io/r/1vO5e5)'s [docker browserless](https://hub.docker.com/r/nstbrowser/browserless)!2. Added the completely new `find_all`/`find` methods to find elements easily on the page with dark magic!3. Added the methods `filter` and `search` to the `Adaptors` class for easier bulk operations on `Adaptor` object groups.4. Added methods `css_first` and `xpath_first` methods for easier usage.5. Added the new class type `TextHandlers` which is used for bulk operations on `TextHandler` objects like the `Adaptors` class.6. Added `generate_full_css_selector` and `generate_full_xpath_selector` methods.-##### Bugs Squashed+##### Bugs Squashed {#v0.2-bugs-squashed}1. Now the `Adaptors` class version of `re_first` returns the first result that matches in all `Adaptor` objects inside instead of the faulty logic of returning the results of `re_first` of all `Adaptor` objects.2. Now if the user selects a text-type content to be returned from selected elements (like css `::text` function) with any method like `.css` or `.xpath`. The `Adaptor` object will return the `TextHandlers` class instead of returning a list of strings like before. So now you can do `page.css('something::text').re_first(r'regex_pattern').json()` instead of `page.css('something::text')[0].re_first(r'regex_pattern').json()`-3. Now `Adaptor`/`Adaptors` re/re_first arguments are consistent with the `TextHandler` ones. So now you have `clean_match` and `case_sensitive` arguments.+3. Now `Adaptor`/`Adaptors` re/re_first arguments are consistent with the `TextHandler` ones. So now you have `clean_match` and `case_sensitive` arguments.4. Now the `auto_match` argument is enabled by default in the initialization of `Adaptor` but still you have to enable it while selecting elements if you want to enable it. (Not a bug but a design decision)5. A lot of type-annotations corrections here and there for better auto-completion experience while you are coding with Scrapling.-##### Quality of life changes+##### Quality of life changes {#v0.2-quality-of-life-changes}1. Renamed both `css_selector` and `xpath_selector` methods to `generate_css_selector` and `generate_xpath_selector` for clarity and to not interrupt the auto-completion while coding.2. Restructured most of the old code into a `core` subpackage and other design decisions for cleaner and easier maintenance in the future.3. Restructured the tests folder into a cleaner structure and added tests for the new features. Also now tox environments are cached on GitHub for faster automated tests with each commit.-## [v0.1.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.2) - 2024-10-16+## [v0.1.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.2) - 2024-10-16 {#v0.1.2}**Changelog**:+- Fixed a bug where the `keep_comments` argument is not working as intended.- Adjusted the text function to automatically remove HTML comments from elements before extracting its text to prevent Lxml different behavior, for example:- ```python- >>> page = Adaptor('<span>CONDITION: <!-- -->Excellent</span>', keep_comments=True)- >>> page.css('span::text')- ['CONDITION: ', 'Excellent']- ```- previously would result in this because of Lxml default behavior but now it would return the full text 'CONDITION: Excellent'- This behavior is known with parsel\scrapy as well so wanted to handle it here.++ ```python+ >>> page = Adaptor('<span>CONDITION: <!-- -->Excellent</span>', keep_comments=True)+ >>> page.css('span::text')+ ['CONDITION: ', 'Excellent']+ ```++ previously would result in this because of Lxml default behavior but now it would return the full text 'CONDITION: Excellent'+ This behavior is known with parsel\scrapy as well so wanted to handle it here.+- Fixed a bug where the SQLite db file created by the library is not deleted when doing `pip uninstall scrapling` or similar.-## [v0.1.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.1) - 2024-10-14+## [v0.1.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.1) - 2024-10-14 {#v0.1.1}Minor fixes-## [v0.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1) - 2024-10-13--**Full Changelog**: https://github.com/D4Vinci/Scrapling/commits/v0.1+## [v0.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1) - 2024-10-13 {#v0.1}+**Full Changelog**: <https://github.com/D4Vinci/Scrapling/commits/v0.1>diff --git a/docs/locales/ar/changelog.md b/docs/locales/ar/changelog.mdnew file mode 100644index 0000000..15e0ade--- /dev/null+++ b/docs/locales/ar/changelog.md@@ -0,0 +1,1279 @@+---+title: "سجل تغييرات Scrapling"+description: "ملاحظات إصدارات Scrapling، بما فيها الميزات الجديدة والإصلاحات والتغييرات التي قد تؤثر في الكود الحالي."+---++# سجل التغييرات {#changelog}++كل التغييرات المهمة في Scrapling، نقلًا عن [إصدارات GitHub](https://github.com/D4Vinci/Scrapling/releases).++## [v0.4.15](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.15) - 2026-08-23 {#v0.4.15}++**أحد أكبر إصدارات هذا العام: إعادة تصميم خادم MCP، وتحويل الصفحات إلى Markdown جاهز لـ RAG بسطر واحد، وتحسين حل تحديات Cloudflare، وإبقاء تبويبات المتصفح مفتوحة للأتمتة 🚀**++!!! warning "تنبيه"++ **يتضمن هذا الإصدار تغييرات في خادم MCP قد تؤثر في الكود الحالي. راجع قسم [هذه التغييرات](https://github.com/D4Vinci/Scrapling/blob/v0.4.15/docs/ai/mcp-server.md#breaking-changes) قبل التحديث.**++### 🚀 الجديد وتحسينات الاستخدام {#v0.4.15-new-stuff-and-quality-of-life-changes}++- **تبقى تبويبات المتصفح مفتوحة الآن وتُستخدم مجددًا في الطلبات التالية** (راجع [التوثيق](fetching/stealthy.md#session-management)):+ - تحتفظ كل جلسات المتصفح بتبويباتها بعد الطلب، ويستخدم الطلب التالي تبويبًا متاحًا بدلًا من فتح تبويب جديد.+ - يعيد كل طلب تطبيق إعداداته الخاصة، مثل المهل الزمنية والترويسات وحظر الموارد، على التبويب الذي يستخدمه. لذلك لا تنتقل إعدادات طلب إلى آخر.+ - تُغلق التبويبات التي يحدث فيها خطأ وتُستبدل، وتغلق الدالة الجديدة `close_pages()` كل التبويبات المفتوحة.+ - تبقى الصفحة التي جلبتها محمّلة، فتعمل دالة `page_setup` للطلب التالي عليها قبل الانتقال إلى صفحة أخرى. يتيح ذلك ربط خطوات الأتمتة عبر عدة طلبات.++- **حوّل أي صفحة إلى Markdown نظيف وجاهز لنماذج اللغة الكبيرة باستخدام `Response.markdown()`** (راجع [التوثيق](ai/building-rag-systems.md)):++ ```python+ from scrapling.fetchers import Fetcher++ markdown = Fetcher.get("https://example.com").markdown(main_content_only=True)+ ```++ - تُزال دائمًا السكربتات والأنماط والمحتوى المخفي الذي قد يُستخدم في هجمات Prompt Injection أولًا، بنفس طريقة التنظيف التي يستخدمها خادم MCP.+ - مرّر `css_selector` لتحويل العناصر التي تحتاجها فقط.+ - تتوفر هذه الميزة عبر الإضافة الاختيارية الجديدة `rag` (`pip install "scrapling[rag]"`)، وتشملها أيضًا إضافات `ai`/`shell`/`all`.++- **قالب `SiteToMarkdownSpider` جديد للزحف إلى موقع كامل وتحويله إلى مجموعة ملفات Markdown لأنظمة RAG** (راجع [التوثيق](ai/building-rag-systems.md)):++ ```python+ from scrapling.spiders import SiteToMarkdownSpider++ class DocsSpider(SiteToMarkdownSpider):+ name = "docs"+ start_urls = ["https://example.com/docs/"]+ allowed_domains = {"example.com"}+ output_dir = "docs_markdown"++ result = DocsSpider().start()+ result.items.to_jsonl("docs.jsonl")+ ```++ - يُنتج عنصرًا واحدًا لكل صفحة يحتوي على `url`/`title`/`markdown`، ويتيح الخيار الاختياري `output_dir` كتابة ملف Markdown لكل صفحة.+ - يحدد `max_pages` أقصى عدد صفحات للزحف. ولأن القالب مبني على `CrawlSpider`، فإن إعادة تعريف `rules()` تمنحك تحكمًا كاملًا في الروابط التي يتبعها.++- **إعادة تصميم خادم MCP (تغييرات قد تؤثر في الكود الحالي)** (راجع [هذه التغييرات](https://github.com/D4Vinci/Scrapling/blob/v0.4.15/docs/ai/mcp-server.md#breaking-changes) و[التوثيق](ai/mcp-server.md)):+ - تنقسم الأدوات الـ 13 الآن إلى وضعين: أدوات تعمل مرة واحدة (`fetch`، `bulk_fetch`، `stealthy_fetch`، `bulk_stealthy_fetch`) وتفتح دائمًا متصفحًا خاصًا بها وتعرض إعداداتها الافتراضية الفعلية، وأدوات تستخدم جلسة تُفتح مرة واحدة.+ - تجلب الأداة الجديدة `session_fetch` الصفحات عبر جلسة متصفح، بينما أصبح `open_session` يحتفظ بإعدادات المتصفح فقط ويعيد الإعدادات الفعلية للجلسة إلى وكيل الذكاء الاصطناعي.+ - تغيّر اسم الأداة `get` إلى `make_request`، وهي تدعم الآن أي طريقة HTTP.+ - تمنح الأداتان الجديدتان `open_request_session` و`session_make_request` الذكاء الاصطناعي جلسات HTTP مستمرة تحتفظ بملفات cookies وبصمة المتصفح بين الطلبات.+ - ينهي هذا أيضًا مشكلة إعادة ضبط إعدادات الجلسة عند جلب الصفحات، والتي أصلحها @Yigtwxx أولًا في [#418](https://github.com/D4Vinci/Scrapling/pull/418).++- **يتطلب اتصال HTTP بخادم MCP التحقق من الهوية الآن، ويستمع على localhost افتراضيًا (تغييرات قد تؤثر في الكود الحالي)**، بمساهمة @yamantaka-singh في [#414](https://github.com/D4Vinci/Scrapling/pull/414) (يصلح [#413](https://github.com/D4Vinci/Scrapling/issues/413)، راجع [التوثيق](ai/mcp-server.md#authentication)):+ - مرّر `--auth-token` (أو متغير البيئة `SCRAPLING_MCP_AUTH_TOKEN`) لطلب رمز bearer، أو `--no-auth` إذا أردت تشغيله دون التحقق من الهوية.+ - مرّر `--host 0.0.0.0` لقبول الاتصالات من الشبكة.++### 🐛 إصلاحات الأخطاء {#v0.4.15-bug-fixes}++- **أصبح حل تحديات Cloudflare Turnstile/Interstitial يعمل بصرف النظر عن لغة المتصفح ومنطقته، ولم يعد يكرر المحاولة بلا نهاية مع التحديات التفاعلية في وضع headless**. كما لم تعد صفحات المتصفح الخفي تتعطل أثناء الحل، بمساهمات من @subediparas5 في [#412](https://github.com/D4Vinci/Scrapling/pull/412). (يصلح [#411](https://github.com/D4Vinci/Scrapling/issues/411) و[#422](https://github.com/D4Vinci/Scrapling/issues/422))+- **إصلاح تجاهل `find`/`find_all` للعناصر ذات الأصناف المتعددة عند استخدام `class_` دون تنبيه**، بمساهمة @yetval في [#410](https://github.com/D4Vinci/Scrapling/pull/410)، **وإصلاح قيم `class_` الفارغة والقيم النصية في CSS التي لم تُعالج محارفها الخاصة**، بمساهمة @yamantaka-singh في [#417](https://github.com/D4Vinci/Scrapling/pull/417).+- **إصلاح فقدان بيانات الطلب الإضافية عند إعادة استخدام الردود المخزنة مؤقتًا في `development_mode`**، بمساهمة @Yigtwxx في [#419](https://github.com/D4Vinci/Scrapling/pull/419).+- **إصلاح فشل طلبات HTTP دون إرسالها عندما تكون قيمة `retries` أقل من 1**، بمساهمة @Yigtwxx في [#420](https://github.com/D4Vinci/Scrapling/pull/420).++### التوثيق {#v0.4.15-docs}++- **إعادة تنظيم أقسام الموقع**: يضم قسم "الاستخدام مع الذكاء الاصطناعي" الجديد خادم MCP، وصفحة [مهارة الوكيل](ai/agent-skill.md) الجديدة، ودليل [بناء أنظمة RAG](ai/building-rag-systems.md). وانتقل دليل الانتقال من BeautifulSoup إلى جانب التكامل مع Scrapy ضمن قسم "التكامل والانتقال من مكتبات أخرى".+- **إضافة [سجل تغييرات](changelog.md)** إلى المستودع يضم ملاحظات كل الإصدارات حتى الآن.++## [v0.4.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.14) - 2026-08-10 {#v0.4.14}++**إصدار صيانة سريع لإصلاح التثبيت باستخدام `uv` 🔧**++### 🐛 إصلاحات الأخطاء {#v0.4.14-bug-fixes}++- **إصلاح رفض `uv` تثبيت v0.4.13 افتراضيًا والعودة إلى إصدار أقدم دون تنبيه**. كان الإصدار السابق يتطلب نسخة تجريبية من `curl_cffi`، وهو ما لا يسمح به `uv` إلا عند تفعيله صراحةً.+أصبحت كل الاعتمادات تستخدم إصدارات مستقرة. (يصلح [#407](https://github.com/D4Vinci/Scrapling/issues/407))++## [v0.4.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.13) - 2026-08-09 {#v0.4.13}++**تحديث جديد يضيف عناكب لملفات الخلاصات وخادم MCP أذكى 🎉**++### 🚀 الجديد وتحسينات الاستخدام {#v0.4.13-new-stuff-and-quality-of-life-changes}++- **قوالب عناكب جديدة للخلاصات**. يمر `XMLFeedSpider` على عُقد أي خلاصة XML (مثل RSS وAtom وخلاصات المنتجات)، ويمر `CSVFeedSpider` على صفوف CSV كقواميس. كلاهما يفك ضغط الخلاصات المضغوطة بـ gzip تلقائيًا. (راجع [التوثيق](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import XMLFeedSpider++ class RSSSpider(XMLFeedSpider):+ name = "rss"+ start_urls = ["https://example.com/feed.xml"]++ async def parse_node(self, response, node):+ yield {"title": node.findtext("title"), "link": node.findtext("link")}++ result = RSSSpider().start()+ ```++- **ترقية خادم MCP إلى MCP SDK v2 وجعله أذكى**. يتضمن الخادم الآن تعليمات تشرح لوكيل الذكاء الاصطناعي كيفية استخدام الأدوات بكفاءة؛ وتعلن كل أداة عن خصائصها حتى تتمكن برامج مثل Claude Code من الموافقة تلقائيًا على الأدوات التي تقرأ فقط؛ وأصبحت أوصاف الأدوات أقصر لتقليل استهلاك tokens؛ ويعرض الخادم إصداره وشعاره لبرامج MCP. (راجع [التوثيق](ai/mcp-server.md))+- **إضافة الأمر `scrapling-mcp`** الذي يشغّل `scrapling mcp` مباشرةً، فأصبح تسجيل Scrapling في برامج وسجلات MCP التي تتوقع أمرًا واحدًا ممكنًا بسطر واحد.+- **إلغاء فرض إصدارات محددة من Playwright/Patchright والمتصفحات**. يطابق User-Agent الذي يُنشأ للمتصفح الآن دائمًا إصدار Chromium الفعلي الذي تشغّله نسخة Playwright/Patchright المثبتة لديك. لذلك لم يعد Scrapling يفرض إصدارات محددة منها ويمكنك ترقيتها بحرية. شغّل `scrapling install --force` بعد التحديث لتحديث المتصفحات.++### 🐛 إصلاحات الأخطاء {#v0.4.13-bug-fixes}++- **إصلاح تعطل استيراد Scrapling بخطأ ValueError من `browserforge`** عندما تكون حزمة بيانات البصمات أقدم من إصدارات المتصفح. (يصلح [#394](https://github.com/D4Vinci/Scrapling/issues/394)، و[#396](https://github.com/D4Vinci/Scrapling/issues/396)، و[#400](https://github.com/D4Vinci/Scrapling/issues/400))+- **إصلاح تحديد عدد الصفحات بشكل خاطئ في أدوات المتصفح الجماعية في MCP**، وهو ما كان يجعل `bulk_fetch` يفشل مع دفعات تزيد على 50 رابطًا، ويجعل `bulk_stealthy_fetch` يجلب كل الروابط عبر تبويب واحد، بمساهمة @Yigtwxx في [#393](https://github.com/D4Vinci/Scrapling/pull/393).++### المشروع {#v0.4.13-project}++- **[سياسة جديدة للمساهمات بمساعدة الذكاء الاصطناعي](https://github.com/D4Vinci/Scrapling/blob/main/AI_POLICY.md)**: نرحب بالمساهمات بمساعدة الذكاء الاصطناعي، لكن يجب ذكر ذلك في طلب الدمج أو البلاغ. تُضاف علامة إلى المساهمات التي تبدو مولّدة بالذكاء الاصطناعي دون الإفصاح عن ذلك، ثم تُغلق.++## [v0.4.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.12) - 2026-07-26 {#v0.4.12}++**إصدار يركز على جعل العناكب أذكى في التعامل مع المواقع التي تزحف إليها**++### 🚀 الجديد وتحسينات الاستخدام {#v0.4.12-new-stuff-and-quality-of-life-changes}++- **تستطيع العناكب الآن ضبط سرعتها تلقائيًا باستخدام AutoThrottle.** بدلًا من تخمين قيمة `download_delay` قد تكون بطيئة جدًا أو تؤدي إلى حظرك، يقيس العنكبوت سرعة رد كل موقع ويضبط فترة الانتظار لكل نطاق بنفسه. عندما يبدأ الموقع في حظرك أو تقييد معدل طلباتك، يضاعف فترة الانتظار (أو ينتظر المدة التي تطلبها ترويسة `Retry-After` بالضبط) حتى يتوقف ذلك، ثم يزيد السرعة مجددًا. تبقى قيمة `download_delay` وأي `Crawl-delay` في robots.txt حدًا أدنى. (راجع [التوثيق](spiders/advanced.md#autothrottle))++ ```python+ class MySpider(Spider):+ name = "adaptive"+ start_urls = ["https://example.com"]+ autothrottle_enabled = True+ autothrottle_start_delay = 2.0+ autothrottle_max_delay = 30.0+ autothrottle_block_backoff = True+ ```++- **تصدير النتائج إلى CSV وXML**، إلى جانب التصدير إلى JSON/JSONL المتاح سابقًا. تُصدَّر العناصر دون فقدان أي بيانات حتى لو اختلفت مفاتيحها، وتُكتب القيم المتداخلة بصيغة JSON. (راجع [التوثيق](spiders/getting-started.md))++ ```python+ result = MySpider().start()+ result.items.to_csv("products.csv")+ result.items.to_xml("products.xml")+ ```++- **يمكن لخادم MCP الآن طلب التحقق من الهوية**، حتى تتمكن من إتاحته بأمان بدلًا من حصره في جهازك. يُرفض أي طلب لا يحتوي على الرمز، ويمكنك أيضًا تحديد أسماء المضيفين التي يرد عليها الخادم. (راجع [التوثيق](ai/mcp-server.md))++ ```bash+ scrapling mcp --http --auth-token "$(openssl rand -hex 32)"+ ```++- **تقبل المتصفحات الآن روابط CDP عبر HTTP**، إلى جانب روابط WebSocket. فبالإضافة إلى عناوين `wss://` التي توفرها خدمات المتصفحات المُدارة، يمكنك الآن توصيل أي أداة جلب بالمتصفح أو جلسة MCP بمتصفح Chrome شغّلته بنفسك باستخدام `--remote-debugging-port=9222`.++- **أصبحت صور Docker المنشورة تحمل وسم رقم إصدارها** بدلًا من الاكتفاء بـ `latest`، حتى تتمكن من تثبيت الإصدار الذي تريده بالضبط، بمساهمة @JanRK في [#384](https://github.com/D4Vinci/Scrapling/pull/384).++### 🐛 إصلاحات الأخطاء {#v0.4.12-bug-fixes}++- **إصلاح فقدان كل ملفات cookies في الردود المخزنة مؤقتًا** عندما يأتي الرد من محرك متصفح، وهو ما كان يعطّل دون تنبيه أي منطق للجلسات أو التحقق من الهوية يعتمد عليها أثناء استخدام وضع تطوير العناكب، بمساهمة @amitvijapur في [#379](https://github.com/D4Vinci/Scrapling/pull/379). (يصلح [#376](https://github.com/D4Vinci/Scrapling/issues/376))++- **إصلاح فرض `StealthyFetcher` إعداد اللغة والمنطقة `en-US`** على كل متصفح بدلًا من اتباع إعداد نظامك. كان ذلك يجعل المواقع ترى اختلافًا بين إعداد اللغة والمنطقة وعنوان IP وتتعامل معك بشك، مثل ردود Google برمز 429. (يصلح [#381](https://github.com/D4Vinci/Scrapling/issues/381))++- **إصلاح رسالة خطأ مضللة في نظام التخزين** وإزالة استدعاء غير مستخدم كان متبقيًا بعد عمليات الإدراج، بمساهمة @fix2015 في [#377](https://github.com/D4Vinci/Scrapling/pull/377).++### الأداء {#v0.4.12-performance}++- **أصبح وقت تنفيذ `get_all_text()` يتناسب مع عدد العقد، أي O(nodes)** بدلًا من المرور على كل أسلاف كل عقدة نصية، مما يجعله أسرع بنحو 5-6 أضعاف في الصفحات ذات التداخل العميق، بمساهمة @yetval في [#378](https://github.com/D4Vinci/Scrapling/pull/378).++## [v0.4.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.11) - 2026-07-12 {#v0.4.11}++**تحديث يضيف أول قالب عنكبوت لمنصة محددة، ومحللًا أسرع، وإصلاحات مهمة 🎉**++### 🚀 الجديد وتحسينات الاستخدام {#v0.4.11-new-stuff-and-quality-of-life-changes}++- **إضافة `ShopifySpider`، أول قالب عنكبوت لمنصة محددة!** استخرج كل المنتجات من أي متجر يعمل بـ Shopify عبر JSON API دون التعامل مع HTML الموقع. أنشئ كلاس يرث منه، وحدد نطاق المتجر، وهذا كل ما تحتاجه (راجع [التوثيق](spiders/platform-templates.md))++ ```python+ from scrapling.spiders import ShopifySpider++ class MyStore(ShopifySpider):+ target_website = "example.com"++ result = MyStore().start()+ ```++- **إضافة `--executable-path` إلى أوامر المتصفح في CLI**. يقبل كل من `scrapling extract fetch` و`scrapling extract stealthy-fetch` الآن مسار ملف تشغيل متصفح مخصص متوافق مع Chromium، ويستخدمان متغير البيئة `SCRAPLING_EXECUTABLE_PATH` عند عدم تمرير الخيار، ليصبحا متوافقين تمامًا مع خادم MCP (يحل [#371](https://github.com/D4Vinci/Scrapling/issues/371))++ ```bash+ scrapling extract fetch "https://example.com" page.html --executable-path "/path/to/chromium"+ ```++### 🤖 تحسينات الاستخدام {#v0.4.11-quality-of-life-changes}+- **تسريع `find_by_text` و`find_by_regex` حتى نحو ضعفين** عند تفعيل `first_match` (وهو الإعداد الافتراضي)، بتحويل العناصر إلى كائنات عند الحاجة فقط حتى يتوقف البحث عند أول تطابق، بمساهمة @yetval في [#370](https://github.com/D4Vinci/Scrapling/pull/370)+- **تحديث اختبارات الأداء بالأرقام الجديدة مقارنةً بأحدث إصدارات كل المكتبات.**+- **تحديث قواعد المساهمة**++### 🐛 إصلاحات الأخطاء {#v0.4.11-bug-fixes}++- **إصلاح تعطل أدوات الجلب في خادم MCP مع الصفحات التي تحتوي على محارف تحكم** بالخطأ `All strings must be XML compatible`، بمساهمة @yetval في [#368](https://github.com/D4Vinci/Scrapling/pull/368) (يصلح [#366](https://github.com/D4Vinci/Scrapling/issues/366))++## [v0.4.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.10) - 2026-07-04 {#v0.4.10}++**تحديث جديد يضيف تكاملًا جديدًا مع Scrapy ومجموعة إصلاحات من المجتمع 🎉**++### 🚀 الجديد وتحسينات الاستخدام {#v0.4.10-new-stuff-and-quality-of-life-changes}++- **إضافة تكامل مع Scrapy** حتى تتمكن من استخدام واجهة التحليل في Scrapling داخل مشاريع Scrapy الحالية دون إعادة كتابتها. ضع الـ decorator المسمى `scrapling_response` على أي دالة callback للعنكبوت، فيصبح الرد الذي تستقبله كائن `Response` من Scrapling، بينما يواصل Scrapy إدارة الزحف (راجع [التوثيق](integrations/scrapy.md)):++ ```python+ import scrapy+ from scrapling.integrations.scrapy import scrapling_response++ class QuotesSpider(scrapy.Spider):+ name = "quotes"+ start_urls = ["https://quotes.toscrape.com"]++ @scrapling_response+ def parse(self, response): # `response` is now a Scrapling Response+ first_quote = response.find_by_text("The world as we have created it", partial=True)+ for quote in [first_quote, *first_quote.find_similar()]:+ yield {"text": quote.get_all_text(strip=True)}+ ```++- **يمكن لخادم MCP الآن استخدام متصفح مخصص متوافق مع Chromium** لكل الأدوات التي تعتمد على المتصفح. اضبطه مرة واحدة باستخدام `scrapling mcp --executable-path "/path/to/chromium"` أو متغير البيئة `SCRAPLING_EXECUTABLE_PATH`، أو لكل طلب باستخدام الوسيط `executable_path`، بمساهمة @samrusani في [#360](https://github.com/D4Vinci/Scrapling/pull/360) (يحل [#347](https://github.com/D4Vinci/Scrapling/issues/347))+- **تحديث كل المتصفحات والبصمات**. شغّل `scrapling install --force` بعد التحديث لتحديثها.++### 🐛 إصلاحات الأخطاء {#v0.4.10-bug-fixes}++- **إصلاح النص المشوّه (mojibake) الناتج من أدوات الجلب بالمتصفح على مواقع لا تستخدم UTF-8**، بمساهمة @yehudalevy-collab في [#365](https://github.com/D4Vinci/Scrapling/pull/365) (يصلح [#364](https://github.com/D4Vinci/Scrapling/issues/364)).+- **إصلاح عدم تصفية `LinkExtractor` لامتدادات الملفات المركبة مثل `.tar.gz`**، بمساهمة @renbkna في [#359](https://github.com/D4Vinci/Scrapling/pull/359) (يصلح [#349](https://github.com/D4Vinci/Scrapling/issues/349)).+- **إصلاح فقدان الطلبات قيد التنفيذ من نقاط الاستكمال عند إيقاف الزحف مؤقتًا، فأصبح الاستكمال لا يتخطاها**، بمساهمة @yetval في [#358](https://github.com/D4Vinci/Scrapling/pull/358).+- **إصلاح حساب العناكب لفترات انتظار خاطئة من تعليمات `Request-rate` في robots.txt** عبر ترقية Protego، مع تحديث الاختبارات بما يناسب ذلك بمساهمة @Disaster-Terminator في [#355](https://github.com/D4Vinci/Scrapling/pull/355).++### التوثيق {#v0.4.10-docs}++- **توضيح كيفية تفاعل `init_script` مع سياق التنفيذ المعزول في Patchright في وضع التخفي**، بمساهمة @mturac في [#353](https://github.com/D4Vinci/Scrapling/pull/353) (يحل [#350](https://github.com/D4Vinci/Scrapling/issues/350)).+- **إضافة طريقة تثبيت مهارة الوكيل عبر [skills.sh](https://skills.sh/D4Vinci/Scrapling)**، بمساهمة @ob-aion في [#363](https://github.com/D4Vinci/Scrapling/pull/363).++## [v0.4.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.9) - 2026-06-07 {#v0.4.9}++**تحديث صيانة يضم الكثير من الإصلاحات التي أبلغ عنها المجتمع 🛠️**++### 🚀 الجديد وتحسينات الاستخدام {#v0.4.9-new-stuff-and-quality-of-life-changes}++- **تحديث كل المتصفحات والبصمات**. شغّل `scrapling install --force` بعد التحديث لتحديثها.+- **إضافة الخيار `--version` إلى CLI**، بمساهمة @ETM-Code في [#303](https://github.com/D4Vinci/Scrapling/pull/303) (يحل [#299](https://github.com/D4Vinci/Scrapling/issues/299))++### 🐛 إصلاحات الأخطاء {#v0.4.9-bug-fixes}++- **إصلاح تجاهل الوسيط `proxy` المحدد للجلسة دون تنبيه في جلسات HTTP**، وهو ما قد يكشف عنوان IP الحقيقي (يحل [#295](https://github.com/D4Vinci/Scrapling/issues/295)). لاحظ أن الجمع بين `proxy` على مستوى الجلسة والوسيط `proxies` على مستوى الطلب (أو العكس) يسبب الآن خطأ بدلًا من تجاهل أحدهما دون تنبيه.+- **إصلاح فشل الانتقال بين الصفحات عند الجمع بين `init_script` و`user_data_dir`** (يحل [#294](https://github.com/D4Vinci/Scrapling/issues/294)).+- **إصلاح اكتشاف الترميز عندما تضع المواقع قيمة charset بين علامتي اقتباس في ترويسة `Content-Type`**، بمساهمة @Bortlesboat في [#323](https://github.com/D4Vinci/Scrapling/pull/323).+- **إصلاح خطأ `IndexError` عند إعادة العثور على العناصر تكيفيًا مع تفعيل `auto_save`**، بمساهمة @Mubashirrrr في [#340](https://github.com/D4Vinci/Scrapling/pull/340).+- **إصلاح تعطل حفظ نقاط الاستكمال والذاكرة المؤقتة للعناكب على Windows**، بمساهمة @MrStarkEG في [#344](https://github.com/D4Vinci/Scrapling/pull/344).+- **إصلاح حساب نسبة تشابه خاطئة في `find_similar` للعناصر التي تختلف في عدد السمات** (يحل [#322](https://github.com/D4Vinci/Scrapling/issues/322)).++### التوثيق {#v0.4.9-docs}++- **توضيح أن التثبيت الافتراضي يشمل محرك التحليل فقط**، وأن أدوات الجلب والعناكب تحتاج إلى الإضافات الاختيارية (يحل [#343](https://github.com/D4Vinci/Scrapling/issues/343)).+- **إصلاح اسم صورة Docker في بقية الأمثلة**، بمساهمة @evanclan في [#315](https://github.com/D4Vinci/Scrapling/pull/315).+- **إصلاح رابط لا يعمل في دليل المساهمة**، بمساهمة @Bortlesboat في [#320](https://github.com/D4Vinci/Scrapling/pull/320).++## [v0.4.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.8) - 2026-05-11 {#v0.4.8}++**تحديث كبير للعناكب يطوّر نظام الزحف 🕷️**++### 🚀 الجديد وتحسينات الاستخدام {#v0.4.8-new-stuff-and-quality-of-life-changes}++- **إضافة أداة `LinkExtractor`** في `scrapling.spiders.LinkExtractor` لاستخراج الروابط من `Response`. توفر الكثير من خيارات التحكم (راجع [التوثيق](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import LinkExtractor++ extractor = LinkExtractor(allow=r"/posts/", deny_domains=["ads.example.com"])+ ```++- **إضافة قالبي العناكب العامين `CrawlSpider` و`CrawlRule`** حتى لا تضطر إلى تكرار كتابة كود "اتبع الروابط التي تطابق هذا النمط". أعد تعريف `rules()` لإرجاع قائمة من كائنات `CrawlRule`، يرتبط كل منها بكائن `LinkExtractor`. (راجع [التوثيق](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import CrawlSpider, CrawlRule, LinkExtractor++ class QuotesSpider(CrawlSpider):+ name = "blog"+ start_urls = ["https://quotes.toscrape.com/"]++ def rules(self):+ return [+ CrawlRule(LinkExtractor(allow=r"/author/"), callback=self.parse_author),+ CrawlRule(LinkExtractor(allow=r"/page/\d+/")), # pagination, no callback+ ]++ async def parse_author(self, response):+ yield {+ "name": response.css(".author-title::text").get(),+ "birthday": response.css(".author-born-date::text").get(),+ "url": response.url,+ }+ ```++- **إضافة قالب `SitemapSpider`** الذي يبدأ الزحف مباشرةً من خريطة موقع أو روابط `robots.txt`. يدعم خرائط المواقع المضغوطة بـ gzip، ويوفر الكثير من خيارات التحكم والإعدادات. تُوزَّع الروابط باستخدام قواعد الزحف كما في مثال **CrawlSpider** أعلاه. (راجع [التوثيق](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import SitemapSpider, CrawlRule, LinkExtractor++ class NewsSitemap(SitemapSpider):+ name = "news"+ sitemap_urls = ["https://example.com/robots.txt"]++ def rules(self):+ return [+ CrawlRule(LinkExtractor(allow=r"/articles/"), callback=self.parse_article),+ ]++ async def parse_article(self, response):+ yield {"url": response.url, "title": response.css("h1::text").get()}+ ```++- **أصبحت إعادة العثور على العناصر تكيفيًا تستخدم حد تشابه افتراضيًا قدره 40%** بدلًا من `0` في كل الدوال. يحسّن هذا عمل الميزة التكيفية. وعندما لا يتجاوز أي عنصر هذا الحد، يخبرك تحذير الآن بأعلى نسبة تشابه عُثر عليها، لتتمكن من خفض `percentage` عن قصد عند الحاجة.++- **تحديث كل المتصفحات والبصمات**. شغّل `scrapling install --force` من جديد بعد التحديث لتحديث المتصفحات والبصمات.++### 🐛 إصلاحات الأخطاء {#v0.4.8-bug-fixes}++- **إصلاح عدم تطبيق `Fetcher.configure(...)` على الاستدعاءات لكل طلب**. طُبق الإصلاح نفسه على `AsyncFetcher`.+- **إصلاح حساب بصمات الطلبات بشكل خاطئ مما تسبب في تكرار الطلبات في العناكب**، بمساهمة @yetval في [#255](https://github.com/D4Vinci/Scrapling/pull/255).+- **إصلاح عدم تنبيه محرك الاستخراج التكيفي عند ضعف التطابق.** مع تغيير حد التشابه أعلاه، يظهر الآن تحذير بدلًا من عنصر مضلل باعتباره "أفضل تخمين" عندما تفشل إعادة العثور على العنصر.++### التوثيق {#v0.4.8-docs}++- **تحديث أمثلة الكود القديمة** في التوثيق لتطابق الإصدار الحالي.+- **تحسين نسخ الكود ولصقه** من موقع التوثيق، واختصار مهارة الوكيل لتستهلك عددًا أقل من tokens في كل استدعاء.++## [v0.4.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.7) - 2026-04-17 {#v0.4.7}++**تحديث يتيح لوكلاء الذكاء الاصطناعي رؤية الصفحات 📸**++### 🚀 الجديد وتحسينات الاستخدام {#v0.4.7-new-stuff-and-quality-of-life-changes}++- **إضافة أداة MCP باسم `screenshot`** تلتقط صورة للصفحة وتعيدها ككتلة MCP فعلية من نوع `ImageContent` حتى يتمكن النموذج من رؤيتها. تتطلب الأداة جلسة متصفح مفتوحة، لذلك استدعِ `open_session` أولًا (إما `dynamic` أو `stealthy`) ومرّر `session_id` هنا. تدعم PNG وJPEG، والتقاط الصفحة كاملة، وجودة JPEG، وخيارات انتظار الجاهزية المعتادة (`wait`، `wait_selector`، `network_idle`، `timeout`). (ينفذ [#244](https://github.com/D4Vinci/Scrapling/issues/244))+- **إضافة وسيط `session_id` مخصص إلى `open_session`** حتى تتمكن من تسمية الجلسات بأسماء واضحة (`"search"`، `"checkout"`) بدلًا من الاسم الافتراضي العشوائي المكوّن من 12 محرفًا بنظام hex. بمساهمة @hauntedhost في [#243](https://github.com/D4Vinci/Scrapling/pull/243)++### 🐛 إصلاحات الأخطاء {#v0.4.7-bug-fixes}++- **إصلاح تلف حالة `FetcherSession` والتعطل عند إغلاق جلسة مؤجلة البدء**. بمساهمة @yetval في [#245](https://github.com/D4Vinci/Scrapling/pull/245)+- **إصلاح الخطأ `TypeError: Session.request() got an unexpected keyword argument 'block_ads'`** عند استخدام خيار CLI المسمى `--ai-targeted` مع أوامر HTTP. بمساهمة @voidborne-d في [#249](https://github.com/D4Vinci/Scrapling/pull/249) (يصلح [#247](https://github.com/D4Vinci/Scrapling/issues/247))++### الترجمات {#v0.4.7-translations}++- **إضافة ترجمة README إلى البرتغالية البرازيلية** بمساهمة @rgomids في [#250](https://github.com/D4Vinci/Scrapling/pull/250)++## [v0.4.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.6) - 2026-04-13 {#v0.4.6}++**تحديث يركز على تخفي المتصفح والخصوصية وتجربة المطور 🔒**++### 🚀 الجديد وتحسينات الاستخدام {#v0.4.6-new-stuff-and-quality-of-life-changes}++- **إضافة حظر إعلانات مدمج** لأدوات الجلب بالمتصفح. مرّر `block_ads=True` لحظر الطلبات إلى نحو 3,500 نطاق معروف للإعلانات والتتبع عند اعتراض مسار الطلب، فيُلغى فورًا دون DNS أو TCP. يمكن الجمع بينه وبين `blocked_domains` لقوائم مخصصة. يفعّل خادم MCP ووضع CLI المسمى `--ai-targeted` هذا الخيار تلقائيًا لتقليل استهلاك tokens وتسريع تحميل الصفحات.++ ```python+ page = StealthyFetcher.fetch('https://example.com', block_ads=True)+ ```++- **إضافة دعم DNS-over-HTTPS** لمنع تسرب DNS عند استخدام proxies. مرّر `dns_over_https=True` لتوجيه استعلامات DNS عبر خدمة DoH من Cloudflare، حتى لا يكشف حل أسماء DNS موقعك الحقيقي عندما تمر حركة HTTP عبر proxy.++ ```python+ page = StealthyFetcher.fetch('https://example.com', proxy='http://proxy:8080', dns_over_https=True)+ ```++- **إضافة دالة callback باسم `page_setup`** لأدوات الجلب بالمتصفح. تعمل هذه الدالة قبل `page.goto()`، فتتيح لك تسجيل مستمعي الأحداث أو المسارات أو السكربتات التي يجب إعدادها قبل انتقال الصفحة. تعمل مع `page_action` (التي تُنفذ بعد الانتقال). (يحل [#237](https://github.com/D4Vinci/Scrapling/issues/237))++ ```python+ def capture_websockets(page):+ page.on("websocket", lambda ws: print(f"WS: {ws.url}"))++ page = DynamicFetcher.fetch('https://example.com', page_setup=capture_websockets)+ ```++- **إضافة خياري CLI المسمّيين `--block-ads` و`--dns-over-https`** إلى الأمرين `fetch` و`stealthy-fetch`.++### 🐛 إصلاحات الأخطاء {#v0.4.6-bug-fixes}++- **إصلاح رفض الاسم البديل للنوع `Seconds`** للقيم العشرية. كان تمرير `wait=1.5` أو `timeout=500.0` إلى أدوات الجلب بالمتصفح يفشل بخطأ نوع، لأن الاسم البديل كان يتعامل مع `float` كبيانات وصفية بدلًا من نوع. بمساهمة @kuishou68 في [#240](https://github.com/D4Vinci/Scrapling/pull/240)+- **إصلاح تكرار أجزاء ID عند إنشاء المحددات ذات المسار الكامل**. كانت محددات العناصر التي تحتوي على سمة `id` تُضاف مرتين عند إنشاء مسارات CSS/XPath الكاملة، فتنتج محددات مثل `body > #main > #main > #target > #target`. وأُصلح أيضًا إنتاج شروط `[@id='x']` وحدها (وهي XPath غير صالح) بدلًا من `*[@id='x']` في مسارات XPath الكاملة. بمساهمة @sjhddh في [#241](https://github.com/D4Vinci/Scrapling/pull/241)+- **إصلاح المعاملات الناقصة في تعريفات دوال shell**. كانت تعريفات الدوال في shell التفاعلية تفتقد `blocked_domains` و`block_ads` و`retries` و`retry_delay` و`capture_xhr` و`executable_path` و`dns_over_https`.++## [v0.4.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.5) - 2026-04-07 {#v0.4.5}++**تحديث يضيف ميزة كبيرة تسهّل عمل مطوري العناكب مع بعض الإصلاحات المهمة 🎉**++### 🚀 الجديد وتحسينات الاستخدام {#v0.4.5-new-stuff-and-quality-of-life-changes}++- **وضع تطوير العناكب**: كان تعديل منطق `parse()` في العنكبوت يتطلب إرسال طلبات إلى خوادم الموقع في كل تشغيل، وهو أمر بطيء ويزيد الضغط عليها، وقد يؤدي إلى تقييد معدل طلباتك وأنت ما زلت تضبط محدداتك. يخزّن وضع التطوير الجديد كل رد على القرص في أول تشغيل، ويعيد استخدامه من القرص في كل تشغيل لاحق. يمكنك بذلك تعديل دوال callback وإعادة التشغيل كما تريد دون إرسال أي طلب للشبكة. فعّله بخاصية واحدة في الكلاس:++ ```python+ class MySpider(Spider):+ name = "my_spider"+ start_urls = ["https://example.com"]+ development_mode = True++ async def parse(self, response):+ yield {"title": response.css("title::text").get("")}+ ```++ توجد الذاكرة المؤقتة افتراضيًا في `.scrapling_cache/{spider.name}/`، ويمكن تغيير مكانها باستخدام `development_cache_dir`. ويتيح لك عدّادان جديدان، `cache_hits` و`cache_misses`، معرفة أداء الذاكرة المؤقتة. تتجاوز إعادة استخدام الردود المخزنة `download_delay` وتقييد معدل الطلبات ومسار إعادة محاولة الطلبات المحظورة، لتصبح التجربة بأقصى سرعة يسمح بها القرص. لا تنشر عنكبوتًا مع `development_mode = True`؛ فهو أداة للتطوير وليس ذاكرة مؤقتة للاستخدام الفعلي. راجع [التوثيق](spiders/advanced.md#development-mode) للتفاصيل.++- **إعادة توجيه أكثر أمانًا افتراضيًا**: أصبحت القيمة الافتراضية لـ `follow_redirects` هي `"safe"` في كل أدوات جلب HTTP وخادم MCP وshell. لا يزال النظام يتبع عمليات إعادة التوجيه، لكنه يرفض ما يستهدف عناوين IP داخلية أو خاصة (loopback والشبكات الخاصة وlink-local). يحميك هذا من SSRF عند استخراج البيانات من روابط يقدمها المستخدمون. مرّر `follow_redirects="all"` للعودة إلى السلوك السابق، أو `False` لتعطيل إعادة التوجيه تمامًا.++### 🐛 إصلاحات الأخطاء {#v0.4.5-bug-fixes}++- **لم يعد الإيقاف الإجباري يفقد نقطة الاستكمال**: كان الضغط على Ctrl+C مرتين (الإيقاف الإجباري) لعنكبوت فعّل `crawldir` يتزامن مع كتابة نقطة الاستكمال. كان نطاق الإلغاء ينهي المهمة قبل اكتمال pickle، ويترك `paused=False` ويشغّل مسار التنظيف الذي *يحذف* نقطة الاستكمال السابقة. لذلك كان إيقاف زحف طويل إجباريًا قد يفقدك كل التقدم الذي تحاول حفظه. يكتب المحرك الآن نقطة الاستكمال **قبل** استدعاء `cancel_scope.cancel()`، فيحفظ الإيقاف الإجباري دائمًا أحدث حالة للطلبات المعلقة. بمساهمة @voidborne-d في [#230](https://github.com/D4Vinci/Scrapling/pull/230).++## [v0.4.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.4) - 2026-04-05 {#v0.4.4}++**تحديث جديد يضيف تحسينات مهمة للعناكب وإصلاحات للأخطاء 🎉**++### 🚀 الجديد وتحسينات الاستخدام {#v0.4.4-new-stuff-and-quality-of-life-changes}+- **إضافة الالتزام بقواعد robots.txt إلى نظام العناكب** عبر الخيار الجديد `robots_txt_obey`. عند تفعيله، يجلب العنكبوت قواعد robots.txt تلقائيًا ويلتزم بها قبل الزحف، بما فيها `Disallow` و`Crawl-delay` و`Request-rate`. تُجلب ملفات robots.txt بالتزامن وتُخزّن مؤقتًا لكل نطاق طوال الزحف. بمساهمة @AbdullahY36 في [#226](https://github.com/D4Vinci/Scrapling/pull/226)+- **إضافة تجهيز مسبق لذاكرة robots.txt المؤقتة** بحيث تُجلب وتُحلل ملفات robots.txt لكل نطاقات start_urls قبل بدء حلقة الزحف، لتجنب التأخير عند أول طلب لكل نطاق.+- **إضافة الإحصائية الجديدة `robots_disallowed_count`** إلى `CrawlStats` لمعرفة عدد الطلبات التي منعتها قواعد robots.txt أثناء الزحف.++اطلع عليها في الموقع من [هنا](spiders/getting-started.md#robotstxt-compliance)++### 🐛 إصلاحات الأخطاء {#v0.4.4-bug-fixes}+- **إصلاح مشكلة مهمة في ترتيب البحث عن الدوال MRO مع `ProxyRotator`**، حيث كان التعريف المبدئي لـ `_build_context_with_proxy` يحجب التنفيذ الفعلي في الكلاسات الفرعية، فتسبب تدوير proxies دائمًا في الخطأ `NotImplementedError` (يصلح [#215](https://github.com/D4Vinci/Scrapling/issues/215)). شكرًا @yetval+- **إصلاح تسرب في مجموعة الصفحات** عند استخدام تدوير proxies لكل طلب مع جلسات المتصفح. لم تكن الصفحات المنشأة داخل سياقات مؤقتة تُحذف من المجموعة عند التنظيف، مما أدى إلى تراكم مراجع قديمة مع الوقت. بمساهمة @yetval في [#223](https://github.com/D4Vinci/Scrapling/pull/223)+- **إصلاح غياب فحص يؤكد النوع** في أداة الجلب الثابتة، حيث كان يمكن أن تعيد `curl_cffi` القيمة `None` من `session.request()`، مما يسبب أخطاء لاحقًا.++### تغييرات أخرى {#v0.4.4-other}+- تحديث الاعتمادات، لتتوفر أحدث البصمات والتحديثات الأخرى.+- إضافة `protego` كاعتماد جديد ضمن المجموعة الاختيارية `fetchers` لتحليل robots.txt.++## [v0.4.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.3) - 2026-03-30 {#v0.4.3}++**تحديث جديد يضم الكثير من التغييرات المهمة 🎉**++### 🚀 الجديد وتحسينات الاستخدام {#v0.4.3-new-stuff-and-quality-of-life-changes}+- **إضافة أداة MCP جديدة** لفتح متصفح عادي أو خفي مستمر لاستخدامه مع بقية الأدوات، وأداة جديدة أخرى لإغلاقه. ([أمثلة](https://github.com/D4Vinci/Scrapling/blob/v0.4.3/docs/ai/mcp-server.md#examples))+- **إضافة أداة MCP جديدة** لعرض كل جلسات المتصفح الحالية، لاستخدامها مع الأدوات الجديدة.+- **إضافة خيار جديد إلى جلسات المتصفح** لجمع كل طلبات الخلفية التي تحدث أثناء الطلب تلقائيًا (يحل [#159](https://github.com/D4Vinci/Scrapling/pull/159)) [[أمثلة](https://github.com/D4Vinci/Scrapling/blob/v0.4.3/docs/fetching/dynamic.md#capturing-xhrfetch-requests)].+- **إضافة أداة تنظيف جديدة** لحماية خادم MCP من هجمات Prompt Injection الشائعة بإزالة المحتوى المخفي وغير المرئي.+- **إضافة خيار سطر أوامر جديد** باسم `--ai-targeted` إلى أوامر استخراج بيانات الويب لجعل المحتوى مناسبًا للذكاء الاصطناعي وآمنًا من هجمات Prompt Injection الشائعة كما في خادم MCP.+- **إضافة خيار جديد إلى جلسات المتصفح** باسم `executable_path` لتحديد مسار متصفح مخصص (يحل [#202](https://github.com/D4Vinci/Scrapling/pull/202))+- **إعادة تنظيم** كود خادم MCP لتسهيل صيانته، وجعل كل الأدوات تعمل بشكل غير متزامن.+- **إعادة تنظيم** كود أوامر CLI لتسهيل صيانته، واختصاره بمقدار 210 أسطر.++### 🐛 إصلاحات الأخطاء {#v0.4.3-bug-fixes}+- إصلاح يحافظ على طريقة HTTP عند إعادة المحاولة في جلسة العنكبوت، بمساهمة @karesansui-u في [#201](https://github.com/D4Vinci/Scrapling/pull/201)+- إضافة حد أقصى لمحاولات جلب محتوى الصفحة لمنع التكرار بلا نهاية، بمساهمة @haosenwang1018 و@D4Vinci في [#197](https://github.com/D4Vinci/Scrapling/pull/197)+- استبدال `raise` دون وسيط بـ `return False` في `_restore_from_checkpoint`، بمساهمة @haosenwang1018 في [#196](https://github.com/D4Vinci/Scrapling/pull/196)+- استبدال `get_all` بـ `getall` في `Texthandler` لتطابق كلاس Selector.++### تحسين الاختبارات وتغطيتها {#v0.4.3-coverage-tests-improvement}+- إضافة اختبارات للحالات الطرفية في `_normalize_credentials`، بمساهمة @Bortlesboat في [#192](https://github.com/D4Vinci/Scrapling/pull/192)+- إضافة اختبارات لعملية الحفظ ثم الاسترجاع وللتخزين الأساسي، بمساهمة @haosenwang1018 في [#193](https://github.com/D4Vinci/Scrapling/pull/193)+- إضافة اختبارات لمسارات regex في `TextHandler` ولـ `TextHandlers.re()`، بمساهمة @haosenwang1018 في [#194](https://github.com/D4Vinci/Scrapling/pull/194)+- إضافة اختبارات للحالات الطرفية في `filter` و`iterancestors` و`find_similar`، بمساهمة @awanawana في [#200](https://github.com/D4Vinci/Scrapling/pull/200)++### تحسين مهارة الوكيل {#v0.4.3-agent-skill-improvement}+- إصلاح روابط Markdown التي لا تعمل في مراجع المهارة، بمساهمة @yetval في [#204](https://github.com/D4Vinci/Scrapling/pull/204)+- تحسين تنظيم المهارة لتجتاز فحوص [Clawhub](https://clawhub.ai/d4vinci/scrapling-official) بصورة أفضل.+- إلزام المهارة باستخدام خيار سطر الأوامر `--ai-targeted` عند استخراج البيانات عبر أوامر سطر الأوامر.++### تحسين التوثيق {#v0.4.3-docs-improvement}+- إضافة ترجمة README إلى الكورية، بمساهمة @greatsk55 في [#187](https://github.com/D4Vinci/Scrapling/pull/187)+- إصلاح المسافات بين محارف CJK واللاتينية في ملفي README الصيني والياباني.+- إصلاح روابط لا تعمل من تصميم الموقع القديم.++## [v0.4.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.2) - 2026-03-08 {#v0.4.2}++**تحديث صيانة جديد مع تغييرات مهمة**++#### إصلاحات الأخطاء {#v0.4.2-bug-fixes}+- تلتقط الدالة `get_all_text()` الآن النص الذي يأتي بعد العناصر أيضًا. يتيح ذلك لخادم MCP والأوامر قراءة نص كان يفوتها من قبل ([#168](https://github.com/D4Vinci/Scrapling/pull/168)). شكرًا @mhillebrand+- أصبح Referer يعيد عنوان Google الأساسي بدلًا من رابط بحث Google. كان المنطق السابق غير صحيح، وقد يعطي المواقع علامة تساعدها في اكتشاف بصمة المتصفح ([#179](https://github.com/D4Vinci/Scrapling/pull/179)). شكرًا @Bortlesboat+- إصلاح مشكلة في دمج خيارات التشغيل الإضافية في جميع المتصفحات. شكرًا @rostchri+- إصلاح مشكلة في تلميحات الأنواع كانت تتسبب في تعطل الكود مع إصدارات Python الأقدم من 3.12. (يحل [#163](https://github.com/D4Vinci/Scrapling/issues/163))++#### تغييرات أخرى {#v0.4.2-other}+- إضافة Agent Skill لأدوات Claude Code / OpenClaw وغيرها من أدوات وكلاء الذكاء الاصطناعي.+- إضافة Agent Skill إلى Clawhub.+- تحديث جميع المتصفحات وPlaywright إلى أحدث الإصدارات.+- إضافة ترجمة فرنسية لملف README الرئيسي.++## [v0.4.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.1) - 2026-02-27 {#v0.4.1}++**تحديث جديد مع تغييرات مهمة كثيرة**++### 🚀 الجديد وتحسينات الاستخدام {#v0.4.1-new-stuff-and-quality-of-life-changes}+- **تحسين دقة regex** لاكتشاف تحديات Cloudflare (شكرًا @Rinz27 [#133](https://github.com/D4Vinci/Scrapling/pull/133))+- **تحسين سرعة وكفاءة** أداة حل تحديات Cloudflare. أصبحت الآن أسرع بنحو الضعف.+- **تحسين أداة حل تحديات Cloudflare** للتعامل مع المواقع التي تعرض صفحة Cloudflare مرتين أحيانًا قبل الانتقال إلى الموقع الأساسي.+- **تحسين التخفي وسرعة المتصفح المتخفي** بإزالة ملفات JS التي كانت تُحقن في الصفحات.+- **تحسين مخطط MCP** ليقبله OpenCode (شكرًا @robin-ede [#137](https://github.com/D4Vinci/Scrapling/pull/137))+- **تحسين توافق مخطط MCP مع المعيار** ليقبله VS Code Copilot وغيره من الأدوات التي تتحقق منه بدقة. (يحل #150 )+- **تقليل استهلاك خادم MCP للتوكنات** بدرجة كبيرة بإزالة وسوم HTML غير المفيدة عند تفعيل الخيار `main_content_only`.+- إصلاح صفحة PyPI وإضافة الملفات اللازمة لتسجيل خادم MCP في سجل خوادم MCP.+- إضافة مثال برمجي جديد يوضح تثبيت متطلبات المتصفحات من الكود بدلًا من سطر الأوامر، لتسهيل الأتمتة.+- تحسين جميع workflows باستخدام أحدث إصدارات actions (شكرًا @salmanmkc [#143](https://github.com/D4Vinci/Scrapling/pull/143)/[#144](https://github.com/D4Vinci/Scrapling/pull/144))++## [v0.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4) - 2026-02-15 {#v0.4}++**أكبر إصدار من Scrapling حتى الآن - يقدم نظام العناكب وتدوير البروكسي وتحسينات كبيرة في محلل الصفحات**++يضيف هذا الإصدار نظام عناكب وزحف غير متزامن بالكامل، وإدارة ذكية للبروكسي، وتغييرات مهمة في API تجعل Scrapling أقوى وأكثر اتساقًا. يرجى قراءة قسم التغييرات التي قد تؤثر في الكود الحالي بعناية قبل التحديث.++### 🕷️ نظام العناكب {#v0.4-spider-framework}++نظام زحف جديد غير متزامن، مبني على `anyio` لاستخراج البيانات بصورة منظمة وعلى نطاق واسع:++```python+from scrapling.spiders import Spider, Response++class MySpider(Spider):+ name = "demo"+ start_urls = ["https://example.com/"]++ async def parse(self, response: Response):+ for item in response.css('.product'):+ yield {"title": item.css('h2::text').get()}++MySpider().start()+```++- **واجهة عناكب شبيهة بـ Scrapy**: عرّف العناكب باستخدام `start_urls` ودوال callback غير متزامنة باسم `parse` وكائنات `Request`/`Response` وطابور حسب الأولوية.+- **زحف بطلبات متزامنة**: يمكنك ضبط حدود التزامن، وسرعة الطلبات لكل نطاق، وفترات الانتظار بين التنزيلات.+- **دعم جلسات متعددة**: واجهة موحدة لطلبات HTTP والمتصفحات المتخفية التي تعمل دون واجهة داخل عنكبوت واحد. وجّه الطلبات إلى جلسات مختلفة حسب المعرّف. ويمكن تهيئة الجلسة عند أول استخدام فقط.+- **الإيقاف المؤقت والاستكمال**: حفظ حالة الزحف باستخدام نقاط الاستكمال. اضغط Ctrl+C للإغلاق المنظم، ثم شغّل العنكبوت مجددًا ليكمل من حيث توقف.+- **وضع البث**: استقبل البيانات فور استخراجها عبر `async for item in spider.stream()` مع إحصاءات مباشرة. يناسب واجهات المستخدم ومسارات معالجة البيانات وعمليات الزحف الطويلة.+- **اكتشاف الطلبات المحظورة**: اكتشاف الطلبات المحظورة وإعادة المحاولة تلقائيًا، مع إمكانية تخصيص المنطق.+- **تصدير مدمج**: صدّر النتائج عبر دوال hooks ومسار معالجة البيانات الذي تنشئه، أو إلى JSON/JSONL باستخدام `result.items.to_json()` / `result.items.to_jsonl()` على الترتيب.+- **دوال مراحل التشغيل**: `on_start()` و`on_close()` و`on_error()` و`on_scraped_item()` وغيرها للتحكم الكامل في مراحل الزحف.+- **إحصاءات زحف مفصلة**: تتبّع الطلبات والردود والبايتات وأكواد الحالة والبروكسي، وتفاصيل كل نطاق وجلسة، وعدد رسائل كل مستوى من مستويات السجل، وغيرها.+- **دعم uvloop**: مرّر `use_uvloop=True` إلى `spider.start()` لتسريع التنفيذ غير المتزامن عند توفره.++أُضيف قسم جديد إلى الموقع يحتوي على التفاصيل الكاملة. اضغط [هنا](spiders/architecture.md)++### 🔄 تدوير البروكسي {#v0.4-proxy-rotation}++* كلاس `ProxyRotator` جديد يدعم التدوير بأمان بين الخيوط. يعمل مع جميع أدوات الجلب والجلسات:++ ```python+ from scrapling import ProxyRotator+ rotator = ProxyRotator(["http://proxy1:8080", "http://proxy2:8080"])+ Fetcher.get(url, proxy_rotator=rotator)+ ```++* **طرق تدوير مخصّصة**: أنشئ منطق تدوير البروكسي الخاص بك+* **تغيير البروكسي لطلب واحد**: مرّر `proxy=` إلى أي استدعاء منفرد لـ `get()`/`post()`/`fetch()` لاستخدام بروكسي مختلف عن بروكسي الجلسة في هذا الطلب.++### 🌐 تحسينات أدوات الجلب بالمتصفح {#v0.4-browser-fetcher-improvements}++* **حظر النطاقات**: معامل `blocked_domains` جديد في `DynamicFetcher`/`StealthyFetcher` لحظر الطلبات إلى نطاقات محددة، ويشمل نطاقاتها الفرعية تلقائيًا.+* **إعادة المحاولة تلقائيًا**: تعيد أدوات الجلب بالمتصفح المحاولة الآن عند الفشل باستخدام المعاملين `retries` (الافتراضي: 3) و`retry_delay` (الافتراضي: 1s). ويشمل ذلك اكتشاف الأخطاء المرتبطة بالبروكسي.+* **بيانات الرد الإضافية**: يحفظ قاموس `Response.meta` البروكسي المستخدم تلقائيًا، ويدمج بيانات الطلب الإضافية.+* **Response.follow()**: إنشاء كائنات `Request` للمتابعة مع ضبط referer تلقائيًا، وهي مصمّمة لنظام العناكب.+* **منع التشغيل التلقائي**: تحظر جلسات المتصفح الآن تشغيل المحتوى تلقائيًا، لأنه كان يسبب مشكلات من قبل.+* **السرعة**: تحسين التخفي والسرعة بضبط خيارات تشغيل المتصفح.++### 🔧 إصلاحات الأخطاء والتحسينات {#v0.4-bug-fixes-improvements}+- **تحسين محلل الصفحات**: تحسين العمليات المتكررة في المحلل لرفع الأداء.+- **الصفحات التي تعطي أخطاء**: إصلاح خطأ كان يمنع إغلاق المتصفح عندما تعطي الصفحات أخطاء.+- **محتوى فارغ**: التعامل مع الردود التي لا تحتوي على محتوى.+- **حلقة Playwright**: حل مشكلة بقاء حلقة Playwright مفتوحة عند فشل اتصال CDP+- **سلامة الأنواع**: إصلاح جميع أخطاء mypy وإضافة تلميحات الأنواع داخل الدوال التي لم تكن تحدد الأنواع. وإضافة mypy وpyright إلى workflow الخاص بـ CI.++### ⚠️ تغييرات قد تؤثر في الكود الحالي {#v0.4-breaking-changes}++* **إزالة `css_first`/`xpath_first`**: استخدم `css('.selector').first` أو `css('.selector')[0]` أو `css('.selector').get()` بدلًا منهما.+* **جميع عمليات الاختيار تعيد `Selectors` الآن**: تعيد `css('::text')` و`xpath('//text()')` و`css('::attr(href)')` و`xpath('//@href')` الآن `Selectors`، مع تغليف العقد النصية في كائنات `Selector` لها `tag="#text"`، بدلًا من `TextHandlers`. يجعل هذا API متسقًا في جميع طرق الاختيار وتلميحات الأنواع.+* **`Response.body` دائمًا من نوع `bytes`**: كان من الممكن أن يكون `str` أو `bytes`، لكنه يعيد الآن `bytes` دائمًا.+* **سلوك `get()`/`getall()`**: في `Selector`: تعيد `get()` كائن `TextHandler`، أي HTML محوّلًا إلى نص أو القيمة النصية، وتعيد `getall()` كائن `TextHandlers`. الأسماء البديلة: `extract_first = get` و`extract = getall`. أُزيلت `get_all()` القديمة من `Selectors`.+* **`Selectors.first`/`.last`**: وصول آمن يعيد `Selector | None` بدلًا من إصدار `IndexError`.+* **تغيير أسماء الثوابت الداخلية**: `DEFAULT_FLAGS` → `DEFAULT_ARGS` و`DEFAULT_STEALTH_FLAGS` → `STEALTH_ARGS` و`HARMFUL_DEFAULT_ARGS` → `HARMFUL_ARGS` و`DEFAULT_DISABLED_RESOURCES` → `EXTRA_RESOURCES`.++### 🔨 تغييرات أخرى {#v0.4-other-changes}++* **تغييرات المتطلبات**: استبدال `tldextract` بـ `tld`، وإزالة `_html_utils.py` الداخلية واستخدام `w3lib.html.replace_entities` بدلًا منها، وإضافة `typing_extensions` كمتطلب أساسي.+* **تحديث شامل للتوثيق**: الانتقال الكامل من MkDocs إلى Zensical، وإضافة قسم لتوثيق العناكب، وتحديث جميع الصفحات الحالية، وإضافة مراجع API جديدة.++## [v0.3.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.14) - 2026-01-03 {#v0.3.14}++**تحديث صيانة صغير لإصلاح مشكلات ظهرت على بعض الأجهزة في v0.3.13**++- تعطيل وضع التصفح الخاص في `StealthyFetcher` وكلاسات جلساته، لأنه كان يمنع بقاء ملفات تعريف الارتباط بين الصفحات على أجهزة Windows. لم تظهر هذه المشكلة على MacOS وLinux (يصلح [#123](https://github.com/D4Vinci/Scrapling/issues/123)، شكرًا @frugality4121 على الإبلاغ عنها و@gembleman على توضيح الحل).+- تثبيت أحدث إصدار من browserforge لحل مشكلة نماذج headers القديمة لدى المستخدمين الذين لديهم إصدار قديم من browserforge.++## [v0.3.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.13) - 2026-01-01 {#v0.3.13}++**تحديث كبير مع تحسينات في أجزاء كثيرة، ومعه تغييرات كثيرة قد تؤثر في الكود الحالي لأسباب مهمة. يرجى قراءة ما يلي قبل التحديث**++* قررنا لأسباب كثيرة التوقف تمامًا عن استخدام Camoufox من الآن، وقد نعود إليه في المستقبل إذا استمر تطويره. إذا كنت تفضّل الاستمرار في استخدام Camoufox كما كان قبل هذا الإصدار، فستجد التعليمات في هذا [القسم](https://github.com/D4Vinci/Scrapling/blob/v0.3.13/docs/fetching/stealthy.md#using-camoufox-as-an-engine).++* كنا نستخدم patchright في وضع التخفي داخل `DynamicFetcher` وكلاسات جلساته. أزلنا الآن وضع التخفي منها وبدأنا استخدام patchright داخل `StealthyFetcher` وكلاسات جلساته، مع تحسينات كثيرة جدًا كما سترى، لتحسين التخفي فوق ما يقدمه patchright.++**يجعل هذا `StealthyFetcher` وكلاسات جلساته أسرع بنسبة 101%، مع استهلاك أقل للذاكرة والمساحة وكود أقصر بنحو ~400 سطر. والأهم أنها أصبحت أكثر استقرارًا مقارنة باستخدام Camoufox من قبل.**++سيقلل ذلك أيضًا وقت التثبيت عبر الأمر `scrapling install`، وحجم صورة Docker، ويحسن سير الاختبارات في CI على GitHub، ويجعل scrapling أوضح للمستخدمين الجدد.++### تغييرات قد تؤثر في الكود الحالي {#v0.3.13-breaking-changes}+1. أُزيل المعامل `stealth` من كلاس `DynamicFetcher` وكلاس جلسته، ونُقل المعامل `hide_canvas` إلى `StealthyFetcher` وكلاسات جلساته.+2. نُقل المعامل `disable_webgl` من `DynamicFetcher` إلى كلاس `StealthyFetcher` وتغير اسمه إلى `allow_webgl`. وينطبق ذلك على جميع كلاسات الجلسات أيضًا.+3. أصبح كلاس `StealthyFetcher` هو النسخة المتخفية الجديدة من `DynamicFetcher`، لذا أُزيلت المعاملات التالية: `block_images` و`humanize` و`addons` و`os_randomize` و`disable_ads` و`geoip`. حاولت توفيرها في Chromium، لكن لكل منها مشكلة خاصة بها. قد يتغير هذا في الإصدارات القادمة قبل v0.4.++والآن إلى الأخبار الجيدة، فقد أجرينا تحسينات وإصلاحات كثيرة :)++### التحسينات {#v0.3.13-improvements}+- تعرف بالفعل أن كلاس `StealthyFetcher` وكلاسات جلساته أصبحت أسرع بنسبة 101%، لكن كلاس `DynamicFetcher` وكلاس جلسته أصبحا أسرع بنسبة 20% أيضًا.+- تحسين خوارزمية حل تحديات Cloudflare لتعمل أسرع وتتعامل مع حالات أكثر. وبفضل إعادة تنظيم الكود، يمكنك توقع حل captcha بضعف السرعة!+- جميع أدوات الجلب تستهلك الآن ذاكرة أقل.+- خادم MCP يستخدم الآن توكنات أقل لتوفير المزيد من المال!+- أصبحت صورة Docker أصغر بنسبة 60%.+- تحديث موقع التوثيق بالكامل بالمزايا الجديدة. وجعل الشرح أوضح، واختصار أقسام كثيرة، وإضافة أمثلة أكثر والمعاملات التي كانت ناقصة، وتحديث قسم مرجع API برسوم توضيحية، وإجراء تحسينات أخرى كثيرة. أصبح الموقع الآن أسرع في التحميل بنسبة 130%، ويستهلك بيانات أقل، وأفضل لمحركات البحث SEO.++### الإصلاحات {#v0.3.13-fixes}+- إضافة المعاملات التي كانت ناقصة في اختصارات Web Scraping shell وجعلها أدق.+- إصلاح مشكلة كان فيها المعامل `google_search` ينشئ Google referrer حتى لو كان عنوان URL يشير إلى localhost/IP.++## [v0.3.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.12) - 2025-12-18 {#v0.3.12}++### ما الذي تغير {#v0.3.12-what-s-changed}+- إضافة معامل جديد إلى كلاسَي `DynamicSession`/`AsyncDynamicSession` باسم `timezone_id`، يتيح ضبط المنطقة الزمنية للمتصفح لتطابق منطقة البروكسي/VPN الذي تستخدمه. بهذه الطريقة، لا تستطيع المواقع اكتشاف استخدامك للبروكسي من اختلاف المنطقة الزمنية.+- تحسين التحويل التلقائي للرد إلى JSON.+- تغيير اسم الدالة الداخلية `__create__` إلى `start` داخل كلاسات جلسات أدوات الجلب لتسهيل استخدامها خارج سياق `with`.+- تحديث `curl_cffi` والمتطلبات الأخرى إلى أحدث الإصدارات.++## [v0.3.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.11) - 2025-12-03 {#v0.3.11}++### ما الذي تغير {#v0.3.11-what-s-changed}+- تحسين منطق التعامل مع أخطاء انتهاء المهلة عند استخدام المعامل `network_idle` مع موقع غير مستقر، مثل المواقع التي تشغّل وسائط باستمرار.+- إصلاح الإكمال التلقائي للاختصار `stealthy_fetch` في Web Scraping Shell++## [v0.3.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.10) - 2025-11-26 {#v0.3.10}++**تحديث صيانة مع تغييرات مهمة كثيرة، وبعضها قد يؤثر في الكود الحالي**++- **حل** جميع مشكلات الترميز باستخدام طريقة أفضل تتعامل مع صفحات الويب التي لا تحدد الترميز بصورة صحيحة (شكرًا @Kemsty2 على الجهد المبذول في توضيح المشكلة في [#110](https://github.com/D4Vinci/Scrapling/issues/110) [#111](https://github.com/D4Vinci/Scrapling/pull/111) )+- **حل** مشكلة منطقية في استبدال معاملات الجلسة بمعاملات الطلب في جميع أدوات الجلب بالمتصفح، وكانت موجودة منذ v0.3+- **إصلاح** تعريفات اختصارات shell التفاعلي لاستخراج البيانات من الويب، مما جعل الإكمال التلقائي لهذه الاختصارات يعمل بصورة كاملة. كانت هذه المشكلة موجودة منذ v0.3 أيضًا.+- **تحديث** إصدار قاعدة بيانات Maxmind، مما يحسن عمل المعامل `geoip` في `StealthyFetcher` وكلاسات جلساته.+- **تحديث** جميع المتصفحات المستخدمة إلى أحدث الإصدارات المتاحة.+- **تغييرات قد تؤثر في الكود الحالي** - أُعيد تنظيم جميع أدوات الجلب بشكل كبير، مما نتج عنه تغييرات مهمة قد تؤثر في كودك:+ 1. أصبح كود Scrapling أقصر بنحو ~750 سطرًا، مع تغييرات كثيرة تجعل صيانته أسهل في المستقبل وتقلل استهلاك الموارد قليلًا.+ 2. أصبح التحقق من المعاملات أسرع بكثير في جميع أدوات الجلب وكلاسات جلساتها، مما يرفع سرعتها عمومًا.+ 3. لتحقيق ذلك، لم تعد أدوات الجلب تقبل معاملات موضعية غير المعامل `url`. يجب تمرير بقية المعاملات بأسمائها، فيكون كودك مثل `Fetcher.get('https://google.com', stealthy_headers=True)` وليس `Fetcher.get('https://google.com', True)` إذا كنت تفعل ذلك لأي سبب!+ 4. كان هناك اختلاف مزعج بين أدوات الجلب بالمتصفح وكلاسات جلساتها منذ v0.3: المعامل المستخدم لتمرير إعدادات مخصّصة للمحلل لكل طلب كان اسمه `custom_config`، بينما كان اسمه `selector_config` في كلاسات الجلسات. أتاحت إعادة تنظيم الكود توحيد الاسم إلى `selector_config` دون تعطيل كودك، ليصبح الاسم الأساسي الآن `selector_config` مع استمرار دعم المعامل القديم `custom_config`. سيتوفر الإكمال التلقائي للمعامل `selector_config` فقط.+ 5. ولتحقيق كل ذلك، أصبح من الضروري توليد تلميحات الأنواع لدوال أدوات الجلب تلقائيًا. إذا لم يعمل الإكمال التلقائي جيدًا في IDE، فتأكد من استخدام إصدار حديث منه. اختبرنا تقريبًا جميع بيئات التطوير والمحررات المعروفة.++> حدّثنا أيضًا جميع جداول قياس الأداء بالأرقام الحالية، مع المقارنة بأحدث إصدارات جميع المكتبات البديلة.++## [v0.3.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.9) - 2025-11-17 {#v0.3.9}++**تحديث جديد مع تغييرات مهمة كثيرة**++### 🚀 الجديد وتحسينات الاستخدام {#v0.3.9-new-stuff-and-quality-of-life-changes}+- يقبل المعامل `impersonate` في `Fetcher` و`FetcherSession` الآن قائمة متصفحات تختار منها المكتبة متصفحًا عشوائيًا مع كل طلب.++```python+from scrapling.fetchers import FetcherSession++with FetcherSession(impersonate=['chrome', 'firefox', 'safari']) as s:+ s.get('https://github.com/D4Vinci/Scrapling')+```++- إضافة معامل جديد إلى الدالة `clean` في `TextHandler` لإزالة HTML entities من النص الحالي بسهولة.+- تحسينات كبيرة في التوثيق مع شرح أدق لأجزاء كثيرة وترجمات آلية لملف `README.md` الرئيسي.++### 🐛 إصلاحات الأخطاء {#v0.3.9-bug-fixes}+- إصلاح مشكلة كبيرة في استرجاع الردود من أدوات الجلب بالمتصفح. يوجد الآن اكتشاف ذكي لنوع المحتوى، يضمن أن `response.body` يحتوي على المحتوى الذي عرضه المتصفح فقط إذا كان المحتوى HTML. وفي غير ذلك، يحتوي على المحتوى الخام لآخر طلب. يتيح هذا تنزيل الملفات الثنائية والنصية دون تغليفها بوسوم HTML، مع الاحتفاظ بإمكانية استرجاع محتوى الموقع بعد عرضه في المتصفح عند جلبه.++### 🔨 تغييرات متنوعة {#v0.3.9-misc}+- تحديث دليل المساهمة ليكون أوضح وأسهل.+- إضافة workflow جديد لفرض استخدام أدوات جودة الكود، وهي الأدوات نفسها المستخدمة في pre-commit hooks.++## [v0.3.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.8) - 2025-10-27 {#v0.3.8}++**تحديث جديد مع تغييرات مهمة كثيرة**++### 🚀 الجديد وتحسينات الاستخدام {#v0.3.8-new-stuff-and-quality-of-life-changes}+- في جميع أدوات الجلب بالمتصفح: لن تتسبب المواقع التي لا تنتهي طلباتها من التحميل في تعطل الكود عند استخدام `network_idle` معها.+- تغيير منطق جمع محتوى الصفحة والتحقق منه في أدوات الجلب بالمتصفح، لجعل المتصفحات على Windows مستقرة مثل Linux/MacOS. يرجع هذا الاختلاف في السلوك إلى اختلاف طريقة عمل Playwright على Windows.+- إعادة تنظيم منطق التحقق من المعاملات بالكامل، مما جعل الطلبات في جميع أدوات الجلب بالمتصفح أسرع بنسبة 8-15%+- إضافة خيار جديد باسم `extra_flags` إلى `DynamicFetcher` وجلسته، ليتيح إضافة خيارات Chrome مخصّصة إلى الخيارات الحالية عند تشغيل المتصفح.+- إعادة منطق توجيه الطلبات لالتقاط الردود، الذي تغير في الإصدار السابق، إلى الطريقة القديمة عند استخدام `page_action`. يتيح هذا جمع أحدث محتوى للصفحة إذا غيّره `page_action` دون إرسال طلب. (شكرًا @gembleman على توضيح ذلك في [#100](https://github.com/D4Vinci/Scrapling/issues/100) و[#102](https://github.com/D4Vinci/Scrapling/pull/102) )++### 🐛 إصلاحات الأخطاء {#v0.3.8-bug-fixes}+- إصلاح خطأ كتابي في `load_dom` داخل async_fetch في DynamicSession+- إصلاح مشكلة في أداة حل تحديات Cloudflare كانت تجعلها تنتظر دون نهاية عند التعامل مع captcha مضمنة لا تختفي بعد حلها. تنتظر الآن 30 ثانية حتى تختفي، ثم تفترض أنها من النوع الذي لا يختفي (يصلح #100 )++### 🔨 تغييرات متنوعة {#v0.3.8-misc}+- تُرفع صورة Docker الآن تلقائيًا إلى Dockerhub وسجل الحاويات في GitHub لتسهيل استخدامها.+- إضافة [صفحة توثيق جديدة](https://github.com/D4Vinci/Scrapling/blob/v0.3.8/docs/tutorials/external.md) توضح كيفية استخدام متصفح Scrapeless مع Scrapling.++## [v0.3.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.7) - 2025-10-12 {#v0.3.7}++**تحديث جديد مع تغييرات مهمة كثيرة**++### 🚀 الجديد وتحسينات الاستخدام {#v0.3.7-new-stuff-and-quality-of-life-changes}+- إعادة تصميم المعامل `solve_cloudflare` في `StealthyFetcher` ليحل جميع صور الاستخدام المخصّص لـ Turnstile.+- إعادة تنظيم الكود بالكامل ليقبله Pyright، لتحسين العمل في جميع بيئات التطوير وحل أخطاء كثيرة.+- إعادة تنظيم منطق الطلبات ليكون أبسط وأسرع (يحل #97 أيضًا )+- إضافة خيار جديد باسم `user_data_dir` إلى جميع كلاسات جلسات المتصفح، ليتيح إعادة استخدام بيانات المتصفح من جلسات سابقة، مثل cookies والتخزين وغيرها. تركه دون قيمة يجعل Playwright يستخدم مجلدًا عشوائيًا في كل تشغيل، كما كان يحدث من قبل.+- إضافة خيار تخصيص جديد باسم `additional_args` إلى `Dynamic fetcher` وكلاس جلسته، لتمرير معاملات إضافية إلى سياق Playwright، كما كان متاحًا من قبل مع `StealthyFetcher`.+- تحسين منطق توجيه الطلبات لجمع آخر رد ناتج عن التنقل في جميع المتصفحات، مما يتيح تمرير الردود الخام إلى المحلل قبل أن تعالجها المتصفحات كما كان يحدث من قبل. يفيد هذا كثيرًا مع الردود النصية وردود JSON.++### 🐛 إصلاحات الأخطاء {#v0.3.7-bug-fixes}+- حل تغيير منطق توجيه الطلبات مشكلة استرجاع محتوى المواقع غير المستقرة على بعض أجهزة Windows.+- أدت إعادة تنظيم الكود في هذا الإصدار إلى حل أخطاء كثيرة كان من الصعب ملاحظتها، ومشكلات غريبة في الإكمال التلقائي ببعض بيئات التطوير.+- إصلاحات كثيرة في موقع التوثيق++## [v0.3.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.6) - 2025-10-01 {#v0.3.6}++### 🚀 الجديد {#v0.3.6-new-stuff}+- تحسين المعامل `solve_cloudflare` في `StealthyFetcher` وكلاسات جلساته ليحل جميع أنواع Turnstile وتحديات Cloudflare التي تظهر في صفحة وسيطة 🎉+- خادم MCP يدعم الآن خيار `Streamable HTTP`، لتسهيل إتاحة الخادم عبر الشبكة.+- إضافة دعم Docker، مع بناء صورة ورفعها تلقائيًا إلى Docker Hub مع كل إصدار، وتشمل جميع المتصفحات++### 🐛 إصلاحات الأخطاء {#v0.3.6-bug-fixes}+- إصلاح مشكلة ترميز في المحلل كانت تحدث في بعض الحالات، وهي رسالة الخطأ المعروفة `invalid start byte`+- إعادة تنظيم أجزاء متعددة من المكتبة لإصلاح بعض حالات تسرب الذاكرة، مما يقلل استهلاك الذاكرة بصورة ملحوظة حسب إعداداتك (يحل #92 أيضًا )+- تحسين تلميحات الأنواع في أجزاء كثيرة من الكود لتسهيل العمل في IDE (يحل #93 أيضًا )++## [v0.3.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.5) - 2025-09-20 {#v0.3.5}++**إصدار ضروري لإصلاح عدة مشكلات**++### 🚀 الجديد {#v0.3.5-new-stuff}+- جميع أدوات الجلب بالمتصفح (`DynamicFetcher`/`StealthyFetcher`/...) وكلاسات جلساتها تجلب المواقع الآن أسرع بنسبة 15-20%:+ 1. أصبحت إدارة الصفحات أسرع بكثير بفضل تحسين المنطق من @AbdullahY36 في #87+ 2. تحسين منطق التحقق من المعاملات عمومًا، وتحسين إنشاء الصفحات في عمليات الجلب المتزامنة. أدت هذه التغييرات معًا إلى تحسينات كبيرة في السرعة++- تحسينات كبيرة لوضع التخفي في `DynamicFetcher` وكلاسات جلساته باستبدال `rebrowser-playwright` بـ `PatchRight`:+ 1. قبل هذا التحديث، كان `rebrowser-playwright` يتوقف عند تفعيل `stealth` و`real_chrome` لأنهما لم يكونا يعملان جيدًا معًا. لم تعد هذه المشكلة موجودة مع `PatchRight`+ 2. يمكنك الآن التعامل مع Closed-Shadow Roots لأن `PatchRight` يتعامل معها تلقائيًا.++### 🐛 إصلاحات الأخطاء {#v0.3.5-bug-fixes}+- إصلاح خطأ يحدث عند استخدام الدالة `re` من كلاس `Selectors`.+- إصلاح خطأ في أمرَي `uncurl` و`curl2fetcher` في Web Scraping Shell كان يسبب تحليلًا غير صحيح لخيار curl المسمى `--data-raw`.+- إصلاح خطأ في الأمر `view` في Web Scraping Shell كان ظهوره مرتبطًا بترميز الموقع.+- إصلاح خطأ في تحويل المحتوى كان يؤثر في وضع `mcp` وأوامر `extract`.++### مساهمون جدد {#v0.3.5-new-contributors}+- قدّم @AbdullahY36 أول مساهمة له في #87++## [v0.3.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.4) - 2025-09-16 {#v0.3.4}++**إصدار ضروري لإصلاح عدة مشكلات**++### 🚀 الجديد {#v0.3.4-new-stuff}+- إضافة جميع كلاسات جلسات أدوات الجلب إلى shell التفاعلي لتكون متاحة مباشرة دون استيراد.++### 🐛 إصلاحات الأخطاء {#v0.3.4-bug-fixes}+- إضافة حل بديل لخطأ في Playwright API على Windows كان يحدث عند استرجاع المحتوى أثناء حل تحديات Cloudflare.+- إصلاح مشكلة ترميز في الأمر `view` داخل shell التفاعلي+- إصلاح خطأ في المعامل `max_pages` في `AsyncStealthySession` كان يتسبب في تعطل الكود.+- إصلاح مشكلة ظهرت مع التحديثات الأخيرة وجعلت الخاصيتين `html_content` و`prettify` في كلاس `Selector` تعيدان bytes حسب الترميز. عادتا إلى إرجاع نصوص كما كانتا.++## [v0.3.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.3) - 2025-09-15 {#v0.3.3}++- إزالة منطق إغلاق تبويب المتصفح الافتراضي من أدوات الجلب بالمتصفح لأنه تسبب في خطأ يعطّل الكود. لم يحدث على Mac، وأمكن تكراره على Windows وLinux فقط++## [v0.3.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.2) - 2025-09-15 {#v0.3.2}++ملاحظات إصدار v0.3.2++### 🚀 الجديد {#v0.3.2-new-stuff}++- **متطلبات اختيارية لأدوات الجلب**: أصبحت جميع أدوات الجلب ضمن مجموعات متطلبات اختيارية، لتقليل حجم الحزمة الأساسية. تحتوي حزمة `scrapling` الأساسية الآن على المحلل فقط، ولاستخدام أدوات الجلب أو خيارات سطر الأوامر، نفّذ: `pip install "scrapling[fetchers]"`. راجع تعليمات التثبيت المفصلة [هنا](index.md#installation)+- **إعدادات لكل صفحة داخل الجلسات**: تدعم كلاسات جلسات أدوات الجلب بالمتصفح الآن إعدادات منفصلة لكل صفحة في الجلسة. يجري التحقق من جميع معاملات الجلب مثل معاملات الجلسة. التفاصيل على موقع التوثيق [هنا](fetching/stealthy.md#full-list-of-arguments)+ <br>مثال:++ ```python+ with StealthySession(headless=True, solve_cloudflare=True) as session:+ page = session.fetch('https://nopecha.com/demo/cloudflare', google_search=False)+ ```++- **تحسين أدوات الجلب بالمتصفح**+ - خيار جديد للتحكم في انتظار انتهاء تنفيذ JavaScript في الصفحات. الخيار مفعّل افتراضيًا الآن، كما كان من قبل++ ```python+ with DynamicSession(headless=True, disable_resources=False, network_idle=True) as session:+ page = session.fetch('https://quotes.toscrape.com/', load_dom=False)+ ```++ - أصبح وضع التخفي أكثر موثوقية في `DynamicFetcher` وكلاسات جلساته.+ - يستخدم `DynamicFetcher` و`StealthyFetcher` الآن موارد أقل، باكتشاف التبويب الافتراضي الذي تفتحه السياقات الدائمة في Playwright API وإغلاقه تلقائيًا+ - إصلاح خطأ مهم في منطق تدوير الصفحات بأدوات الجلب بالمتصفح. تُستبدل الصفحات السابقة الآن بصفحات جديدة، لأن التبويبات التي يُعاد استخدامها قد تحتفظ بآثار الإعدادات السابقة+ - أصبح `StealthyFetcher` وكلاسات جلساته أسرع قليلًا (5%)++- **تحسين الخاصية `.body`**: تعيد الآن المحتوى الممرّر كما هو دون معالجة، مما يتيح تنزيل الملفات والتعامل مع الطلبات التي لا تعيد HTML. المثال التالي يوضح تنزيل صورة:++ ```python+ from scrapling.fetchers import Fetcher++ page = Fetcher.get('https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/poster.png')+ with open(file='poster.png', mode='wb') as f:+ f.write(page.body)+ ```++### 🐛 إصلاحات الأخطاء {#v0.3.2-bug-fixes}++- **حل مشكلات الترميز**: إصلاح مشكلات ترميز متعددة ظهرت مع بعض المواقع في المحلل ووضع mcp وأوامر extract (يحل #80 و#81 أيضًا)+- **تحليل أسرع**: بفضل تغييرات كثيرة في أجزاء مختلفة، أصبحت المكتبة أسرع، وهو ما يظهر في نتائج قياس الأداء المحدّثة++### 🔨 تغييرات متنوعة {#v0.3.2-misc}++- **تحديث قياسات الأداء**: تحديث القياسات لمقارنة تحسينات السرعة الحالية بأحدث إصدارات المكتبات المشابهة+- **إعادة تنظيم أجزاء كثيرة من الكود واستبدال الكود غير المستخدم بطرق أفضل**: كود أقل وأبسط وصيانة أسهل+- **إضافة فيديو YouTube**: إضافة محتوى فيديو إلى توثيق MCP.+- **نموذج جديد للمشكلات**: نموذج جديد وسهل للمستخدمين الذين لا يستطيعون استخدام النماذج الحالية.+- **تحسين workflow الخاص بـ CI**: تتجاوز اختبارات workflow التشغيل الآن عندما تقتصر التغييرات على التوثيق أو الملفات التي لا تحتوي على كود.+- **تحديث المتطلبات**: تحديث متطلبات مختلفة إلى أحدث الإصدارات.+- **تحسين أسلوب الكود**: تطبيق قواعد ruff جديدة على جميع الملفات.+- **Pre-commit hooks**: تحديث إعدادات pre-commit.++### 🎯 تغييرات قد تؤثر في الكود الحالي {#v0.3.2-breaking-changes}++- إزالة المعامل `max_pages` من النسخة المتزامنة من `StealthySession` لتطابق `DynamicSession`، لأنه لا فائدة منه في النسخة المتزامنة++## [v0.3.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.1) - 2025-09-02 {#v0.3.1}++1. إصلاح مشكلة في تثبيت scrapling عند تثبيته دون الإضافة `shell` (#76 )+2. إضافة معامل جديد إلى جميع أدوات الجلب بالمتصفح وكلاسات جلساتها لإضافة ملف JS يُنفّذ عند إنشاء الصفحة (#56) :++```python+from scrapling.fetchers import StealthyFetcher++StealthyFetcher.fetch('https://example.com', init_script="/absolute/path/to/js/script.js")+```++## [v0.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3) - 2025-09-01 {#v0.3}++🎉 **إصدار رئيسي - إعادة بناء كاملة**++يمثل Scrapling v0.3 أكبر تحديث في تاريخ المشروع. يشمل إعادة كتابة كاملة للبنية، وتحسينات كبيرة في الأداء، وميزات قوية جديدة، منها التكامل مع الذكاء الاصطناعي وبيئة تفاعلية لاستخراج البيانات من الويب.++يتضمن هذا الإصدار عدة تغييرات قد تؤثر في الكود الحالي. اقرأ ملاحظات الإصدار بعناية.++### 🚀 أهم الميزات الجديدة {#v0.3-major-new-features}++#### بنية تعتمد على الجلسات {#v0.3-session-based-architecture}+- **فئات جديدة للجلسات**: إعادة كتابة كاملة لإضافة دعم الجلسات التي تبقى مفتوحة+ - `FetcherSession` - طلبات HTTP مع حفظ حالة الجلسة، وتعمل مع الكود المتزامن وغير المتزامن+ - `DynamicSession`/`AsyncDynamicSession` - أتمتة المتصفح مع إبقائه مفتوحًا حتى تنتهي+ - `StealthySession`/`AsyncStealthySession` - تصفح متخفٍ مع إبقاء المتصفح مفتوحًا حتى تنتهي+- **إدارة تبويبات المتصفح بشكل غير متزامن**: مجموعة جديدة من التبويبات عبر الخيار `max_pages`، يعاد استخدامها بالتناوب لجلب الصفحات في الوقت نفسه+- **جلسات متوازية**: تشغيل عدة جلسات مستقلة في الوقت نفسه++راجع قسم `Fetching` في الموقع لمعرفة المزيد.++#### ميزات كثيرة جديدة للتخفي وتجاوز أنظمة مكافحة الروبوتات {#v0.3-a-lot-of-new-stealth-anti-bot-capabilities}+- **🤖 حل تحديات Cloudflare**: [حل تحديات Cloudflare Turnstile تلقائيًا](fetching/stealthy.md#cloudflare-and-stealth-options) في `StealthyFetcher` وفئات الجلسات الخاصة به+- **محاكاة بصمة المتصفح**: محاكاة بصمات TLS للمتصفحات الحقيقية، وترويسات تطابق إصدار المتصفح، ودعم HTTP/3، والمزيد مع فئة [Fetcher](fetching/static.md) الجديدة بالكامل+- **تحسين وضع التخفي**: أصبح وضع التخفي في `DynamicFetcher` وفئات الجلسات الخاصة به أقوى وأكثر موثوقية (المعروف أيضًا باسم `PlayWrightFetcher`)++#### التكامل مع الذكاء الاصطناعي وخادم MCP {#v0.3-ai-integration-mcp-server}+- **خادم MCP مدمج**: خادم Model Context Protocol لاستخراج البيانات من الويب بمساعدة الذكاء الاصطناعي+- **6 أدوات قوية**: `get`, `bulk_get`, `fetch`, `bulk_fetch`, `stealthy_fetch`, `bulk_stealthy_fetch`+- **استخراج ذكي للمحتوى**: تحويل صفحات الويب أو عناصرها إلى Markdown أو HTML، أو استخراج نسخة نظيفة من النص+- **دعم محددات CSS**: استخدام محرك Scrapling لتحديد عناصر معينة بدقة قبل إرسال المحتوى إلى الذكاء الاصطناعي+- **تجاوز أنظمة مكافحة الروبوتات**: التعامل مع Cloudflare Turnstile وغيرها من أنظمة الحماية+- **دعم البروكسي**: استخدام البروكسي لإخفاء الهوية والوصول إلى المواقع من مناطق جغرافية محددة+- **محاكاة المتصفحات**: محاكاة المتصفحات الحقيقية باستخدام بصمات TLS وترويسات متصفح حقيقية تطابق إصداره، والمزيد+- **معالجة متوازية**: استخراج البيانات من عدة روابط في الوقت نفسه لزيادة الكفاءة+- [والمزيد...](ai/mcp-server.md)++#### بيئة تفاعلية جديدة لاستخراج البيانات من الويب {#v0.3-new-interactive-web-scraping-shell}+- **بيئة تفاعلية جديدة**: بيئة IPython مخصصة مع اختصارات ذكية مدمجة كثيرة، مثل `get` و`post` و`put` و`delete` و`fetch` و`stealthy_fetch`+- **إدارة ذكية للصفحات**: أمران جديدان، `page` و`pages`، لحفظ الصفحة الحالية وسجل جميع الطلبات المنفذة عبر البيئة التفاعلية تلقائيًا+- **التكامل مع Curl**: استخدام الدالتين `uncurl` و`curl2fetcher` لتحويل أوامر curl من أدوات المطور في المتصفح إلى طلبات `Fetcher`+- [والمزيد...](cli/interactive-shell.md)++#### استخراج البيانات من الطرفية دون برمجة {#v0.3-scrape-from-the-terminal-without-programming}+- **أوامر جديدة لاستخراج البيانات**: استخراج البيانات من الطرفية دون برمجة+ - `scrapling extract get/post/put/delete` - طلبات HTTP بسيطة+ - `scrapling extract fetch` - استخراج المحتوى الديناميكي+ - `scrapling extract stealthy-fetch` - تجاوز أنظمة مكافحة الروبوتات+- **تنزيل صفحات الويب** وحفظ محتواها في ملفات.+- **تحويل HTML إلى صيغ سهلة القراءة** مثل Markdown، أو الاحتفاظ به كـ HTML، أو استخراج نص الصفحة فقط.+- **دعم محددات CSS مخصصة** لاستخراج أجزاء معينة من الصفحة.+- **التعامل مع طلبات HTTP وجلب الصفحات عبر المتصفحات.**+- **خيارات تخصيص كثيرة** للترويسات وملفات تعريف الارتباط والبروكسي وغيرها. معظم الخيارات المتاحة في الكود متاحة أيضًا من الطرفية.+- [والمزيد...](cli/extract-commands.md)++### 🔧 تحسينات تقنية {#v0.3-technical-improvements}++#### تحسينات الأداء {#v0.3-performance-enhancements}+- **Fetcher أسرع الآن 4 مرات** - نعم، قرأت ذلك بشكل صحيح!+- **DynamicFetcher أسرع الآن بنحو ~60%** - زيادة كبيرة في السرعة حسب إعداداتك (خاصة وضع التخفي)+- **StealthyFetcher أسرع الآن بنسبة 20–30%** - بفضل البنية الجديدة والبدء في استخدام الكود الخاص بنا بدلًا من واجهة Python في `Camoufox`+- **زيادة مجمعة في السرعة بنسبة 50%+** لدوال تحديد العناصر الأساسية (`find_by_text` و`find_similar` و`find_by_regex` و`relocate` وغيرها) 🚀+- **زيادة بنحو ~10% في سرعة دوال اختيار أول نتيجة من CSS/XPath** - أصبحت `css_first` و`xpath_first` أسرع من `css` و`xpath`+- **الدالة `get_all_text()` أسرع بنسبة 40%** عند استخراج المحتوى+- **زيادة في السرعة بنسبة 20%** عند العثور على العناصر مجددًا باستخدام الميزة التكيفية+- **تحسين خصائص التنقل** - أصبحت خصائص مثل `next` و`previous` و`below_elements` وغيرها أسرع بشكل ملحوظ+- **تنظيف النصوص أسرع 5 مرات**+- **تحسين استخدام الذاكرة** عبر تحسين الاستيراد وتقليل العمليات الإضافية+- **⚡ استيراد سريع جدًا**: تقليل وقت بدء التشغيل بتحسين تحميل الوحدات+- **نتائج أفضل في اختبارات الأداء**: جعلت تحسينات السرعة Scrapling أسرع بكثير من قبل مقارنة بالمكتبات الأخرى (أسرع من BeautifulSoup بمقدار 1775 مرة، ومن AutoScraper بمقدار 5.1 مرة، راجع [اختبارات الأداء](benchmarks.md))++#### تحسين البنية وجودة الكود وسهولة الاستخدام {#v0.3-architecture-code-quality-and-quality-of-life}+- **سياق متصفح دائم**: أصبحت كل أدوات جلب الصفحات عبر المتصفح تستخدم سياقًا دائمًا افتراضيًا. (يحل #64 أيضًا)+- **استخدام msgspec للتحقق بسرعة كبيرة من إعدادات كل أدوات جلب الصفحات عبر المتصفح** قبل تنفيذ الطلبات، لتسهيل اكتشاف الأخطاء.+- **كل ملفات تعريف الارتباط** التي تعيدها أدوات الجلب أصبحت بالتنسيق الذي تقبله الأداة نفسها. يمكنك استرجاعها وتمريرها مجددًا إلى كل أدوات الجلب وفئات جلساتها.+- **فحص الكود وتنسيقه أسرع** بعد الانتقال إلى `ruff`+- **نظام بناء حديث**: الانتقال من setup.py إلى pyproject.toml 📦+- **تحسين GitHub Actions وسير العمل** لتسهيل التطوير والاختبار+- **🎨 تحسين تلميحات الأنواع**: تغطية كاملة للأنواع وفق معايير Python الحديثة لتحسين دعم محررات الكود والموثوقية+- **كود أنظف**: إزالة الكود غير المستخدم وتحسين الدوال الأساسية 🧹+- **🚀 التوافق مع الإصدارات السابقة**: إضافة اختصارات للحفاظ على عمل الكود القديم++### تغييرات قد تؤثر في الكود الحالي {#v0.3-breaking-changes}++#### أقل إصدار مدعوم من Python {#v0.3-minimum-python-version}+- **يتطلب Python 3.10+**: إيقاف دعم Python 3.9 والإصدارات الأقدم++#### أسماء الفئات والدوال {#v0.3-class-and-method-naming}+تهدف تغييرات الأسماء إلى جعلها أوضح وأكثر اتساقًا، خاصة للمستخدمين الجدد.++- **`Adaptor` → `Selector`**: تغيير اسم فئة التحليل الأساسية (لا يزال استيرادها باسم `Adaptor` ممكنًا للتوافق مع الكود القديم)+- **`Adaptors` → `Selectors`**: تغيير اسم فئة المجموعة (لا يزال استيرادها باسم `Adaptors` ممكنًا للتوافق مع الكود القديم)+- **`auto_match` → `adaptive`**: تغيير اسم الخيار في جميع الدوال+- **`adaptor_arguments` → `selector_config`**: تغيير اسم خيار الإعدادات+- **`automatch_domain` → `adaptive_domain`**: تغيير اسم خيار النطاق+- **`additional_arguments` → `additional_args`**: اختصار اسم الخيار+- **⚠️ `text/body` → `content`**: أصبح خيار إنشاء Selector يقبل كلًا من `str` و`bytes`+- **`PlayWrightFetcher` → `DynamicFetcher`**: تغيير اسم فئة أتمتة المتصفح (لا يزال استيرادها باسم `PlayWrightFetcher` ممكنًا للتوافق مع الكود القديم)+- **إزالة الكود والخيارات الخاصة بـ NSTBrowser من DynamicFetcher** لعدم الحاجة إليها الآن.+- **لم يعد خيار headless في StealthyFetcher يقبل القيمة 'virtual'** لأن استخدام مكتبة Camoufox أصبح مقتصرًا على معرفة مسار تثبيت المتصفح وبقية خيارات تشغيله++### 🐛 إصلاحات الأخطاء {#v0.3-bug-fixes}++- إصلاح حساب العناصر الفرعية المتداخلة داخل الوسوم التي تتجاهلها `get_all_text` (#61)+- إصلاح مشكلة في التثبيت عند وجود مسافات في مسار ملف تشغيل Python (#57)+- إصلاح مشكلات خيوط التنفيذ في التخزين، مع التعامل مع الدوال التي تستدعي نفسها عند تفعيل الميزة التكيفية+- إصلاح أولوية الخيارات باستخدام نمط Sentinel في `FetcherSession`+- إصلاح التعامل مع أنواع البروكسي في `StealthyFetcher`+- إصلاح التعارض بين الخيارين `referer` و`google_search`+- إصلاح مشكلات حقن سكربتات التخفي في الكود غير المتزامن++## [v0.2.99](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.99) - 2025-04-08 {#v0.2.99}++**هذا تحديث مهم للجميع للاستفادة الكاملة من Scrapling كما صُممت.**++### ما الذي تغير {#v0.2.99-what-s-changed}+#### موقع جديد للتوثيق الكامل {#v0.2.99-new-full-documentation-website}+- نعم، أخيرًا 😄 يمكنك زيارته من [هنا](index.md)+#### طريقة موحدة لاستيراد أدوات جلب الصفحات {#v0.2.99-unified-import-logic-for-fetchers}+- يمكنك الآن استيراد جميع أدوات جلب الصفحات باستخدام `from scrapling.fetchers import Fetcher, AsyncFetcher, StealthyFetcher, PlayWrightFetcher`، ثم استخدامها مباشرة مثل `page = Fetcher.get(...)` دون إنشاء كائن أولًا.<br/> يحل هذا محل الاستيراد القديم `from scrapling.defaults import Fetcher, AsyncFetcher, StealthyFetcher, PlayWrightFetcher`.+#### تغيير قد يؤثر في الكود الحالي: تعطيل automatch افتراضيًا {#v0.2.99-breaking-change-automatch-is-now-turned-off-by-default}+- توجد الآن طريقة جديدة لتفعيل automatch من أدوات جلب الصفحات أو خيارات التحليل الأخرى. راجع [صفحة التوثيق](fetching/choosing.md#parser-configuration-in-all-fetchers) للتفاصيل.+> تظل طرق الاستيراد والاستخدام القديمة متاحة مع تحذير، للحفاظ على التوافق مع الكود القديم.+#### خيارات جديدة لأدوات جلب الصفحات {#v0.2.99-new-options-added-to-fetchers}+- أصبح لدى `StealthyFetcher` و`PlayWrightFetcher` خيار جديد عند جلب الصفحات باسم `wait`. يجعل الأداة تنتظر مدة محددة بالمللي ثانية قبل إغلاق الصفحة وإعادة الاستجابة إليك.+- أصبح `StealthyFetcher` يقبل في الدالتين `fetch` و`async_fetch` الخيار `additional_arguments` لتمرير إعدادات إضافية إلى Camoufox، وتكون لها أولوية أعلى من إعدادات Scrapling (#54 )+#### إصلاحات الأخطاء {#v0.2.99-bugs-squashed}+- إصلاح خطأ في التعامل مع عمليات إعادة التوجيه في `async_fetch` داخل الفئتين `StealthyFetcher` و`PlayWrightFetcher`.++**_شكرًا لكم على كل الدعم والتبرعات!_**++## [v0.2.98](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.98) - 2025-03-17 {#v0.2.98}++**هذا تحديث مهم للجميع للاستفادة الكاملة من Scrapling كما صُممت**++### ما الذي تغير {#v0.2.98-what-s-changed}+#### تحسينات متنوعة لاستخدام الذاكرة والسرعة {#v0.2.98-various-memory-usage-and-speed-optimizations}+- أصبح استخدام الذاكرة في جميع دوال تحديد العناصر نحو ~40% من الاستخدام السابق، مع زيادة بسيطة في السرعة.+- تطبيق التحميل عند الحاجة على كل الوحدات الفرعية للمكتبة، بحيث لا يُحمّل إلا ما تستخدمه، مثلًا:+قبل التحديث، كان الاستيراد `from scrapling import Adaptor` يستخدم `30-40mb` من الذاكرة لأنه يحمّل أيضًا كل أدوات الجلب وغيرها. الآن يستخدم `~1.2mb`.+- جعل التحديث السابق المكتبة تستخدم نحو ~32% من الذاكرة التي كانت تستخدمها مع مجموعة كبيرة من الطلبات. والآن حُسّن التخزين المؤقت أكثر لتستخدم ذاكرة أقل.+- زيادة بسيطة في السرعة العامة لمحلل الصفحات بنسبة 2-5%++**_شكرًا لكم على كل الدعم والتبرعات!_**++## [v0.2.97](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.97) - 2025-03-15 {#v0.2.97}++**هذا تحديث مهم للجميع للاستفادة الكاملة من Scrapling كما صُممت**++### ما الذي تغير {#v0.2.97-what-s-changed}+#### استخدام أقل للذاكرة وزيادة بسيطة في سرعة جميع أدوات جلب الصفحات {#v0.2.97-lower-memory-usage-and-small-speed-increase-across-all-fetchers}+- مع الحدود الجديدة لحجم التخزين المؤقت في المكتبة، ستلاحظ انخفاضًا كبيرًا في استخدام الذاكرة عند تنفيذ عدد كبير من الطلبات أو العمليات.+- إعادة تنظيم أجزاء كبيرة من أدوات جلب الصفحات لتسهيل صيانتها وزيادة سرعتها قليلًا.++#### إصلاحات الأخطاء {#v0.2.97-bugs-fixed}+- إصلاح خطأ في `TextHandler` كان يحوّل القيمة غير النصية إلى نص فارغ عند استيراده وحده. الآن تُحوّل أي قيمة تُمرر إلى `TextHandler` إلى نص أولًا، ثم إلى `TextHandler`. يُطبق ذلك على كل قيمة، فـ `TextHandler`، كما يدل اسمه، مخصص للتعامل مع النصوص فقط! (#45 )+- إصلاح خطأ كان يجعل معظم دوال AsyncFetcher تتجاهل الخيار `retries`.++#### تغييرات أخرى {#v0.2.97-miscellaneous}+- تحديث تلميحات الأنواع لمعظم الخيارات في جميع أدوات جلب الصفحات لتكون أوضح وأدق.++**_شكرًا لكم على كل الدعم والتبرعات!_**++## [v0.2.96](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.96) - 2025-03-05 {#v0.2.96}++**هذا تحديث مهم للجميع للاستفادة الكاملة من Scrapling كما صُممت**++### ما الذي تغير {#v0.2.96-what-s-changed}+1. إضافة الخيار `-f` إلى `scrapling install` لفرض إعادة تثبيت متطلبات المتصفح. أنصح بتشغيل `scrapling install -f` الآن للاستفادة من الزيادة الكبيرة في سرعة `StealthyFetcher` مع إصدار Camoufox الجديد :)+2. إصلاح خطأ في `TextHandler` كان يجعل أخذ جزء من النص يعيد `TextHandlers` بدلًا من `TextHandler`، مع تصحيح تلميح النوع (#41 )+3. إصلاح مشكلة كانت تجعل `scrapling install` يفتح بيئة Python التفاعلية في بعض الحالات!++## [v0.2.95](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.95) - 2025-02-25 {#v0.2.95}++**هذا تحديث مهم للجميع للاستفادة الكاملة من Scrapling كما صُممت**++### ما الذي تغير {#v0.2.95-what-s-changed}+1. إصلاح خطأ في `Fetcher` كان يجعل الترويسات الناتجة عن الخيار `stealthy_headers` تستبدل بعض الترويسات التي قدمها المستخدم، مثل `Accept` (#39 )+2. تحسين طريقة إنشاء الترويسات قليلًا، مما يُفترض أن يزيد السرعة بشكل بسيط.++## [v0.2.94](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.94) - 2025-02-22 {#v0.2.94}++**هذا تحديث مهم للجميع للاستفادة الكاملة من Scrapling كما صُممت**++### ما الذي تغير {#v0.2.94-what-s-changed}+1. إضافة الخاصية `history` إلى جميع أدوات جلب الصفحات لعرض عمليات إعادة التوجيه (#32 )+2. إصلاح طريقة عمل الخيار `case_sensitive` في جميع دوال `re`/`re_first`. قد يعيد الكود نتائج مختلفة إذا كنت تستخدمه (لكن ربما تستحق ذلك لأنك لاحظت أنه لا يعمل كما ينبغي ولم تبلغ عن المشكلة، ههه)+3. تحديث المكتبات المطلوبة وإعادة تفعيل `coop` في محرك Camoufox (StealthyFetcher).++## [v0.2.93](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.93) - 2025-01-31 {#v0.2.93}++**هذا تحديث مهم للجميع للاستفادة الكاملة من Scrapling كما صُممت**++### ما الذي تغير {#v0.2.93-what-s-changed}+1. أصبح نوع النتيجة متسقًا في محرك التحليل كله. ستكون النتيجة دائمًا من نوع `Adaptor` أو `Adaptors` أو `TextHandler` أو `TextHandlers` أو `None`، أو قائمة عند وجود نتائج مختلطة، مثل محدد CSS مركب. هذا يسهّل كتابة الكود ويقلل الحاجة إلى فحص الأنواع يدويًا، ويجعل المكتبة أكثر استقرارًا ويسمح دائمًا بتسلسل استدعاءات الدوال.+2. إعادة تنظيم معظم محرك التحليل، خاصة فئة `Adaptor`، لجعل الكود أنظف وأسرع. زادت سرعة معظم الدوال والخصائص، خاصة دوال البحث، بنسبة 5-40%. بعض الدوال حصلت على زيادة أكبر، مثل `find_by_regex` التي زادت سرعتها بنحو ~60%! وزادت سرعة ميزة automatch بنحو ~5%.+3. إصلاح أخطاء في الدالتين `find_all`/`find` كانت تجعل شروط التصفية تعمل بمنطق OR أحيانًا وAND أحيانًا أخرى. الآن يجب أن تحقق كل العناصر الناتجة جميع الشروط التي تمررها.+4. أصبحت كل الدوال المرتبطة بالتعبيرات النمطية تعيد `TextHandler`/`TextHandlers` لتسهيل تسلسل استدعاءات الدوال.+5. **إضافة خاصية جديدة** باسم `below_elements` تعيد كائن `Adaptors` يضم جميع العناصر الموجودة أسفل العنصر الحالي في شجرة DOM.+6. أصبحت كل الدوال والخصائص التي كانت تعيد كود HTML كنص تعيده الآن كـ `TextHandler`، لتسهيل استخدام التعبيرات النمطية عليه وغيرها من العمليات...+7. أصبح StealthyFetcher أسرع قليلًا وأفضل في التخفي. ويمكن الآن النقر على اختبارات Captcha داخل iframes، مثل **Cloudflare Turnstile**.+8. تحسين الإكمال التلقائي وتلميحات الأنواع كثيرًا في نحو نصف المكتبة، خاصة `Adaptor` و`TextHandler` و`TextHandlers`.+9. أصبح أخذ جزء من `TextHandler`، أو الوصول إلى حرف برقم موضعه، أو استخدام الدالة `split`، يعيد `TextHandler` آخر بدلًا من نص Python العادي. معظم عمليات ودوال النصوص القياسية تعيد الآن `Texthandler` بدلًا من النص العادي، للسماح دائمًا بتسلسل استدعاءات الدوال.+10. إصلاح بعض الأخطاء الصغيرة وأخطاء الكتابة. مثلًا، كانت async_put في Fetcher تنفذ طلب post بدلًا من put 😶🌫️+11. تحسين README قليلًا إلى أن أنتهي من موقع التوثيق.++كان من المفترض أن يكون هذا تحديثًا صغيرًا قبل الإصدار 0.3، لكنني قررت تحسينه أكثر.++## [v0.2.92](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.92) - 2024-12-26 {#v0.2.92}++### ما الذي تغير {#v0.2.92-what-s-changed}+- أصبحت الاستجابة التي تعيدها أدوات جلب الصفحات عبر المتصفح تعتمد على مصادر بيانات أكثر موثوقية عندما تحتوي الصفحة على كثير من Iframes.+- **أصبح تثبيت `Scrapling` أسهل: ثبّتها باستخدام pip، ثم شغّل `scrapling install` في الطرفية، وستكون جاهزًا!**+- تصحيح تلميح نوع غير دقيق في محلل الصفحات.++## [v0.2.91](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.91) - 2024-12-19 {#v0.2.91}++### ما الذي تغير {#v0.2.91-what-s-changed}+- إصلاح خطأ كان يجعل رسالة سجل جلب الصفحة تظهر مع الطلب الأول فقط.+- السلوك الافتراضي لـ Playwright API عند تصفح صفحة هو إعادة أول استجابة تحقق حالة التحميل المحددة للدالة `goto`: `["load", "domcontentloaded", "networkidle"]`. لذلك، إذا كان الموقع يعرض صفحة انتظار مثل صفحة Cloudflare ثم يعيد توجيهك إلى الموقع الحقيقي، يعيد Playwright رمز الحالة الأول، وقد يكون مثلًا 403. يحل هذا التحديث المشكلة في `PlaywrightFetcher` و`StealthyFetcher`، إذ يستخدم كلاهما Playwright API، ولم تعد النتيجة تعتمد على سلوكه الافتراضي.+- إضافة دعم بروكسي SOCKS في فئة `Fetcher`.+- تصحيح تلميح النوع للخيار `wait_selector_state`، ليعرض الإكمال التلقائي القيم الصحيحة التي يمكنك استخدامها.++## [v0.2.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.9) - 2024-12-16 {#v0.2.9}++### ما الذي تغير {#v0.2.9-what-s-changed}+##### ميزات جديدة {#v0.2.9-new-features}+1. إضافة دعم الكود غير المتزامن إلى Scrapling، وهو **ما انتظرناه طويلًا**! أصبحت فئة `AsyncFetcher` النسخة غير المتزامنة من `Fetcher`، وحصلت الفئتان `StealthyFetcher` و`PlayWrightFetcher` على دالة جديدة باسم `async_fetch` بالخيارات نفسها.++```python+>> from scrapling import StealthyFetcher+>> page = await StealthyFetcher().async_fetch('https://www.browserscan.net/bot-detection') # the async version of fetch+>> page.status == 200+True+```++2. أصبح لدى فئة `StealthyFetcher` خيار `geoip` في دوال الجلب. عند تفعيله، تستخدم تلقائيًا خط الطول وخط العرض والمنطقة الزمنية والبلد والإعدادات المحلية المرتبطة بعنوان IP، ثم تغيّر عنوان IP الذي يظهر عبر WebRTC. وتحدد أيضًا لغة المتصفح وتحاكيها حسب توزيع متحدثي اللغات في المنطقة المستهدفة.+3. إضافة الخيار `retries` إلى الفئتين `Fetcher`/`AsyncFetcher`، لتحديد عدد مرات إعادة محاولة كل طلب ينفذه `httpx`.+4. إضافة الدالة `url_join` إلى `Adaptor` وأدوات جلب الصفحات. تأخذ رابطًا نسبيًا وتجمعه مع الرابط الحالي لإنشاء رابط كامل!+5. إضافة الدالة `keep_cdata` إلى `Adaptor` وأدوات جلب الصفحات لمنع محلل الصفحات من إزالة cdata عند الحاجة.+6. أصبحت `Adaptor`/`Response` تعيد عبر الدالة `body` استجابة HTML الخام إن أمكن (دون معالجتها داخل المكتبة).+7. إضافة تسجيل الأحداث لفئة `Response`. عند استخدام أدوات جلب الصفحات، ستحصل الآن على سجل يعرض معلومات عن الاستجابة.+مثال:++ ```python+ >> from scrapling.defaults import Fetcher+ >> Fetcher.get('https://books.toscrape.com/index.html')+ [2024-12-16 13:33:36] INFO: Fetched (200) <GET https://books.toscrape.com/index.html> (referer: https://www.google.com/search?q=toscrape)+ >>+ ```++8. أصبح استخدام دوال النصوص القياسية على `TextHandler`، مثل `.replace()`، يعيد `TextHandler` آخر. كان يعيد نصًا عاديًا من قبل.+9. تحسينات كبيرة في السرعة في المكتبة كلها، وتحسين التخفي في أدوات جلب الصفحات بشكل عام.+10. إضافة دوال توافق مثل `extract_first`\`extract` تعيد النتيجة نفسها التي يعيدها الكائن الأصلي. أُضيفت فقط لتسهيل نقل الكود من Scrapy/Parsel إلى Scrapling عند الحاجة، لأن هذه الدوال مستخدمة هناك!+11. أصبحت الطلبات الجماعية أسرع بكثير بفضل إعادة تنظيم أجزاء كثيرة من الكود واستخدام التخزين المؤقت في الأماكن المناسبة.++##### تغييرات قد تؤثر في الكود الحالي {#v0.2.9-breaking-changes}+- إيقاف دعم Python 3.8. (السبب الرئيسي هو توقف Playwright عن دعمه، لكنه كان إصدارًا كثير المشكلات على أي حال)+- إزالة الخيار `debug` من المكتبة كلها. لتفعيل وضع تصحيح الأخطاء، نفّذ ما يلي بعد استيراد المكتبة:++ ```python+ >>> import logging+ >>> logging.getLogger("scrapling").setLevel(logging.DEBUG)+ ```++##### إصلاحات الأخطاء {#v0.2.9-bugs-squashed}+1. تفعيل WebGL افتراضيًا لأن كثيرًا من أنظمة الحماية تتحقق الآن من تفعيله.+2. إصلاح بعض الأخطاء وأخطاء الكتابة في التوثيق وREADME.++##### تحسينات الاستخدام {#v0.2.9-quality-of-life-changes}+1. توحيد كل السجلات تحت اسم `scrapling` لتسهيل التحكم بها. كنا نستخدم root logger من قبل.+2. إعادة تنظيم مجلد الاختبارات وإضافة اختبارات للميزات الجديدة. أُعيدت كتابة كل الاختبارات بشكل أوضح، وأُضيف المزيد منها لتغطية أجزاء أكثر من الكود.+3. إعادة تنظيم جزء كبير من الكود ليكون أنظف وأسهل في الصيانة.++> كانت كل هذه التغييرات ضمن ما خططت لإضافته في 0.3، لكنني قررت إضافتها هنا لأن الإصدار التالي سيحتاج إلى بعض الوقت. الخطوة التالية هي إكمال موقع التوثيق المفصل، ثم العمل على الإصدار 0.3++## [v0.2.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.8) - 2024-11-30 {#v0.2.8}++### ما الذي تغير {#v0.2.8-what-s-changed}+- تحديث صغير يتضمن تحسينات ضرورية لتسهيل استخدام الكود، وتصحيح خطأ كتابة في ملف README الرئيسي (#20)++## [v0.2.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.7) - 2024-11-26 {#v0.2.7}++### ما الذي تغير {#v0.2.7-what-s-changed}+##### ميزات جديدة {#v0.2.7-new-features}+- عند استخدام الخيار `wait_selector` مع `StealthyFetcher` و`PlayWrightFetcher`، تنتظر Scrapling مجددًا اكتمال تحميل JS وتنفيذه كالمعتاد. وإذا استخدمت الخيار `network_idle`، فستنتظر تحققه مجددًا بعد ذلك أيضًا. وبالطبع، لا يحدث انتظار إذا كانت جميع الحالات قد تحققت بالفعل.+- يمكنك الآن تفعيل الإعلانات أو تعطيلها في `StealthyFetcher` باستخدام الخيار `disable_ads`. حظر الإعلانات مفعّل افتراضيًا، ويثبّت إضافة `ublock origin`.+- يمكنك الآن تحديد الإعدادات المحلية التي يستخدمها `PlayWrightFetcher` عبر الخيار `locale`. تظل القيمة الافتراضية `en-US`.+- أصبحت الطلبات الأساسية عبر `Fetcher` تقبل البروكسي بالتنسيق `http://username:password@localhost:8030`.+- تحسين وضع التخفي قليلًا في `PlayWrightFetcher`.++##### إصلاحات الأخطاء والتحسينات {#v0.2.7-bugs-squashed-improvements}+1. لم يعد تفعيل البروكسي في فئة `PlayWrightFetcher` مرتبطًا بتفعيل وضع `stealth` أو تعطيله (شكرًا لـ [@AbdullahY36](https://github.com/AbdullahY36) على التنبيه)+2. أصبحت `ResponseEncoding` تتحقق من إمكانية استخدام الترميز الوارد في الاستجابة مع الصفحة. إذا سبب هذا الترميز خطأ، تستخدم Scrapling الترميز الافتراضي `utf-8`++## [v0.2.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.6) - 2024-11-24 {#v0.2.6}++### ما الذي تغير {#v0.2.6-what-s-changed}+##### ميزات جديدة {#v0.2.6-new-features}+- يمكن الآن لـ `PlayWrightFetcher` استخدام المتصفح الحقيقي مباشرة عبر تمرير الخيار `real_chrome` إلى الدالة `PlayWrightFetcher.fetch`، بشرط تثبيت متصفح Chrome. تشغّل Scrapling نسخة من Chrome لديك، ويمكنك استخدام معظم الخيارات كالمعتاد. (كان الخيار `cdp_url` هو الطريقة الوحيدة لذلك من قبل)+- تحديث الإصدار الذي تعكسه الترويسات المولّدة للمتصفحات الحقيقية.++##### إصلاحات الأخطاء {#v0.2.6-bugs-squashed}+1. اتضح أن تنسيق ترويسات المتصفح التي يولدها `BrowserForge` كان قديمًا، مما جعل بعض أنظمة الحماية تكتشف Scrapling. لذلك أصبح `BrowserForge` يُستخدم فقط لتوليد useragent حقيقي.+2. تعطيل الخيار `hide_canvas` افتراضيًا لأن ReCaptcha من Google تكتشفه.++## [v0.2.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.5) - 2024-11-23 {#v0.2.5}++### ما الذي تغير {#v0.2.5-what-s-changed}++##### إصلاحات الأخطاء {#v0.2.5-bugs-squashed}+- معالجة خطأ يحدث مع الخيار 'wait_selector' عندما يطابق أكثر من 1 عنصر. يؤثر ذلك في الفئتين `StealthyFetcher` و`PlayWrightFetcher`.+- تصحيح نوع الترميز عندما تحتوي قيمة ترويسة `content_type` على خيارات مثل `charset` (شكرًا لـ @andyfcx على [#12](https://github.com/D4Vinci/Scrapling/issues/12) )++##### تحسينات الاستخدام {#v0.2.5-quality-of-life}+- إضافة اختبارات لتغطية أجزاء جديدة من الكود، وتشغيل الاختبارات في خيوط تنفيذ.+- تحديث نصوص التوثيق داخل الكود لتظهر بشكل صحيح في أداة apidoc من Sphinx والأدوات المشابهة.++##### مساهمون جدد {#v0.2.5-new-contributors}+- قدّم @andyfcx مساهمته الأولى في [#13 ](https://github.com/D4Vinci/Scrapling/pull/13)++## [v0.2.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.4) - 2024-11-20 {#v0.2.4}++### ما الذي تغير {#v0.2.4-what-s-changed}++##### إصلاحات الأخطاء {#v0.2.4-bugs-squashed}+- إصلاح خطأ عند استرجاع بايتات الاستجابة بعد استخدام الخيار `network_idle` في الفئتين `StealthyFetcher` و`PlayWrightFetcher`. <br/> كان يسبب رسالة الخطأ التالية:++ ```+ Response.body: Protocol error (Network.getResponseBody): No resource with given identifier found+ ```++- تعيد PlayWright API أحيانًا نص حالة فارغًا مع الاستجابة، لذا تحسبه `Scrapling` الآن بنفسها عند حدوث ذلك. يؤثر هذا في الفئتين `StealthyFetcher` و`PlayWrightFetcher`.++## [v0.2.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.3) - 2024-11-19 {#v0.2.3}++### ما الذي تغير {#v0.2.3-what-s-changed}++##### إصلاحات الأخطاء {#v0.2.3-bugs-squashed}+- إصلاح خطأ في التثبيت باستخدام pip كان يمنع وضع التخفي في PlayWright Fetcher من العمل تمامًا.++## [v0.2.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.2) - 2024-11-16 {#v0.2.2}++### ما الذي تغير {#v0.2.2-what-s-changed}+##### ميزات جديدة {#v0.2.2-new-features}+- إذا أردت استخدام القيم الافتراضية دون تمرير خيارات إلى كائن `Adaptor` الناتج، يمكنك استخدام الاستيراد التالي ليكون الكود أبسط++ ```python+ >> from scrapling.default import Fetcher, StealthyFetcher, PlayWrightFetcher+ >> page = Fetcher.get('https://example.com', stealthy_headers=True)+ ```++ وإلا++ ```python+ >> from scrapling import Fetcher, StealthyFetcher, PlayWrightFetcher+ >> page = Fetcher(auto_match=False).get('https://example.com', stealthy_headers=True)+ ```++##### إصلاحات الأخطاء {#v0.2.2-bugs-squashed}+1. إصلاح خطأ في كائن `Response` ظهر مع تحديث v0.2.1 بالأمس، وكان يحدث في بعض حالات التحديد أو التحليل المتداخل.++## [v0.2.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.1) - 2024-11-15 {#v0.2.1}++### ما الذي تغير {#v0.2.1-what-s-changed}+##### ميزات جديدة {#v0.2.1-new-features}+1. أصبح كائن `Response` الذي تعيده جميع أدوات جلب الصفحات مماثلًا لكائن `Adaptor`، مع إضافة الخصائص التالية: `status` و`reason` و`cookies` و`headers` و`request_headers`. تكون `cookies` و`headers` و`request_headers` دائمًا من نوع `dictionary`. <br/>يمكن أن يصبح الكود الآن بهذا الشكل:++ ```python+ >> from scrapling import Fetcher+ >> page = Fetcher().get('https://example.com', stealthy_headers=True)+ >> print(page.status)+ 200+ >> products = page.css('.product')+ ```++ بدلًا من الشكل السابق++ ```python+ >> from scrapling import Fetcher+ >> fetcher = Fetcher().get('https://example.com', stealthy_headers=True)+ >> print(fetcher.status)+ 200+ >> page = fetcher.adaptor+ >> products = page.css('.product')+ ```++ لكنني أبقيت الخاصية `.adaptor` تعمل للتوافق مع الكود القديم.++2. أصبحت الفئتان `StealthyFetcher` و`PlayWrightFetcher` تقبلان الخيار `proxy` في دالة الجلب، ويقبل نصًا أو قاموسًا.+3. أصبح لدى فئة `StealthyFetcher` الخيار `os_randomize` في الدالة `fetch`. عند تفعيله، تختار Scrapling بصمات نظام التشغيل عشوائيًا. أما افتراضيًا، فتطابق البصمات نظام التشغيل الحالي.++##### إصلاحات الأخطاء {#v0.2.1-bugs-squashed}+1. إصلاح خطأ يحدث عند تمرير الترويسات مع فئة `Fetcher`.+2. إصلاح خطأ في تحليل استجابات JSON التي تأتي من أدوات جلب الصفحات.++##### تحسينات الاستخدام {#v0.2.1-quality-of-life-changes}+1. كانت دوال النصوص تحاول إزالة تعليقات HTML قبل إعادة النص، لكن ذلك سبب أخطاء في بعض الحالات وجعل الكود أعقد من اللازم. عادت الآن إلى السلوك الافتراضي لـ lxml، **وستلاحظ زيادة بسيطة في سرعة كل العمليات التي تعتمد على نص العناصر، مثل المحددات**. إذا أردت أن تزيل Scrapling تعليقات HTML من العناصر قبل إعادة النص، لتجنب سلوك تقسيم النص الغريب في lxml/parsel/scrapy، أبقِ الخيار `keep_comments` مضبوطًا على True كما هو افتراضيًا.++## [v0.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2) - 2024-11-11 {#v0.2}++### ما الذي تغير {#v0.2-what-s-changed}+##### ميزات جديدة {#v0.2-new-features}+1. إضافة ميزة `Fetchers` مع 3 أنواع رئيسية جديدة، لتجلب Scrapling الصفحات لك بخيارات كثيرة جدًا!+ - فئة `Fetcher` لطلبات HTTP الأساسية+ - فئة `StealthyFetcher` لجلب الصفحات بتخفٍ كامل باستخدام [نسخة معدّلة من Firefox للتخفي](https://github.com/daijro/camoufox).+ - فئة `PlayWrightFetcher` لطلبات المتصفح عبر PlayWright العادي، أو PlayWright مع وضع التخفي الذي طورته، أو متصفحات حقيقية عبر CDP، أو [NSTBrowser](https://app.nstbrowser.io/r/1vO5e5) عبر [docker browserless](https://hub.docker.com/r/nstbrowser/browserless)!+2. إضافة الدالتين الجديدتين بالكامل `find_all`/`find` للعثور على عناصر الصفحة بسهولة وبشيء من السحر!+3. إضافة الدالتين `filter` و`search` إلى فئة `Adaptors` لتسهيل العمليات الجماعية على مجموعات كائنات `Adaptor`.+4. إضافة الدالتين `css_first` و`xpath_first` لتسهيل الاستخدام.+5. إضافة الفئة الجديدة `TextHandlers` لتنفيذ عمليات جماعية على كائنات `TextHandler`، مثل فئة `Adaptors`.+6. إضافة الدالتين `generate_full_css_selector` و`generate_full_xpath_selector`.++##### إصلاحات الأخطاء {#v0.2-bugs-squashed}+1. أصبحت فئة `Adaptors` تعيد عبر `re_first` أول نتيجة مطابقة من جميع كائنات `Adaptor` الموجودة فيها، بدلًا من السلوك الخاطئ الذي كان يعيد نتائج `re_first` لكل كائنات `Adaptor`.+2. عند اختيار محتوى نصي من العناصر (مثل دالة CSS المسماة `::text`) بأي دالة مثل `.css` أو `.xpath`، يعيد كائن `Adaptor` الآن فئة `TextHandlers` بدلًا من قائمة نصوص كما كان من قبل. يمكنك الآن كتابة `page.css('something::text').re_first(r'regex_pattern').json()` بدلًا من `page.css('something::text')[0].re_first(r'regex_pattern').json()`+3. أصبحت خيارات re/re_first في `Adaptor`/`Adaptors` متسقة مع خيارات `TextHandler`. أصبح الخياران `clean_match` و`case_sensitive` متاحين.+4. تفعيل الخيار `auto_match` افتراضيًا عند إنشاء `Adaptor`، لكن لا يزال عليك تفعيله عند تحديد العناصر إذا أردت استخدامه. (هذا قرار تصميم، وليس خطأ)+5. تصحيح كثير من تلميحات الأنواع لتحسين الإكمال التلقائي أثناء كتابة الكود باستخدام Scrapling.++##### تحسينات الاستخدام {#v0.2-quality-of-life-changes}+1. تغيير اسمي الدالتين `css_selector` و`xpath_selector` إلى `generate_css_selector` و`generate_xpath_selector` لزيادة الوضوح ومنع التداخل مع الإكمال التلقائي أثناء كتابة الكود.+2. نقل معظم الكود القديم إلى حزمة فرعية باسم `core`، مع قرارات تصميم أخرى لجعل الصيانة مستقبلًا أسهل وأوضح.+3. إعادة تنظيم مجلد الاختبارات وإضافة اختبارات للميزات الجديدة. وأصبحت بيئات tox تُحفظ مؤقتًا على GitHub لتسريع الاختبارات الآلية مع كل commit.++## [v0.1.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.2) - 2024-10-16 {#v0.1.2}++**سجل التغييرات**:++- إصلاح خطأ كان يجعل الخيار `keep_comments` لا يعمل كما ينبغي.+- تعديل دالة النصوص لإزالة تعليقات HTML من العناصر تلقائيًا قبل استخراج نصها، لتجنب اختلاف سلوك Lxml، مثلًا:++ ```python+ >>> page = Adaptor('<span>CONDITION: <!-- -->Excellent</span>', keep_comments=True)+ >>> page.css('span::text')+ ['CONDITION: ', 'Excellent']+ ```++ كان هذا هو الناتج سابقًا بسبب السلوك الافتراضي لـ Lxml، لكن الناتج الآن هو النص الكامل 'CONDITION: Excellent'+ هذا السلوك معروف أيضًا في parsel\scrapy، لذا أردت معالجته هنا.++- إصلاح خطأ كان يمنع حذف ملف قاعدة بيانات SQLite الذي تنشئه المكتبة عند تشغيل `pip uninstall scrapling` أو أمر مشابه.++## [v0.1.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.1) - 2024-10-14 {#v0.1.1}++إصلاحات بسيطة++## [v0.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1) - 2024-10-13 {#v0.1}++**سجل التغييرات الكامل**: <https://github.com/D4Vinci/Scrapling/commits/v0.1>diff --git a/docs/locales/de/changelog.md b/docs/locales/de/changelog.mdnew file mode 100644index 0000000..f292ba1--- /dev/null+++ b/docs/locales/de/changelog.md@@ -0,0 +1,1279 @@+---+title: "Änderungsverlauf von Scrapling"+description: "Versionshinweise zu Scrapling mit neuen Funktionen, Fehlerbehebungen und inkompatiblen Änderungen."+---++# Änderungsverlauf {#changelog}++Alle wichtigen Änderungen an Scrapling aus den [GitHub-Releases](https://github.com/D4Vinci/Scrapling/releases).++## [v0.4.15](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.15) - 2026-08-23 {#v0.4.15}++**Eine der größten Veröffentlichungen dieses Jahres: ein überarbeiteter MCP-Server, Markdown für RAG mit einer Zeile Code, besseres Lösen von Cloudflare-Prüfungen und Browser-Tabs, die für die Automatisierung offen bleiben 🚀**++!!! warning "Warnung"++ **Diese Version enthält inkompatible Änderungen am MCP-Server. Lesen Sie vor dem Update den Abschnitt zu den [inkompatiblen Änderungen](https://github.com/D4Vinci/Scrapling/blob/v0.4.15/docs/ai/mcp-server.md#breaking-changes).**++### 🚀 Neuerungen und Verbesserungen der Bedienung {#v0.4.15-new-stuff-and-quality-of-life-changes}++- **Browser-Tabs bleiben jetzt offen und werden für weitere Anfragen wiederverwendet** (siehe [Dokumentation](fetching/stealthy.md#session-management)):+ - Alle Browser-Sitzungen behalten ihre Tabs nach einer Anfrage. Die nächste Anfrage nutzt einen freien Tab, statt einen neuen zu öffnen.+ - Jede Anfrage wendet ihre eigenen Einstellungen (Zeitlimits, Header und Ressourcensperren) erneut auf den zugewiesenen Tab an. So gelangen keine Einstellungen von einer Anfrage in die nächste.+ - Tabs mit Fehlern werden geschlossen und ersetzt. Die neue Methode `close_pages()` schließt alle offenen Tabs.+ - Die abgerufene Seite bleibt geladen. Eine Funktion `page_setup` in der nächsten Anfrage läuft deshalb auf dieser Seite, bevor der Browser zu einer anderen wechselt. Damit lassen sich Automatisierungsschritte über mehrere Anfragen verknüpfen.++- **Wandeln Sie jede Seite mit `Response.markdown()` in sauberes Markdown für LLMs um** (siehe [Dokumentation](ai/building-rag-systems.md)):++ ```python+ from scrapling.fetchers import Fetcher++ markdown = Fetcher.get("https://example.com").markdown(main_content_only=True)+ ```++ - Skripte, Stile und versteckte Inhalte für Prompt Injection werden immer zuerst entfernt, mit derselben Bereinigung wie im MCP-Server.+ - Übergeben Sie `css_selector`, um nur die benötigten Elemente umzuwandeln.+ - Verfügbar über das neue Extra `rag` (`pip install "scrapling[rag]"`), das auch in den Extras `ai`/`shell`/`all` enthalten ist.++- **Neue Vorlage `SiteToMarkdownSpider`, um eine ganze Website zu crawlen und eine Markdown-Sammlung für RAG-Pipelines zu erstellen** (siehe [Dokumentation](ai/building-rag-systems.md)):++ ```python+ from scrapling.spiders import SiteToMarkdownSpider++ class DocsSpider(SiteToMarkdownSpider):+ name = "docs"+ start_urls = ["https://example.com/docs/"]+ allowed_domains = {"example.com"}+ output_dir = "docs_markdown"++ result = DocsSpider().start()+ result.items.to_jsonl("docs.jsonl")+ ```++ - Liefert einen Datensatz pro Seite mit `url`/`title`/`markdown`. Der optionale Parameter `output_dir` schreibt eine Markdown-Datei pro Seite.+ - `max_pages` begrenzt den Crawl. Da die Vorlage auf `CrawlSpider` aufbaut, haben Sie durch Überschreiben von `rules()` volle Kontrolle über die verfolgten Links.++- **Der MCP-Server wurde überarbeitet (inkompatible Änderung)** (siehe [inkompatible Änderungen](https://github.com/D4Vinci/Scrapling/blob/v0.4.15/docs/ai/mcp-server.md#breaking-changes) und [Dokumentation](ai/mcp-server.md)):+ - Die 13 Werkzeuge sind jetzt in zwei Modi aufgeteilt: Werkzeuge für einzelne Aufrufe (`fetch`, `bulk_fetch`, `stealthy_fetch`, `bulk_stealthy_fetch`), die immer ihren eigenen Browser starten und ihre tatsächlichen Standardwerte anzeigen, sowie Sitzungswerkzeuge, die eine einmal geöffnete Sitzung nutzen.+ - Das neue Werkzeug `session_fetch` ruft Seiten über eine Browser-Sitzung ab. `open_session` enthält jetzt nur noch Einstellungen auf Browser-Ebene und gibt dem KI-Agenten die tatsächlich verwendeten Einstellungen der Sitzung zurück.+ - Das Werkzeug `get` wurde in `make_request` umbenannt und unterstützt jetzt jede HTTP-Methode.+ - Die neuen Werkzeuge `open_request_session` und `session_make_request` geben der KI dauerhafte HTTP-Sitzungen, die Cookies und den Browser-Fingerprint zwischen Anfragen behalten.+ - Damit setzen Abrufe auch nicht mehr die Sitzungseinstellungen zurück. Dieses Problem wurde zuerst von @Yigtwxx in [#418](https://github.com/D4Vinci/Scrapling/pull/418) behoben.++- **Der HTTP-Transport des MCP-Servers erfordert jetzt eine Authentifizierung und lauscht standardmäßig auf localhost (inkompatible Änderung)**, von @yamantaka-singh in [#414](https://github.com/D4Vinci/Scrapling/pull/414) (behebt [#413](https://github.com/D4Vinci/Scrapling/issues/413), siehe [Dokumentation](ai/mcp-server.md#authentication)):+ - Übergeben Sie `--auth-token` (oder die Umgebungsvariable `SCRAPLING_MCP_AUTH_TOKEN`), um ein Bearer-Token zu verlangen. Mit `--no-auth` betreiben Sie den Server bewusst ohne Authentifizierung.+ - Übergeben Sie `--host 0.0.0.0`, um Verbindungen aus dem Netzwerk anzunehmen.++### 🐛 Fehlerbehebungen {#v0.4.15-bug-fixes}++- **Cloudflare Turnstile/Interstitial wird jetzt unabhängig von den Sprach- und Regionseinstellungen des Browsers gelöst. Interaktive Prüfungen im Headless-Modus führen nicht mehr zu Endlosschleifen**. Seiten im getarnten Browser stürzen auch nicht mehr während der Lösung ab, mit Beiträgen von @subediparas5 in [#412](https://github.com/D4Vinci/Scrapling/pull/412). (Behebt [#411](https://github.com/D4Vinci/Scrapling/issues/411) und [#422](https://github.com/D4Vinci/Scrapling/issues/422))+- **Behoben: `find`/`find_all` mit `class_` übersahen ohne Hinweis Elemente mit mehreren Klassen**, von @yetval in [#410](https://github.com/D4Vinci/Scrapling/pull/410), **sowie leere `class_`-Werte und nicht maskierte CSS-Zeichenfolgen**, von @yamantaka-singh in [#417](https://github.com/D4Vinci/Scrapling/pull/417).+- **Behoben: Antworten aus dem Cache verloren beim erneuten Verwenden im `development_mode` die Metadaten der Anfrage**, von @Yigtwxx in [#419](https://github.com/D4Vinci/Scrapling/pull/419).+- **Behoben: HTTP-Anfragen mit `retries` unter 1 schlugen fehl, ohne die Anfrage zu senden**, von @Yigtwxx in [#420](https://github.com/D4Vinci/Scrapling/pull/420).++### Dokumentation {#v0.4.15-docs}++- **Die Website-Bereiche wurden neu geordnet**: Der neue Bereich „Mit KI verwenden“ enthält den MCP-Server, die neue Seite zum [Agent Skill](ai/agent-skill.md) und die Anleitung zum [Aufbau von RAG-Systemen](ai/building-rag-systems.md). Die Anleitung zum Wechsel von BeautifulSoup steht jetzt neben der Scrapy-Integration unter „Integrationen und Migrationen“.+- **Ein [Änderungsverlauf](changelog.md) wurde hinzugefügt**, der die Hinweise zu allen bisher veröffentlichten Versionen im Repository enthält.++## [v0.4.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.14) - 2026-08-10 {#v0.4.14}++**Ein schnelles Wartungsupdate zur Behebung der Installation mit `uv` 🔧**++### 🐛 Fehlerbehebungen {#v0.4.14-bug-fixes}++- **Behoben: `uv` weigerte sich standardmäßig, v0.4.13 zu installieren, und wechselte ohne Hinweis zu einer älteren Version**. Die vorherige Version verlangte eine Vorabversion von `curl_cffi`. `uv` erlaubt das nur, wenn es ausdrücklich aktiviert wird.+Alle Abhängigkeiten lassen sich jetzt mit stabilen Versionen auflösen. (Behebt [#407](https://github.com/D4Vinci/Scrapling/issues/407))++## [v0.4.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.13) - 2026-08-09 {#v0.4.13}++**Ein neues Update mit Feed-Spidern und einem intelligenteren MCP-Server 🎉**++### 🚀 Neuerungen und Verbesserungen der Bedienung {#v0.4.13-new-stuff-and-quality-of-life-changes}++- **Neue Spider-Vorlagen für Feeds**. `XMLFeedSpider` durchläuft die Knoten beliebiger XML-Feeds (RSS, Atom, Produkt-Feeds usw.), und `CSVFeedSpider` durchläuft CSV-Zeilen als Dictionaries. Beide entpacken mit gzip komprimierte Feeds automatisch. (Siehe [Dokumentation](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import XMLFeedSpider++ class RSSSpider(XMLFeedSpider):+ name = "rss"+ start_urls = ["https://example.com/feed.xml"]++ async def parse_node(self, response, node):+ yield {"title": node.findtext("title"), "link": node.findtext("link")}++ result = RSSSpider().start()+ ```++- **Der MCP-Server wurde auf MCP SDK v2 umgestellt und verbessert**. Er enthält jetzt Anweisungen, die Ihrem KI-Agenten die effiziente Nutzung der Werkzeuge erklären. Jedes Werkzeug gibt Annotationen an, damit Clients wie Claude Code rein lesende Werkzeuge automatisch genehmigen können. Kürzere Beschreibungen sparen Tokens, und der Server meldet seine Version und sein Logo an MCP-Clients. (Siehe [Dokumentation](ai/mcp-server.md))+- **Der Befehl `scrapling-mcp` wurde hinzugefügt**. Er führt direkt `scrapling mcp` aus. So lässt sich Scrapling mit einer Zeile bei MCP-Clients und Verzeichnissen registrieren, die einen einzelnen Befehl erwarten.+- **Playwright/Patchright und Browser sind nicht mehr auf feste Versionen begrenzt**. Der erzeugte User-Agent passt jetzt immer genau zur Chromium-Version, die Ihre installierte Version von Playwright/Patchright steuert. Deshalb legt Scrapling deren Versionen nicht mehr fest, und Sie können sie frei aktualisieren. Führen Sie nach dem Update `scrapling install --force` aus, um die Browser zu aktualisieren.++### 🐛 Fehlerbehebungen {#v0.4.13-bug-fixes}++- **Behoben: Der Import von Scrapling brach mit einem ValueError von `browserforge` ab**, wenn das Datenpaket für Fingerprints hinter den Browser-Versionen zurücklag. (Behebt [#394](https://github.com/D4Vinci/Scrapling/issues/394), [#396](https://github.com/D4Vinci/Scrapling/issues/396) und [#400](https://github.com/D4Vinci/Scrapling/issues/400))+- **Falsche Größen der Seiten-Pools in den MCP-Browser-Werkzeugen für Stapelabrufe wurden korrigiert**. Wegen dieses Fehlers schlug `bulk_fetch` bei mehr als 50 URLs fehl, und `bulk_stealthy_fetch` rief alle URLs über einen einzigen Tab ab. Von @Yigtwxx in [#393](https://github.com/D4Vinci/Scrapling/pull/393).++### Projekt {#v0.4.13-project}++- **Neue [Richtlinie für KI-gestützte Beiträge](https://github.com/D4Vinci/Scrapling/blob/main/AI_POLICY.md)**: Beiträge mit KI-Unterstützung sind willkommen, müssen aber im PR oder Issue gekennzeichnet werden. Beiträge, die ohne Kennzeichnung nach KI-Ausgaben aussehen, erhalten ein Label und werden geschlossen.++## [v0.4.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.12) - 2026-07-26 {#v0.4.12}++**Eine Version, mit der Ihre Spider intelligenter auf die gecrawlten Websites reagieren**++### 🚀 Neuerungen und Verbesserungen der Bedienung {#v0.4.12-new-stuff-and-quality-of-life-changes}++- **Spider können ihre Geschwindigkeit jetzt mit AutoThrottle selbst anpassen.** Statt einen `download_delay` zu schätzen, der entweder zu langsam ist oder zu einer Sperre führt, misst der Spider die Antwortgeschwindigkeit jeder Website und passt die Wartezeit pro Domain selbst an. Sobald eine Website Sie sperrt oder die Anfragerate begrenzt, verdoppelt er die Wartezeit (oder wartet genau so lange, wie der Header `Retry-After` verlangt), bis das aufhört. Danach wird er wieder schneller. Ihr `download_delay` und jeder `Crawl-delay` aus robots.txt gelten weiterhin als Mindestwert. (Siehe [Dokumentation](spiders/advanced.md#autothrottle))++ ```python+ class MySpider(Spider):+ name = "adaptive"+ start_urls = ["https://example.com"]+ autothrottle_enabled = True+ autothrottle_start_delay = 2.0+ autothrottle_max_delay = 30.0+ autothrottle_block_backoff = True+ ```++- **Exportieren Sie Ihre Ergebnisse als CSV und XML**, zusätzlich zu den bisherigen JSON/JSONL-Exporten. Auch Datensätze mit unterschiedlichen Schlüsseln werden ohne Verluste exportiert. Verschachtelte Werte werden als JSON geschrieben. (Siehe [Dokumentation](spiders/getting-started.md))++ ```python+ result = MySpider().start()+ result.items.to_csv("products.csv")+ result.items.to_xml("products.xml")+ ```++- **Der MCP-Server kann jetzt eine Authentifizierung verlangen**. So können Sie ihn sicher bereitstellen, statt ihn nur auf Ihrem eigenen Rechner zu betreiben. Jede Anfrage ohne Token wird abgelehnt. Sie können auch einschränken, auf welche Hostnamen der Server antwortet. (Siehe [Dokumentation](ai/mcp-server.md))++ ```bash+ scrapling mcp --http --auth-token "$(openssl rand -hex 32)"+ ```++- **Browser akzeptieren jetzt CDP-URLs über HTTP**, nicht nur über WebSocket. Neben den `wss://`-Endpunkten verwalteter Browser-Anbieter können Sie jeden Browser-Fetcher oder jede MCP-Sitzung mit einem selbst gestarteten Chrome mit `--remote-debugging-port=9222` verbinden.++- **Veröffentlichte Docker-Images tragen jetzt ein Tag mit ihrer Versionsnummer**, statt nur `latest`. So können Sie genau die gewünschte Version festlegen. Von @JanRK in [#384](https://github.com/D4Vinci/Scrapling/pull/384).++### 🐛 Fehlerbehebungen {#v0.4.12-bug-fixes}++- **Behoben: Antworten aus dem Cache verloren alle Cookies, wenn sie von einem Browser kamen**. Dadurch funktionierte im Entwicklungsmodus der Spider die Sitzungs- oder Authentifizierungslogik, die diese Cookies brauchte, ohne Hinweis nicht mehr. Von @amitvijapur in [#379](https://github.com/D4Vinci/Scrapling/pull/379). (Behebt [#376](https://github.com/D4Vinci/Scrapling/issues/376))++- **Behoben: `StealthyFetcher` erzwang die Regionseinstellung `en-US`** für jeden Browser, statt die Systemeinstellung zu übernehmen. Websites erkannten dadurch einen Widerspruch zwischen Ihren Sprach- und Regionseinstellungen und Ihrer IP-Adresse und stuften Sie als verdächtig ein. Google antwortete zum Beispiel mit 429. (Behebt [#381](https://github.com/D4Vinci/Scrapling/issues/381))++- **Eine irreführende Fehlermeldung im Speichersystem wurde korrigiert**, und ein ungenutzter Aufruf nach Einfügevorgängen wurde entfernt. Von @fix2015 in [#377](https://github.com/D4Vinci/Scrapling/pull/377).++### Leistung {#v0.4.12-performance}++- **Die Laufzeit von `get_all_text()` wächst jetzt proportional zur Anzahl der Knoten, O(nodes)**, statt die Vorfahren jedes einzelnen Textknotens zu durchlaufen. Das macht die Methode auf tief verschachtelten Seiten etwa 5-6-mal schneller. Von @yetval in [#378](https://github.com/D4Vinci/Scrapling/pull/378).++## [v0.4.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.11) - 2026-07-12 {#v0.4.11}++**Ein großes Update mit der ersten Spider-Vorlage für eine Plattform, einem schnelleren Parser und wichtigen Fehlerbehebungen 🎉**++### 🚀 Neuerungen und Verbesserungen der Bedienung {#v0.4.11-new-stuff-and-quality-of-life-changes}++- **`ShopifySpider`, die erste Spider-Vorlage für eine Plattform, wurde hinzugefügt!** Extrahieren Sie alle Produkte eines Shopify-Shops über dessen JSON-API, ohne das HTML der Website zu verwenden. Erstellen Sie eine Unterklasse, setzen Sie die Shop-Domain, und schon sind Sie fertig (siehe [Dokumentation](spiders/platform-templates.md))++ ```python+ from scrapling.spiders import ShopifySpider++ class MyStore(ShopifySpider):+ target_website = "example.com"++ result = MyStore().start()+ ```++- **`--executable-path` wurde zu den Browser-Befehlen der CLI hinzugefügt**. Sowohl `scrapling extract fetch` als auch `scrapling extract stealthy-fetch` akzeptieren jetzt eine eigene ausführbare Browser-Datei, die mit Chromium kompatibel ist. Ohne diese Option verwenden sie die Umgebungsvariable `SCRAPLING_EXECUTABLE_PATH`. Damit bieten sie denselben Funktionsumfang wie der MCP-Server (löst [#371](https://github.com/D4Vinci/Scrapling/issues/371))++ ```bash+ scrapling extract fetch "https://example.com" page.html --executable-path "/path/to/chromium"+ ```++### 🤖 Verbesserungen der Bedienung {#v0.4.11-quality-of-life-changes}+- **`find_by_text` und `find_by_regex` sind jetzt bis zu etwa 2-mal schneller**, wenn `first_match` aktiviert ist (Standard). Elemente werden erst bei Bedarf in Objekte umgewandelt, sodass die Suche beim ersten Treffer endet. Von @yetval in [#370](https://github.com/D4Vinci/Scrapling/pull/370)+- **Die Benchmarks wurden mit neuen Zahlen und den neuesten Versionen aller Bibliotheken aktualisiert.**+- **Die Beitragsregeln wurden aktualisiert**++### 🐛 Fehlerbehebungen {#v0.4.11-bug-fixes}++- **Abstürze der Abrufwerkzeuge des MCP-Servers auf Seiten mit Steuerzeichen wurden behoben**. Dabei erschien der Fehler `All strings must be XML compatible`. Von @yetval in [#368](https://github.com/D4Vinci/Scrapling/pull/368) (behebt [#366](https://github.com/D4Vinci/Scrapling/issues/366))++## [v0.4.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.10) - 2026-07-04 {#v0.4.10}++**Ein neues Update mit einer neuen Scrapy-Integration und mehreren Korrekturen aus der Community 🎉**++### 🚀 Neuerungen und Verbesserungen der Bedienung {#v0.4.10-new-stuff-and-quality-of-life-changes}++- **Eine Scrapy-Integration wurde hinzugefügt**, damit Sie die Parsing-API von Scrapling in vorhandenen Scrapy-Projekten nutzen können, ohne sie neu zu schreiben. Setzen Sie den Dekorator `scrapling_response` auf einen Spider-Callback. Die empfangene Antwort wird dann zu einer `Response` von Scrapling, während Scrapy weiterhin den Crawl steuert (siehe [Dokumentation](integrations/scrapy.md)):++ ```python+ import scrapy+ from scrapling.integrations.scrapy import scrapling_response++ class QuotesSpider(scrapy.Spider):+ name = "quotes"+ start_urls = ["https://quotes.toscrape.com"]++ @scrapling_response+ def parse(self, response): # `response` is now a Scrapling Response+ first_quote = response.find_by_text("The world as we have created it", partial=True)+ for quote in [first_quote, *first_quote.find_similar()]:+ yield {"text": quote.get_all_text(strip=True)}+ ```++- **Der MCP-Server kann jetzt einen eigenen, mit Chromium kompatiblen Browser nutzen**, und zwar für alle Browser-Werkzeuge. Legen Sie ihn einmal mit `scrapling mcp --executable-path "/path/to/chromium"` oder der Umgebungsvariable `SCRAPLING_EXECUTABLE_PATH` fest, oder pro Anfrage mit dem Argument `executable_path`. Von @samrusani in [#360](https://github.com/D4Vinci/Scrapling/pull/360) (löst [#347](https://github.com/D4Vinci/Scrapling/issues/347))+- **Alle Browser und Fingerprints wurden aktualisiert**. Führen Sie nach dem Update `scrapling install --force` aus, um sie zu erneuern.++### 🐛 Fehlerbehebungen {#v0.4.10-bug-fixes}++- **Unlesbarer Text (Mojibake) von Browser-Fetchern auf Websites ohne UTF-8 wurde behoben**, von @yehudalevy-collab in [#365](https://github.com/D4Vinci/Scrapling/pull/365) (behebt [#364](https://github.com/D4Vinci/Scrapling/issues/364)).+- **Behoben: `LinkExtractor` filterte zusammengesetzte Dateiendungen wie `.tar.gz` nicht**, von @renbkna in [#359](https://github.com/D4Vinci/Scrapling/pull/359) (behebt [#349](https://github.com/D4Vinci/Scrapling/issues/349)).+- **Der Verlust laufender Anfragen in Checkpoints pausierter Crawls wurde behoben. Beim Fortsetzen werden sie jetzt nicht mehr übersprungen**, von @yetval in [#358](https://github.com/D4Vinci/Scrapling/pull/358).+- **Falsch berechnete Crawl-Wartezeiten aus den robots.txt-Regeln `Request-rate` wurden behoben**, durch das Protego-Update und angepasste Tests von @Disaster-Terminator in [#355](https://github.com/D4Vinci/Scrapling/pull/355).++### Dokumentation {#v0.4.10-docs}++- **Das Zusammenspiel von `init_script` mit dem isolierten Ausführungskontext von Patchright im Stealth-Modus wurde erklärt**, von @mturac in [#353](https://github.com/D4Vinci/Scrapling/pull/353) (löst [#350](https://github.com/D4Vinci/Scrapling/issues/350)).+- **Die Installation des Agent Skills über [skills.sh](https://skills.sh/D4Vinci/Scrapling) wurde hinzugefügt**, von @ob-aion in [#363](https://github.com/D4Vinci/Scrapling/pull/363).++## [v0.4.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.9) - 2026-06-07 {#v0.4.9}++**Ein Wartungsupdate mit vielen Fehlerbehebungen zu Meldungen aus der Community 🛠️**++### 🚀 Neuerungen und Verbesserungen der Bedienung {#v0.4.9-new-stuff-and-quality-of-life-changes}++- **Alle Browser und Fingerprints wurden aktualisiert**. Führen Sie nach dem Update `scrapling install --force` aus, um sie zu erneuern.+- **Die Option `--version` wurde zur CLI hinzugefügt**, von @ETM-Code in [#303](https://github.com/D4Vinci/Scrapling/pull/303) (löst [#299](https://github.com/D4Vinci/Scrapling/issues/299))++### 🐛 Fehlerbehebungen {#v0.4.9-bug-fixes}++- **Behoben: Das Argument `proxy` auf Sitzungsebene wurde in HTTP-Sitzungen ohne Hinweis ignoriert**, wodurch Ihre echte IP sichtbar werden konnte (löst [#295](https://github.com/D4Vinci/Scrapling/issues/295)). Wenn Sie jetzt einen `proxy` auf Sitzungsebene mit dem Argument `proxies` pro Anfrage kombinieren (oder umgekehrt), wird ein Fehler ausgelöst. Es wird nicht mehr eines der Argumente ohne Hinweis verworfen.+- **Fehler bei der Browser-Navigation beim Kombinieren von `init_script` mit `user_data_dir` wurden behoben** (löst [#294](https://github.com/D4Vinci/Scrapling/issues/294)).+- **Die Erkennung der Zeichenkodierung wurde korrigiert, wenn Websites den charset-Wert im Header `Content-Type` in Anführungszeichen setzen**, von @Bortlesboat in [#323](https://github.com/D4Vinci/Scrapling/pull/323).+- **Ein `IndexError` beim adaptiven Wiederfinden von Elementen mit aktiviertem `auto_save` wurde behoben**, von @Mubashirrrr in [#340](https://github.com/D4Vinci/Scrapling/pull/340).+- **Abstürze beim Speichern von Checkpoints und Cache der Spider unter Windows wurden behoben**, von @MrStarkEG in [#344](https://github.com/D4Vinci/Scrapling/pull/344).+- **Falsche Ähnlichkeitswerte in `find_similar` für Elemente mit unterschiedlich vielen Attributen wurden korrigiert** (löst [#322](https://github.com/D4Vinci/Scrapling/issues/322)).++### Dokumentation {#v0.4.9-docs}++- **Es wurde klargestellt, dass die Standardinstallation nur den Parser enthält** und Fetcher sowie Spider die Extras benötigen (löst [#343](https://github.com/D4Vinci/Scrapling/issues/343)).+- **Der Name des Docker-Images wurde in den übrigen Beispielen korrigiert**, von @evanclan in [#315](https://github.com/D4Vinci/Scrapling/pull/315).+- **Ein defekter Link in der Beitragsanleitung wurde korrigiert**, von @Bortlesboat in [#320](https://github.com/D4Vinci/Scrapling/pull/320).++## [v0.4.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.8) - 2026-05-11 {#v0.4.8}++**Ein großes Spider-Update, das das Crawl-System weiter verbessert 🕷️**++### 🚀 Neuerungen und Verbesserungen der Bedienung {#v0.4.8-new-stuff-and-quality-of-life-changes}++- **Das Werkzeug `LinkExtractor` wurde hinzugefügt**, unter `scrapling.spiders.LinkExtractor`, um URLs aus einer `Response` zu lesen. Es bietet viele Einstellmöglichkeiten (siehe [Dokumentation](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import LinkExtractor++ extractor = LinkExtractor(allow=r"/posts/", deny_domains=["ads.example.com"])+ ```++- **Die allgemeinen Spider-Vorlagen `CrawlSpider` und `CrawlRule` wurden hinzugefügt**. Sie müssen damit nicht mehr immer denselben Code für „Links verfolgen, die zu diesem Muster passen“ schreiben. Überschreiben Sie `rules()`, um eine Liste von `CrawlRule`-Objekten zurückzugeben, die jeweils mit einem `LinkExtractor` verbunden sind. (Siehe [Dokumentation](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import CrawlSpider, CrawlRule, LinkExtractor++ class QuotesSpider(CrawlSpider):+ name = "blog"+ start_urls = ["https://quotes.toscrape.com/"]++ def rules(self):+ return [+ CrawlRule(LinkExtractor(allow=r"/author/"), callback=self.parse_author),+ CrawlRule(LinkExtractor(allow=r"/page/\d+/")), # pagination, no callback+ ]++ async def parse_author(self, response):+ yield {+ "name": response.css(".author-title::text").get(),+ "birthday": response.css(".author-born-date::text").get(),+ "url": response.url,+ }+ ```++- **Die Vorlage `SitemapSpider` wurde hinzugefügt**. Sie startet einen Crawl direkt aus einer Sitemap oder über URLs zu `robots.txt`-Dateien. Sie verarbeitet gzip-komprimierte Sitemaps und bietet viele Einstellmöglichkeiten. URLs werden über die Crawl-Regeln zugeordnet, wie oben für **CrawlSpider** gezeigt. (Siehe [Dokumentation](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import SitemapSpider, CrawlRule, LinkExtractor++ class NewsSitemap(SitemapSpider):+ name = "news"+ sitemap_urls = ["https://example.com/robots.txt"]++ def rules(self):+ return [+ CrawlRule(LinkExtractor(allow=r"/articles/"), callback=self.parse_article),+ ]++ async def parse_article(self, response):+ yield {"url": response.url, "title": response.css("h1::text").get()}+ ```++- **Das adaptive Wiederfinden nutzt jetzt in allen Methoden standardmäßig eine Ähnlichkeitsschwelle von 40 %** statt `0`. Dadurch arbeitet die adaptive Funktion besser. Wenn kein Element den Grenzwert überschreitet, zeigt eine Warnung jetzt den höchsten gefundenen Wert an. So können Sie `percentage` bei Bedarf bewusst senken.++- **Alle Browser und Fingerprints wurden aktualisiert**. Führen Sie nach dem Update erneut `scrapling install --force` aus, um die Browser und Fingerprints zu erneuern.++### 🐛 Fehlerbehebungen {#v0.4.8-bug-fixes}++- **Behoben: `Fetcher.configure(...)` wurde nicht auf Aufrufe einzelner Anfragen angewendet**. Dieselbe Korrektur gilt für `AsyncFetcher`.+- **Falsche Anfrage-Fingerprints, die zu doppelten Anfragen in Spidern führten, wurden korrigiert**, von @yetval in [#255](https://github.com/D4Vinci/Scrapling/pull/255).+- **Die adaptive Scraping-Engine warnt jetzt bei schwachen Übereinstimmungen.** Zusammen mit der geänderten Schwelle erhalten Sie bei fehlgeschlagenem Wiederfinden jetzt eine Warnung statt eines irreführenden Elements als „beste Schätzung“.++### Dokumentation {#v0.4.8-docs}++- **Ältere Codebeispiele wurden in der gesamten Dokumentation aktualisiert**, damit sie zur aktuellen Version passen.+- **Das Kopieren und Einfügen von Code auf der Dokumentationswebsite wurde verbessert**, und der Agent Skill wurde gekürzt, damit er bei jedem Aufruf weniger Tokens benötigt.++## [v0.4.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.7) - 2026-04-17 {#v0.4.7}++**Ein Update, mit dem Ihre KI-Agenten Seiten sehen können 📸**++### 🚀 Neuerungen und Verbesserungen der Bedienung {#v0.4.7-new-stuff-and-quality-of-life-changes}++- **Das MCP-Werkzeug `screenshot` wurde hinzugefügt**. Es erstellt ein Bild der Seite und gibt es als echten MCP-Block vom Typ `ImageContent` zurück, damit das Modell es sehen kann. Das Werkzeug braucht eine offene Browser-Sitzung. Rufen Sie daher zuerst `open_session` auf (mit `dynamic` oder `stealthy`) und übergeben Sie hier die `session_id`. Unterstützt werden PNG und JPEG, Aufnahmen ganzer Seiten, JPEG-Qualität und die üblichen Warteeinstellungen (`wait`, `wait_selector`, `network_idle`, `timeout`). (Setzt [#244](https://github.com/D4Vinci/Scrapling/issues/244) um)+- **Ein eigener Parameter `session_id` wurde zu `open_session` hinzugefügt**. So können Sie Sitzungen sinnvoll benennen (`"search"`, `"checkout"`), statt den zufälligen hexadezimalen Standardwert mit 12 Zeichen zu nutzen. Von @hauntedhost in [#243](https://github.com/D4Vinci/Scrapling/pull/243)++### 🐛 Fehlerbehebungen {#v0.4.7-bug-fixes}++- **Fehler im Zustand von `FetcherSession` und ein Absturz beim Schließen einer verzögert gestarteten Sitzung wurden behoben**. Von @yetval in [#245](https://github.com/D4Vinci/Scrapling/pull/245)+- **`TypeError: Session.request() got an unexpected keyword argument 'block_ads'` wurde behoben**, wenn die CLI-Option `--ai-targeted` mit HTTP-Befehlen verwendet wird. Von @voidborne-d in [#249](https://github.com/D4Vinci/Scrapling/pull/249) (behebt [#247](https://github.com/D4Vinci/Scrapling/issues/247))++### Übersetzungen {#v0.4.7-translations}++- **Eine brasilianisch-portugiesische Übersetzung der README wurde hinzugefügt**, von @rgomids in [#250](https://github.com/D4Vinci/Scrapling/pull/250)++## [v0.4.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.6) - 2026-04-13 {#v0.4.6}++**Ein Update mit Schwerpunkt auf Browser-Tarnung, Datenschutz und der Arbeit von Entwicklern 🔒**++### 🚀 Neuerungen und Verbesserungen der Bedienung {#v0.4.6-new-stuff-and-quality-of-life-changes}++- **Integrierter Werbeblocker für Browser-Fetcher hinzugefügt**. Übergeben Sie `block_ads=True`, um Anfragen an etwa 3.500 bekannte Werbe- und Tracking-Domains direkt beim Abfangen der Route zu blockieren: kein DNS, kein TCP, sofortiger Abbruch. Mit `blocked_domains` können Sie eigene Listen ergänzen. Der MCP-Server und der CLI-Modus `--ai-targeted` schalten dies automatisch ein, um Tokens zu sparen und Seiten schneller zu laden.++ ```python+ page = StealthyFetcher.fetch('https://example.com', block_ads=True)+ ```++- **Unterstützung für DNS-over-HTTPS hinzugefügt**, um DNS-Lecks bei der Nutzung von Proxys zu vermeiden. Übergeben Sie `dns_over_https=True`, um DNS-Anfragen über Cloudflares DoH-Dienst zu leiten. So wird Ihr echter Standort nicht durch die DNS-Auflösung sichtbar, auch wenn Ihr HTTP-Verkehr durch einen Proxy läuft.++ ```python+ page = StealthyFetcher.fetch('https://example.com', proxy='http://proxy:8080', dns_over_https=True)+ ```++- **Der Callback `page_setup` wurde für Browser-Fetcher hinzugefügt**. Diese Funktion läuft vor `page.goto()`. Damit können Sie Ereignis-Listener, Routen oder Skripte registrieren, die vor der Navigation eingerichtet sein müssen. Sie ergänzt `page_action` (wird nach der Navigation ausgeführt). (Löst [#237](https://github.com/D4Vinci/Scrapling/issues/237))++ ```python+ def capture_websockets(page):+ page.on("websocket", lambda ws: print(f"WS: {ws.url}"))++ page = DynamicFetcher.fetch('https://example.com', page_setup=capture_websockets)+ ```++- **Die CLI-Optionen `--block-ads` und `--dns-over-https` wurden hinzugefügt**, sowohl für `fetch` als auch für `stealthy-fetch`.++### 🐛 Fehlerbehebungen {#v0.4.6-bug-fixes}++- **Der Typalias `Seconds` wurde korrigiert**, der Dezimalwerte ablehnte. `wait=1.5` oder `timeout=500.0` verursachten bei Browser-Fetchern einen Typfehler, weil der Alias `float` fälschlich als Metadaten statt als Typ behandelte. Von @kuishou68 in [#240](https://github.com/D4Vinci/Scrapling/pull/240)+- **Doppelte ID-Abschnitte beim Erzeugen vollständiger Selektorpfade wurden behoben**. Bei Elementen mit `id`-Attributen wurde der Selektor beim Erzeugen vollständiger CSS/XPath-Pfade doppelt angehängt. Das führte zu Selektoren wie `body > #main > #main > #target > #target`. Auch alleinstehende Bedingungen wie `[@id='x']` (ungültiges XPath) statt `*[@id='x']` in vollständigen XPath-Pfaden wurden korrigiert. Von @sjhddh in [#241](https://github.com/D4Vinci/Scrapling/pull/241)+- **Fehlende Parameter in den Shell-Signaturen wurden ergänzt**. In den Funktionssignaturen der interaktiven Shell fehlten `blocked_domains`, `block_ads`, `retries`, `retry_delay`, `capture_xhr`, `executable_path` und `dns_over_https`.++## [v0.4.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.5) - 2026-04-07 {#v0.4.5}++**Ein Update mit einer großen Erleichterung für Spider-Entwickler und einigen wichtigen Fehlerbehebungen 🎉**++### 🚀 Neuerungen und Verbesserungen der Bedienung {#v0.4.5-new-stuff-and-quality-of-life-changes}++- **Entwicklungsmodus für Spider**: Änderungen an der `parse()`-Logik eines Spiders erforderten bisher bei jedem Lauf neue Zugriffe auf die Zielserver. Das ist langsam, erzeugt unnötigen Verkehr und kann dazu führen, dass der Server Ihre Anfragerate begrenzt, während Sie noch an den Selektoren arbeiten. Der neue Entwicklungsmodus speichert beim ersten Lauf jede Antwort auf der Festplatte und liest sie bei späteren Läufen wieder von dort. So können Sie Ihre Callbacks ändern und beliebig oft neu starten, ohne eine einzige Netzwerkanfrage zu senden. Aktivieren Sie ihn mit einem Klassenattribut:++ ```python+ class MySpider(Spider):+ name = "my_spider"+ start_urls = ["https://example.com"]+ development_mode = True++ async def parse(self, response):+ yield {"title": response.css("title::text").get("")}+ ```++ Der Cache liegt standardmäßig unter `.scrapling_cache/{spider.name}/`. Mit `development_cache_dir` können Sie ihn an einen anderen Ort verlegen. Zwei neue Zähler, `cache_hits` und `cache_misses`, zeigen die Cache-Nutzung. Beim Lesen aus dem Cache werden `download_delay`, Begrenzungen der Anfragerate und erneute Versuche für gesperrte Anfragen übersprungen. So sind die Testläufe so schnell, wie die Festplatte es zulässt. Setzen Sie `development_mode = True` nicht im Produktivbetrieb ein. Das ist ein Entwicklungswerkzeug, kein Produktions-Cache. Alle Einzelheiten stehen in der [Dokumentation](spiders/advanced.md#development-mode).++- **Sicherere Weiterleitungen als Standard**: `follow_redirects` hat jetzt bei allen HTTP-Fetchern, im MCP-Server und in der Shell den Standardwert `"safe"`. Weiterleitungen werden weiterhin verfolgt, aber Ziele mit internen oder privaten IP-Adressen (Loopback, private Netzwerke, Link-Local) werden abgelehnt. Das schützt vor SSRF beim Scraping von URLs, die Benutzer eingeben. Übergeben Sie `follow_redirects="all"` für das bisherige Verhalten oder `False`, um Weiterleitungen ganz abzuschalten.++### 🐛 Fehlerbehebungen {#v0.4.5-bug-fixes}++- **Ein erzwungener Stopp verliert Ihren Checkpoint nicht mehr**: Zweimaliges Drücken von Ctrl+C (erzwungener Stopp) bei einem Spider mit aktiviertem `crawldir` konnte bisher mit dem Schreiben des Checkpoints kollidieren. Der Cancel-Scope beendete die Aufgabe, bevor das Pickle fertig war. Dabei blieb `paused=False` gesetzt und die Bereinigung wurde ausgelöst, die den vorherigen Checkpoint *löscht*. Bei einem langen Crawl konnte so der gesamte Fortschritt verloren gehen, den Sie gerade sichern wollten. Die Engine schreibt den Checkpoint jetzt **vor** dem Aufruf von `cancel_scope.cancel()`. So bleibt bei einem erzwungenen Stopp immer der neueste ausstehende Zustand erhalten. Von @voidborne-d in [#230](https://github.com/D4Vinci/Scrapling/pull/230).++## [v0.4.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.4) - 2026-04-05 {#v0.4.4}++**Ein neues Update mit wichtigen Spider-Verbesserungen und Fehlerbehebungen 🎉**++### 🚀 Neuerungen und Verbesserungen der Bedienung {#v0.4.4-new-stuff-and-quality-of-life-changes}+- **Das Spider-System beachtet jetzt robots.txt** über die neue Option `robots_txt_obey`. Wenn sie aktiviert ist, ruft der Spider robots.txt vor dem Crawl automatisch ab und hält sich an die Regeln, darunter `Disallow`, `Crawl-delay` und `Request-rate`. Die robots.txt-Dateien werden parallel abgerufen und pro Domain für den gesamten Crawl im Cache gespeichert. Von @AbdullahY36 in [#226](https://github.com/D4Vinci/Scrapling/pull/226)+- **Der robots.txt-Cache wird jetzt vorab gefüllt**. Alle robots.txt-Dateien der Domains aus start_urls werden vor Beginn der Crawl-Schleife abgerufen und geparst. So gibt es bei der ersten Anfrage an eine Domain keine zusätzliche Wartezeit.+- **Die neue Statistik `robots_disallowed_count` wurde zu `CrawlStats` hinzugefügt**, um die während eines Crawls durch robots.txt-Regeln blockierten Anfragen zu zählen.++Weitere Informationen finden Sie auf der Website [hier](spiders/getting-started.md#robotstxt-compliance)++### 🐛 Fehlerbehebungen {#v0.4.4-bug-fixes}+- **Ein schwerwiegendes MRO-Problem mit `ProxyRotator` wurde behoben**: Die Platzhaltermethode `_build_context_with_proxy` verdeckte die tatsächliche Implementierung der Unterklassen. Dadurch löste die Proxy-Rotation immer `NotImplementedError` aus (behebt [#215](https://github.com/D4Vinci/Scrapling/issues/215)). Danke, @yetval+- **Ein Leck im Seiten-Pool wurde behoben**, das bei Proxy-Rotation pro Anfrage in Browser-Sitzungen auftrat. Seiten aus temporären Kontexten wurden bei der Bereinigung nicht aus dem Pool entfernt, sodass sich mit der Zeit veraltete Referenzen ansammelten. Von @yetval in [#223](https://github.com/D4Vinci/Scrapling/pull/223)+- **Eine fehlende Typprüfung im statischen Fetcher wurde ergänzt**. `curl_cffi` konnte den Wert `None` aus `session.request()` zurückgeben, was später zu Fehlern führte.++### Weitere Änderungen {#v0.4.4-other}+- Die Abhängigkeiten wurden aktualisiert, einschließlich der neuesten Fingerprints und weiterer Bestandteile.+- `protego` wurde als neue Abhängigkeit in der optionalen Gruppe `fetchers` hinzugefügt, um robots.txt zu parsen.++## [v0.4.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.3) - 2026-03-30 {#v0.4.3}++**Ein neues Update mit vielen wichtigen Änderungen 🎉**++### 🚀 Neuerungen und Verbesserungen der Bedienung {#v0.4.3-new-stuff-and-quality-of-life-changes}+- **Ein neues MCP-Werkzeug wurde hinzugefügt**, um einen dauerhaften normalen oder getarnten Browser zu öffnen und mit den anderen Werkzeugen weiterzuverwenden. Ein weiteres neues Werkzeug schließt ihn. ([Beispiele](https://github.com/D4Vinci/Scrapling/blob/v0.4.3/docs/ai/mcp-server.md#examples))+- **Ein neues MCP-Werkzeug wurde hinzugefügt**, das alle vorhandenen Browser-Sitzungen auflistet. Es ist für die Nutzung mit den neuen Werkzeugen gedacht.+- **Eine neue Option für Browser-Sitzungen wurde hinzugefügt**, die während einer Anfrage automatisch alle Hintergrundanfragen sammelt (löst [#159](https://github.com/D4Vinci/Scrapling/pull/159)) [[Beispiele](https://github.com/D4Vinci/Scrapling/blob/v0.4.3/docs/fetching/dynamic.md#capturing-xhrfetch-requests)].+- **Eine neue Bereinigung wurde hinzugefügt**, um den MCP-Server durch das Entfernen versteckter oder unsichtbarer Inhalte vor üblichen Prompt-Injection-Angriffen zu schützen.+- **Eine neue Kommandozeilenoption namens `--ai-targeted` wurde hinzugefügt**, um die Ausgabe der Web-Scraping-Befehle für KI aufzubereiten und wie beim MCP-Server vor üblichen Prompt-Injection-Angriffen zu schützen.+- **Eine neue Option für Browser-Sitzungen namens `executable_path` wurde hinzugefügt**, um einen eigenen Browser-Pfad anzugeben (löst [#202](https://github.com/D4Vinci/Scrapling/pull/202))+- **Der Code des MCP-Servers wurde umstrukturiert**, um die Wartung zu vereinfachen. Alle Werkzeuge arbeiten jetzt asynchron.+- **Der Code der CLI-Befehle wurde umstrukturiert**, um die Wartung zu vereinfachen und ihn um 210 Zeilen zu kürzen.++### 🐛 Fehlerbehebungen {#v0.4.3-bug-fixes}+- Korrektur zur Beibehaltung der HTTP-Methode bei erneuten Versuchen in einer Spider-Sitzung, von @karesansui-u in [#201](https://github.com/D4Vinci/Scrapling/pull/201)+- Eine Höchstzahl für erneute Versuche zum Abrufen des Seiteninhalts wurde hinzugefügt, um Endlosschleifen zu vermeiden, von @haosenwang1018 und @D4Vinci in [#197](https://github.com/D4Vinci/Scrapling/pull/197)+- Ein alleinstehendes `raise` wurde durch `return False` in `_restore_from_checkpoint` ersetzt, von @haosenwang1018 in [#196](https://github.com/D4Vinci/Scrapling/pull/196)+- `get_all` wurde durch `getall` in `Texthandler` ersetzt, um zur Klasse Selector zu passen.++### Verbesserungen der Tests und Testabdeckung {#v0.4.3-coverage-tests-improvement}+- Tests für Randfälle von `_normalize_credentials` wurden hinzugefügt, von @Bortlesboat in [#192](https://github.com/D4Vinci/Scrapling/pull/192)+- Tests für das Speichern und anschließende Abrufen sowie für die grundlegende Speicherung wurden hinzugefügt, von @haosenwang1018 in [#193](https://github.com/D4Vinci/Scrapling/pull/193)+- Testabdeckung für die Regex-Pfade von `TextHandler` und `TextHandlers.re()` wurde hinzugefügt, von @haosenwang1018 in [#194](https://github.com/D4Vinci/Scrapling/pull/194)+- Tests für Randfälle von `filter`, `iterancestors` und `find_similar` wurden hinzugefügt, von @awanawana in [#200](https://github.com/D4Vinci/Scrapling/pull/200)++### Verbesserungen am Agent Skill {#v0.4.3-agent-skill-improvement}+- Defekte Markdown-Links in den Skill-Referenzen wurden korrigiert, von @yetval in [#204](https://github.com/D4Vinci/Scrapling/pull/204)+- Die Struktur des Skills wurde verbessert, damit sie die Prüfung von [Clawhub](https://clawhub.ai/d4vinci/scrapling-official) besser erfüllt.+- Der Skill muss jetzt beim Scraping über die Kommandozeile die Option `--ai-targeted` verwenden.++### Verbesserungen der Dokumentation {#v0.4.3-docs-improvement}+- Eine koreanische README-Übersetzung wurde hinzugefügt, von @greatsk55 in [#187](https://github.com/D4Vinci/Scrapling/pull/187)+- Abstände zwischen CJK- und lateinischen Zeichen in den chinesischen und japanischen READMEs wurden korrigiert.+- Defekte Links aus dem alten Website-Design wurden korrigiert.++## [v0.4.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.2) - 2026-03-08 {#v0.4.2}++**Ein neues Wartungsupdate mit wichtigen Änderungen**++#### Fehlerbehebungen {#v0.4.2-bug-fixes}+- Die Funktion `get_all_text()` erfasst jetzt auch Textknoten, die auf Elemente folgen. Dadurch können der MCP-Server und die Befehle Text lesen, der zuvor fehlte ([#168](https://github.com/D4Vinci/Scrapling/pull/168)). Danke @mhillebrand+- Referer gibt jetzt die einfache Google-URL statt einer Google-Such-URL zurück. Die bisherige Logik war falsch und konnte ein Merkmal zur Erkennung des Browser-Fingerabdrucks erzeugen ([#179](https://github.com/D4Vinci/Scrapling/pull/179)). Danke @Bortlesboat+- Ein Problem beim Zusammenfügen zusätzlicher Startoptionen wurde in allen Browsern behoben. Danke @rostchri+- Ein Problem mit Typannotationen wurde behoben, das bei Python-Versionen vor 3.12 zu Abstürzen führte. (Behebt [#163](https://github.com/D4Vinci/Scrapling/issues/163))++#### Sonstige Änderungen {#v0.4.2-other}+- Ein Agent Skill für Claude Code / OpenClaw und andere Werkzeuge für KI-Agenten wurde hinzugefügt.+- Der Agent Skill wurde zu Clawhub hinzugefügt.+- Alle Browser und Playwright wurden auf die neuesten Versionen aktualisiert.+- Eine französische Übersetzung der Haupt-README wurde hinzugefügt.++## [v0.4.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.1) - 2026-02-27 {#v0.4.1}++**Ein neues Update mit vielen wichtigen Änderungen**++### 🚀 Neuerungen und Verbesserungen der Bedienung {#v0.4.1-new-stuff-and-quality-of-life-changes}+- **Genauere reguläre Ausdrücke** zur Erkennung von Cloudflare-Challenges (Danke an @Rinz27 [#133](https://github.com/D4Vinci/Scrapling/pull/133))+- **Schnellere und effizientere Lösung** von Cloudflare-Challenges. Sie ist jetzt fast doppelt so schnell.+- **Verbesserte Lösung von Cloudflare-Challenges** für Websites, die manchmal zweimal die Cloudflare-Seite anzeigen, bevor sie zur eigentlichen Website weiterleiten.+- **Bessere Tarnung und höhere Geschwindigkeit des getarnten Browsers** durch das Entfernen der injizierten JS-Dateien.+- **Verbessertes MCP-Schema**, das von OpenCode akzeptiert wird (Danke an @robin-ede [#137](https://github.com/D4Vinci/Scrapling/pull/137))+- **Noch bessere Übereinstimmung des MCP-Schemas mit dem Protokoll**, damit VS Code Copilot und andere streng prüfende Werkzeuge es akzeptieren. (Behebt #150 )+- **Deutlich geringerer Token-Verbrauch des MCP-Servers**, weil unnötige HTML-Tags bei aktivierter Option `main_content_only` entfernt werden.+- Die PyPI-Seite wurde korrigiert. Dateien zur Registrierung des MCP-Servers im MCP-Serververzeichnis wurden hinzugefügt.+- Ein neues Codebeispiel zeigt, wie Sie die Browser-Abhängigkeiten per Code statt über die Kommandozeile installieren, um die Automatisierung zu erleichtern.+- Alle Workflows wurden durch die Verwendung der neuesten Action-Versionen verbessert (Danke an @salmanmkc [#143](https://github.com/D4Vinci/Scrapling/pull/143)/[#144](https://github.com/D4Vinci/Scrapling/pull/144))++## [v0.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4) - 2026-02-15 {#v0.4}++**Die bisher größte Scrapling-Version: Spider-Framework, Proxy-Rotation und große Verbesserungen am Parser**++Diese Version bringt ein vollständig asynchrones Spider- und Crawling-Framework, intelligente Proxy-Verwaltung und wichtige API-Änderungen, die Scrapling leistungsfähiger und einheitlicher machen. Lesen Sie vor dem Update den Abschnitt zu inkompatiblen Änderungen sorgfältig durch.++### 🕷️ Spider-Framework {#v0.4-spider-framework}++Ein neues asynchrones Crawling-Framework auf Basis von `anyio` für strukturiertes Scraping in großem Umfang:++```python+from scrapling.spiders import Spider, Response++class MySpider(Spider):+ name = "demo"+ start_urls = ["https://example.com/"]++ async def parse(self, response: Response):+ for item in response.css('.product'):+ yield {"title": item.css('h2::text').get()}++MySpider().start()+```++- **Spider-API ähnlich wie in Scrapy**: Definieren Sie Spider mit `start_urls`, asynchronen `parse`-Callbacks, `Request`/`Response`-Objekten und einer Prioritätswarteschlange.+- **Gleichzeitiges Crawling**: Einstellbare Grenzen für gleichzeitige Anfragen, Drosselung je Domain und Wartezeiten zwischen Downloads.+- **Unterstützung mehrerer Sitzungen**: Einheitliche Schnittstelle für HTTP-Anfragen und getarnte Browser ohne sichtbares Fenster in einem Spider. Leiten Sie Anfragen anhand der ID an verschiedene Sitzungen weiter. Sitzungen lassen sich bei Bedarf starten.+- **Pausieren und Fortsetzen**: Der Zustand des Crawls wird mit Checkpoints gespeichert. Drücken Sie Ctrl+C für ein geordnetes Beenden und starten Sie dann erneut, um an derselben Stelle fortzufahren.+- **Streaming-Modus**: Empfangen Sie extrahierte Einträge sofort über `async for item in spider.stream()`, mit Statistiken in Echtzeit. Ideal für Benutzeroberflächen, Pipelines und lange Crawls.+- **Erkennung blockierter Anfragen**: Blockierte Anfragen werden automatisch erkannt und wiederholt. Die Logik ist anpassbar.+- **Integrierter Export**: Exportieren Sie Ergebnisse über Hooks und Ihre eigene Pipeline oder nutzen Sie den integrierten JSON/JSONL-Export mit `result.items.to_json()` bzw. `result.items.to_jsonl()`.+- **Hooks für den Lebenszyklus**: `on_start()`, `on_close()`, `on_error()`, `on_scraped_item()` und weitere Hooks bieten volle Kontrolle über den Ablauf des Crawls.+- **Detaillierte Crawl-Statistiken**: Verfolgen Sie Anfragen, Antworten, Bytes, Statuscodes, Proxys, Details je Domain und Sitzung, die Anzahl der Logmeldungen je Stufe und mehr.+- **uvloop-Unterstützung**: Übergeben Sie `use_uvloop=True` an `spider.start()`, um die asynchrone Ausführung zu beschleunigen, wenn uvloop verfügbar ist.++Ein neuer Abschnitt auf der Website enthält alle Details. Klicken Sie [hier](spiders/architecture.md)++### 🔄 Proxy-Rotation {#v0.4-proxy-rotation}++* Neue Klasse `ProxyRotator` mit threadsicherer Rotation. Sie funktioniert mit allen Fetchern und Sitzungen:++ ```python+ from scrapling import ProxyRotator+ rotator = ProxyRotator(["http://proxy1:8080", "http://proxy2:8080"])+ Fetcher.get(url, proxy_rotator=rotator)+ ```++* **Eigene Rotationsstrategien**: Erstellen Sie Ihre eigene Logik zur Proxy-Rotation+* **Proxy je Anfrage ersetzen**: Übergeben Sie `proxy=` an einen einzelnen Aufruf von `get()`/`post()`/`fetch()`, um für diese Anfrage einen anderen Proxy als den der Sitzung zu verwenden.++### 🌐 Verbesserungen an Browser-Fetchern {#v0.4-browser-fetcher-improvements}++* **Domains blockieren**: Neuer Parameter `blocked_domains` in `DynamicFetcher`/`StealthyFetcher`, um Anfragen an bestimmte Domains zu blockieren. Subdomains werden automatisch einbezogen.+* **Automatische Wiederholungen**: Browser-Fetcher wiederholen fehlgeschlagene Anfragen jetzt mit den Parametern `retries` (Standard: 3) und `retry_delay` (Standard: 1s). Dazu gehört die Erkennung von Proxy-Fehlern.+* **Antwortmetadaten**: Das Dictionary `Response.meta` speichert automatisch den verwendeten Proxy und übernimmt die Metadaten der Anfrage.+* **Response.follow()**: Erstellen Sie `Request`-Objekte für Folgeanfragen mit automatischer Referer-Verwaltung. Diese Funktion ist für das Spider-System vorgesehen.+* **Keine automatische Wiedergabe**: Browser-Sitzungen blockieren jetzt automatisch abgespielte Inhalte, die zuvor Probleme verursacht haben.+* **Geschwindigkeit**: Bessere Tarnung und höhere Geschwindigkeit durch angepasste Browser-Startoptionen.++### 🔧 Fehlerbehebungen und Verbesserungen {#v0.4-bug-fixes-improvements}+- **Parser-Optimierung**: Der Parser wurde für wiederholte Vorgänge optimiert, um die Leistung zu verbessern.+- **Fehlerhafte Seiten**: Ein Fehler wurde behoben, durch den der Browser bei Seitenfehlern nicht geschlossen wurde.+- **Leerer Inhalt**: Antworten mit leerem Body werden verarbeitet.+- **Playwright-Schleife**: Ein Problem wurde behoben, bei dem die Playwright-Schleife nach einer fehlgeschlagenen CDP-Verbindung offen blieb+- **Typsicherheit**: Alle mypy-Fehler wurden behoben. Typannotationen wurden in bisher untypisierten Funktionskörpern ergänzt. mypy und pyright wurden zum CI-Workflow hinzugefügt.++### ⚠️ Inkompatible Änderungen {#v0.4-breaking-changes}++* **`css_first`/`xpath_first` entfernt**: Verwenden Sie stattdessen `css('.selector').first`, `css('.selector')[0]` oder `css('.selector').get()`.+* **Alle Auswahlmethoden geben jetzt `Selectors` zurück**: `css('::text')`, `xpath('//text()')`, `css('::attr(href)')` und `xpath('//@href')` geben jetzt `Selectors` zurück, wobei Textknoten in `Selector`-Objekte mit `tag="#text"` eingebettet werden. Zuvor wurde `TextHandlers` zurückgegeben. Das vereinheitlicht die API über alle Auswahlmethoden und Typannotationen hinweg.+* **`Response.body` ist immer `bytes`**: Zuvor konnte der Wert `str` oder `bytes` sein. Jetzt wird immer `bytes` zurückgegeben.+* **Verhalten von `get()`/`getall()`**: Bei `Selector` gibt `get()` ein `TextHandler`-Objekt zurück, also serialisiertes HTML oder einen Textwert. `getall()` gibt `TextHandlers` zurück. Aliase: `extract_first = get`, `extract = getall`. Das alte `get_all()` von `Selectors` wurde entfernt.+* **`Selectors.first`/`.last`**: Sicherer Zugriff, der `Selector | None` zurückgibt, statt `IndexError` auszulösen.+* **Interne Konstanten umbenannt**: `DEFAULT_FLAGS` → `DEFAULT_ARGS`, `DEFAULT_STEALTH_FLAGS` → `STEALTH_ARGS`, `HARMFUL_DEFAULT_ARGS` → `HARMFUL_ARGS`, `DEFAULT_DISABLED_RESOURCES` → `EXTRA_RESOURCES`.++### 🔨 Sonstige Änderungen {#v0.4-other-changes}++* **Geänderte Abhängigkeiten**: `tldextract` wurde durch `tld` ersetzt. Die interne Datei `_html_utils.py` wurde zugunsten von `w3lib.html.replace_entities` entfernt. `typing_extensions` ist jetzt zwingend erforderlich.+* **Überarbeitete Dokumentation**: Vollständiger Wechsel von MkDocs zu Zensical, ein neuer Abschnitt zur Spider-Dokumentation, aktualisierte bestehende Seiten und neue API-Referenzen.++## [v0.3.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.14) - 2026-01-03 {#v0.3.14}++**Ein kleines Wartungsupdate für Probleme, die mit v0.3.13 auf einigen Geräten aufgetreten sind**++- Der Inkognitomodus wurde in `StealthyFetcher` und seinen Sitzungsklassen deaktiviert, weil Cookies unter Windows dadurch nicht über mehrere Seiten hinweg erhalten blieben. Unter MacOS und Linux trat das nicht auf (Behebt [#123](https://github.com/D4Vinci/Scrapling/issues/123); danke an @frugality4121 für den Hinweis und an @gembleman für die Lösung).+- Die neueste browserforge-Version wurde fest vorgegeben, um Probleme mit alten Header-Modellen bei Benutzern zu lösen, die bereits eine alte browserforge-Version installiert hatten.++## [v0.3.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.13) - 2026-01-01 {#v0.3.13}++**Ein großes Update mit vielen Verbesserungen in vielen Bereichen, aber auch mit zahlreichen begründeten inkompatiblen Änderungen. Lesen Sie die folgenden Hinweise vor dem Update**++* Aus mehreren Gründen verwenden wir Camoufox ab jetzt nicht mehr. Falls die Entwicklung fortgesetzt wird, könnten wir in Zukunft darauf zurückkommen. Wenn Sie Camoufox wie vor dieser Version weiterverwenden möchten, finden Sie in diesem [Abschnitt](https://github.com/D4Vinci/Scrapling/blob/v0.3.13/docs/fetching/stealthy.md#using-camoufox-as-an-engine) eine Anleitung.++* Bisher haben wir patchright im Tarnmodus von `DynamicFetcher` und seinen Sitzungsklassen verwendet. Dieser Modus wurde dort entfernt. Stattdessen verwenden wir patchright jetzt in `StealthyFetcher` und seinen Sitzungsklassen, mit SEHR VIELEN Verbesserungen, wie Sie sehen werden. Sie verbessern die Tarnung zusätzlich zu den Funktionen von patchright.++**Dadurch sind `StealthyFetcher` und seine Sitzungsklassen 101 % schneller, benötigen weniger Arbeitsspeicher und Speicherplatz und haben etwa ~400 Codezeilen weniger. Vor allem sind sie stabiler als bei der früheren Verwendung von Camoufox.**++Das verkürzt auch die Installation mit `scrapling install`, verkleinert das Docker-Image, verbessert den Ablauf der Tests in der GitHub-CI und macht scrapling für neue Benutzer verständlicher.++### Inkompatible Änderungen {#v0.3.13-breaking-changes}+1. Das Argument `stealth` wurde aus `DynamicFetcher` und seiner Sitzungsklasse entfernt. `hide_canvas` wurde nach `StealthyFetcher` und in dessen Sitzungsklassen verschoben.+2. Das Argument `disable_webgl` wurde von `DynamicFetcher` in die Klasse `StealthyFetcher` verschoben und in `allow_webgl` umbenannt. Das gilt auch für alle Sitzungsklassen.+3. Die Klasse `StealthyFetcher` ist jetzt im Wesentlichen die neue getarnte Version von `DynamicFetcher`. Daher wurden diese Argumente entfernt: `block_images`, `humanize`, `addons`, `os_randomize`, `disable_ads` und `geoip`. Ich habe versucht, sie in Chromium nachzubilden, aber jedes davon hatte ein eigenes Problem. Das könnte sich in kommenden Versionen vor v0.4 ändern.++Nun zu den guten Nachrichten: Wir haben vieles verbessert und behoben :)++### Verbesserungen {#v0.3.13-improvements}+- Sie wissen bereits, dass `StealthyFetcher` und seine Sitzungsklassen jetzt 101 % schneller sind. Auch `DynamicFetcher` und seine Sitzungsklasse sind jetzt 20 % schneller.+- Der Algorithmus zum Lösen von Cloudflare-Challenges wurde verbessert, um schneller fertig zu werden und mehr Fälle abzudecken. Dank der überarbeiteten Struktur können Sie außerdem eine doppelt so schnelle Captcha-Lösung erwarten!+- Alle Fetcher benötigen jetzt weniger Arbeitsspeicher.+- Der MCP-Server verbraucht weniger Tokens und spart dadurch mehr Geld!+- Das Docker-Image ist jetzt 60 % kleiner.+- Die gesamte Dokumentationswebsite wurde um die neuen Funktionen ergänzt. Gleichzeitig wurden Erklärungen verständlicher, viele Abschnitte kürzer und weitere Beispiele sowie fehlende Argumente ergänzt. Die API-Referenz erhielt Diagramme, dazu kamen viele weitere Verbesserungen. Die Website lädt jetzt 130 % schneller, verbraucht weniger Daten und ist besser für SEO geeignet.++### Fehlerbehebungen {#v0.3.13-fixes}+- Fehlende Argumente wurden in den Kurzbefehlen der Web-Scraping-Shell ergänzt. Die Kurzbefehle wurden außerdem genauer gemacht.+- Ein Problem wurde behoben, bei dem `google_search` auch für localhost- oder IP-URLs einen Google-Referer erzeugte.++## [v0.3.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.12) - 2025-12-18 {#v0.3.12}++### Was sich geändert hat {#v0.3.12-what-s-changed}+- Die Klassen `DynamicSession`/`AsyncDynamicSession` haben ein neues Argument namens `timezone_id`. Damit können Sie die Zeitzone des Browsers an die des verwendeten Proxys oder VPNs anpassen. Websites können den Proxy dann nicht anhand unterschiedlicher Zeitzonen erkennen.+- Die automatische Umwandlung von Antworten in JSON wurde verbessert.+- Die interne Funktion `__create__` wurde in den Sitzungsklassen der Fetcher in `start` umbenannt, um die Verwendung außerhalb des `with`-Kontexts zu erleichtern.+- `curl_cffi` und weitere Abhängigkeiten wurden auf die neuesten Versionen aktualisiert.++## [v0.3.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.11) - 2025-12-03 {#v0.3.11}++### Was sich geändert hat {#v0.3.11-what-s-changed}+- Die Behandlung von Zeitüberschreitungen wurde verbessert, wenn `network_idle` auf instabilen Websites verwendet wird, etwa auf Seiten mit laufender Medienwiedergabe.+- Die Autovervollständigung für den Kurzbefehl `stealthy_fetch` in der Web-Scraping-Shell wurde korrigiert++## [v0.3.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.10) - 2025-11-26 {#v0.3.10}++**Ein Wartungsupdate mit vielen wichtigen und möglicherweise inkompatiblen Änderungen**++- **Alle Kodierungsprobleme behoben** durch einen besseren Ansatz, der Webseiten mit falsch deklarierter Kodierung verarbeitet (Danke an @Kemsty2 für den Einsatz und die Hinweise in [#110](https://github.com/D4Vinci/Scrapling/issues/110) [#111](https://github.com/D4Vinci/Scrapling/pull/111) )+- **Ein Logikproblem behoben**, das seit v0.3 beim Überschreiben von Sitzungsparametern durch Anfrageparameter in allen Browser-Fetchern bestand+- **Die Signaturen der Kurzbefehle korrigiert** in der interaktiven Web-Scraping-Shell. Dadurch funktioniert ihre Autovervollständigung vollständig. Auch dieses Problem bestand seit v0.3.+- **Die Maxmind-Datenbank aktualisiert**, was das Argument `geoip` von `StealthyFetcher` und seinen Sitzungsklassen verbessert.+- **Alle verwendeten Browser aktualisiert** auf die neuesten verfügbaren Versionen.+- **INKOMPATIBLE ÄNDERUNGEN**: Alle Fetcher wurden umfassend überarbeitet. Daraus ergeben sich einige interessante Änderungen, die Ihren Code beeinträchtigen könnten:+ 1. Der Code von Scrapling ist jetzt etwa ~750 Zeilen kürzer. Viele Änderungen erleichtern die künftige Wartung und verringern den Ressourcenverbrauch etwas.+ 2. Die Validierung aller Fetcher und ihrer Sitzungsklassen ist deutlich schneller, was auch ihre Gesamtgeschwindigkeit verbessert.+ 3. Dafür akzeptieren die Fetcher keine Positionsargumente außer `url` mehr. Alle übrigen Argumente müssen mit ihrem Namen übergeben werden. Verwenden Sie also `Fetcher.get('https://google.com', stealthy_headers=True)` statt `Fetcher.get('https://google.com', True)`, falls Sie das aus irgendeinem Grund bisher so gemacht haben!+ 4. Seit v0.3 gab es einen störenden Unterschied zwischen Browser-Fetchern und ihren Sitzungsklassen: Das Argument für Parser-Einstellungen je Anfrage hieß `custom_config`, in den Sitzungsklassen dagegen `selector_config`. Durch die Überarbeitung konnten wir den Namen zu `selector_config` vereinheitlichen, ohne Ihren Code zu beschädigen. Der Hauptname ist jetzt `selector_config`, das alte Argument `custom_config` bleibt aus Kompatibilitätsgründen unterstützt. Autovervollständigung gibt es nur für `selector_config`.+ 5. Dafür mussten auch die Typannotationen der Fetcher-Funktionen dynamisch erzeugt werden. Falls die Autovervollständigung in Ihrer IDE nicht richtig funktioniert, stellen Sie sicher, dass Sie eine aktuelle Version verwenden. Wir haben fast alle bekannten IDEs und Editoren getestet.++> Wir haben auch alle Benchmark-Tabellen mit den aktuellen Zahlen im Vergleich zu den neuesten Versionen aller alternativen Bibliotheken aktualisiert.++## [v0.3.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.9) - 2025-11-17 {#v0.3.9}++**Ein neues Update mit vielen wichtigen Änderungen**++### 🚀 Neuerungen und Verbesserungen der Bedienung {#v0.3.9-new-stuff-and-quality-of-life-changes}+- Das Argument `impersonate` in `Fetcher` und `FetcherSession` akzeptiert jetzt eine Browser-Liste. Die Bibliothek wählt daraus bei jeder Anfrage zufällig einen Browser aus.++```python+from scrapling.fetchers import FetcherSession++with FetcherSession(impersonate=['chrome', 'firefox', 'safari']) as s:+ s.get('https://github.com/D4Vinci/Scrapling')+```++- Ein neues Argument der Methode `clean` in `TextHandler` entfernt HTML-Entitäten einfach aus dem aktuellen Text.+- Große Verbesserungen an der Dokumentation mit genaueren Erklärungen vieler Bereiche und automatischen Übersetzungen der Hauptdatei `README.md`.++### 🐛 Fehlerbehebungen {#v0.3.9-bug-fixes}+- Ein großes Problem beim Abrufen von Antworten mit Browser-Fetchern wurde behoben. Eine intelligente Erkennung des Inhaltstyps stellt jetzt sicher, dass `response.body` nur bei HTML den vom Browser gerenderten Inhalt enthält. Andernfalls enthält es den Rohinhalt der letzten Anfrage. So können Sie Binär- und Textdateien herunterladen, ohne dass sie in HTML-Tags verpackt werden. Gleichzeitig können Sie weiterhin den gerenderten Inhalt einer Website abrufen, wenn Sie ihn benötigen.++### 🔨 Sonstige Änderungen {#v0.3.9-misc}+- Der Leitfaden für Beiträge wurde verständlicher und einfacher gestaltet.+- Ein neuer Workflow erzwingt die Verwendung der Werkzeuge zur Codequalität. Es sind dieselben wie bei den Pre-commit-Hooks.++## [v0.3.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.8) - 2025-10-27 {#v0.3.8}++**Ein neues Update mit vielen wichtigen Änderungen**++### 🚀 Neuerungen und Verbesserungen der Bedienung {#v0.3.8-new-stuff-and-quality-of-life-changes}+- Bei allen Browser-Fetchern führen Websites, deren Anfragen nie fertig laden, mit `network_idle` nicht mehr zum Absturz des Codes.+- Die Logik zum Sammeln und Prüfen von Seiteninhalten in Browser-Fetchern wurde geändert, damit Browser unter Windows so stabil wie unter Linux/MacOS laufen. Dieser Verhaltensunterschied liegt an der anderen Implementierung von Playwright unter Windows.+- Die gesamte Validierungslogik wurde überarbeitet, wodurch Anfragen aller Browser-Fetcher 8-15 % schneller sind+- Die neue Option `extra_flags` in `DynamicFetcher` und seiner Sitzung erlaubt zusätzliche eigene Chrome-Startoptionen neben den bestehenden Optionen.+- Beim Einsatz von `page_action` wird wieder die alte Routing-Logik zur Erfassung von Antworten verwendet, die in der letzten Version geändert worden war. So lässt sich der neueste Seiteninhalt erfassen, wenn `page_action` ihn ohne neue Anfrage verändert. (Danke an @gembleman für den Hinweis in [#100](https://github.com/D4Vinci/Scrapling/issues/100) und [#102](https://github.com/D4Vinci/Scrapling/pull/102) )++### 🐛 Fehlerbehebungen {#v0.3.8-bug-fixes}+- Ein Tippfehler in `load_dom` in der Methode async_fetch von DynamicSession wurde korrigiert+- Ein Problem beim Lösen von Cloudflare-Challenges wurde behoben: Bei eingebetteten Captchas, die nach dem Lösen sichtbar bleiben, wurde endlos auf ihr Verschwinden gewartet. Nach 30 Sekunden wird nun angenommen, dass es sich um diesen Captcha-Typ handelt (Behebt #100 )++### 🔨 Sonstige Änderungen {#v0.3.8-misc}+- Das Docker-Image wird jetzt zur einfacheren Nutzung automatisch auf Dockerhub und in der Container-Registry von GitHub veröffentlicht.+- Eine [neue Dokumentationsseite](https://github.com/D4Vinci/Scrapling/blob/v0.3.8/docs/tutorials/external.md) zeigt, wie Sie den Scrapeless-Browser mit Scrapling verwenden.++## [v0.3.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.7) - 2025-10-12 {#v0.3.7}++**Ein neues Update mit vielen wichtigen Änderungen**++### 🚀 Neuerungen und Verbesserungen der Bedienung {#v0.3.7-new-stuff-and-quality-of-life-changes}+- Das Argument `solve_cloudflare` in `StealthyFetcher` wurde überarbeitet, um alle Arten eigener Turnstile-Implementierungen lösen zu können.+- Der gesamte Code wurde überarbeitet, um die Prüfungen von Pyright zu bestehen. Das verbessert die Arbeit in allen IDEs und behebt viele Fehler.+- Die Anfragelogik wurde übersichtlicher und schneller gestaltet (Behebt auch #97 )+- Die neue Option `user_data_dir` in allen Browser-Sitzungsklassen ermöglicht es, Browserdaten aus früheren Sitzungen wiederzuverwenden, etwa Cookies und gespeicherte Daten. Ohne diese Option verwendet Playwright bei jedem Start wie bisher ein zufälliges Verzeichnis.+- Die neue Anpassungsoption `additional_args` in `Dynamic fetcher` und seiner Sitzungsklasse erlaubt zusätzliche Argumente für den Playwright-Kontext. Das war zuvor bereits mit `StealthyFetcher` möglich.+- Die Routing-Logik zur Erfassung der letzten Navigationsantwort wurde für alle Browser verbessert. Rohe Antworten können jetzt an den Parser gehen, bevor der Browser sie verarbeitet, statt wie bisher zuerst im Browser verarbeitet zu werden. Das ist besonders für Text- und JSON-Antworten hilfreich.++### 🐛 Fehlerbehebungen {#v0.3.7-bug-fixes}+- Die überarbeitete Routing-Logik behebt ein Problem beim Abrufen instabiler Websites auf einigen Windows-Geräten.+- Die Überarbeitungen dieser Version beheben viele zuvor schwer erkennbare Fehler sowie ungewöhnliche Probleme mit der Autovervollständigung in einigen IDEs.+- Viele Korrekturen an der Dokumentationswebsite++## [v0.3.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.6) - 2025-10-01 {#v0.3.6}++### 🚀 Neuerungen {#v0.3.6-new-stuff}+- Das Argument `solve_cloudflare` in `StealthyFetcher` und seinen Sitzungsklassen wurde verbessert, um alle Arten von Turnstile- und Cloudflare-Zwischenseiten-Challenges zu lösen 🎉+- Der MCP-Server kann jetzt `Streamable HTTP` verwenden, damit Sie ihn einfach über das Netzwerk bereitstellen können.+- Docker-Unterstützung wurde hinzugefügt. Bei jeder Veröffentlichung wird automatisch ein Image mit allen Browsern erstellt und auf Docker Hub veröffentlicht++### 🐛 Fehlerbehebungen {#v0.3.6-bug-fixes}+- Ein Kodierungsproblem im Parser wurde behoben, das in einigen Fällen auftrat: der bekannte Fehler `invalid start byte`+- Mehrere Teile der Bibliothek wurden umstrukturiert, um Speicherlecks zu beheben. Je nach Konfiguration wird jetzt deutlich weniger Speicher benötigt (Behebt auch #92 )+- Typannotationen wurden in vielen Teilen des Codes verbessert, um die Arbeit in der IDE zu erleichtern (Behebt auch #93 )++## [v0.3.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.5) - 2025-09-20 {#v0.3.5}++**Eine notwendige Version, die mehrere Probleme behebt**++### 🚀 Neuerungen {#v0.3.5-new-stuff}+- Alle Browser-Fetcher (`DynamicFetcher`/`StealthyFetcher`/...) und ihre Sitzungsklassen rufen Websites jetzt 15-20 % schneller ab:+ 1. Die Seitenverwaltung ist dank der verbesserten Logik von @AbdullahY36 in #87 deutlich schneller+ 2. Die allgemeine Validierungslogik und die Erstellung von Seiten für synchrone Abrufe wurden optimiert. Zusammen bringen diese Änderungen große Geschwindigkeitsgewinne++- Große Verbesserungen am Tarnmodus von `DynamicFetcher` und seinen Sitzungsklassen durch den Ersatz von `rebrowser-playwright` durch `PatchRight`:+ 1. Vor diesem Update wurde `rebrowser-playwright` deaktiviert, wenn Sie `stealth` und `real_chrome` aktivierten, weil beide nicht gut zusammenarbeiteten. Mit `PatchRight` besteht dieses Problem nicht mehr+ 2. Sie können jetzt mit geschlossenen Shadow Roots interagieren, da `PatchRight` automatisch mit ihnen umgehen kann.++### 🐛 Fehlerbehebungen {#v0.3.5-bug-fixes}+- Ein Fehler bei der Verwendung der Methode `re` aus der Klasse `Selectors` wurde behoben.+- Ein Fehler in den Befehlen `uncurl` und `curl2fetcher` der Web-Scraping-Shell wurde behoben, durch den die curl-Option `--data-raw` falsch verarbeitet wurde.+- Ein Fehler im Befehl `view` der Web-Scraping-Shell wurde behoben, dessen Auftreten von der Kodierung der Website abhing.+- Ein Fehler bei der Inhaltskonvertierung wurde behoben, der den Modus `mcp` und die Befehle `extract` betraf.++### Neue Mitwirkende {#v0.3.5-new-contributors}+- @AbdullahY36 hat mit #87 erstmals beigetragen++## [v0.3.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.4) - 2025-09-16 {#v0.3.4}++**Eine notwendige Version, die mehrere Probleme behebt**++### 🚀 Neuerungen {#v0.3.4-new-stuff}+- Alle Sitzungsklassen der Fetcher wurden zur interaktiven Shell hinzugefügt und sind dort ohne Import sofort verfügbar.++### 🐛 Fehlerbehebungen {#v0.3.4-bug-fixes}+- Eine Umgehung für einen Fehler in der Playwright-API unter Windows wurde hinzugefügt, der beim Abrufen von Inhalten während der Lösung von Cloudflare-Challenges auftrat.+- Ein Kodierungsproblem im Befehl `view` der interaktiven Shell wurde behoben+- Ein Fehler im Argument `max_pages` von `AsyncStealthySession` wurde behoben, der den Code abstürzen ließ.+- Ein Problem der letzten Updates wurde behoben, bei dem die Eigenschaften `html_content` und `prettify` von `Selector` abhängig von der Kodierung Bytes zurückgaben. Beide geben wieder Strings zurück.++## [v0.3.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.3) - 2025-09-15 {#v0.3.3}++- Die Logik zum Schließen des Standardtabs in Browser-Fetchern wurde entfernt, da sie einen Absturz auslöste. Das trat nicht auf dem Mac auf und konnte nur unter Windows und Linux reproduziert werden++## [v0.3.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.2) - 2025-09-15 {#v0.3.2}++Versionshinweise für v0.3.2++### 🚀 Neuerungen {#v0.3.2-new-stuff}++- **Optionale Fetcher-Abhängigkeiten**: Alle Fetcher gehören jetzt zu optionalen Abhängigkeitsgruppen. Das verkleinert das Basispaket. Das Basismodul `scrapling` enthält nur noch den Parser. Für Fetcher oder Kommandozeilenoptionen führen Sie `pip install "scrapling[fetchers]"` aus. Die ausführliche Installationsanleitung finden Sie [hier](index.md#installation)+- **Konfiguration je Seite in Sitzungen**: Die Sitzungsklassen der Browser-Fetcher erlauben jetzt getrennte Einstellungen für jede Seite. Alle Parameter für einzelne Abrufe werden wie Sitzungsparameter validiert. Weitere Details stehen [hier](fetching/stealthy.md#full-list-of-arguments) auf der Dokumentationswebsite+ <br>Beispiel:++ ```python+ with StealthySession(headless=True, solve_cloudflare=True) as session:+ page = session.fetch('https://nopecha.com/demo/cloudflare', google_search=False)+ ```++- **Verbesserte Browser-Fetcher**+ - Eine neue Option steuert, ob auf das Ende der JavaScript-Ausführung auf einer Seite gewartet wird. Sie ist wie bisher standardmäßig aktiviert++ ```python+ with DynamicSession(headless=True, disable_resources=False, network_idle=True) as session:+ page = session.fetch('https://quotes.toscrape.com/', load_dom=False)+ ```++ - Der Tarnmodus in `DynamicFetcher` und seinen Sitzungsklassen ist jetzt zuverlässiger.+ - `DynamicFetcher` und `StealthyFetcher` benötigen weniger Ressourcen, indem sie den von persistenten Playwright-Kontexten geöffneten Standardtab automatisch finden und schließen+ - Ein wichtiger Logikfehler bei der Seitenrotation der Browser-Fetcher wurde behoben. Vorherige Seiten werden jetzt durch neue ersetzt, weil wiederverwendete Tabs noch durch frühere Einstellungen beeinflusst sein konnten+ - `StealthyFetcher` und seine Sitzungsklassen sind jetzt etwas schneller (5 %)++- **Verbesserte Eigenschaft `.body`**: Sie gibt den übergebenen Inhalt jetzt unverändert und ohne Verarbeitung zurück. Das ermöglicht Dateidownloads und Anfragen ohne HTML-Antwort. Hier ist ein Beispiel für den Download eines Bildes:++ ```python+ from scrapling.fetchers import Fetcher++ page = Fetcher.get('https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/poster.png')+ with open(file='poster.png', mode='wb') as f:+ f.write(page.body)+ ```++### 🐛 Fehlerbehebungen {#v0.3.2-bug-fixes}++- **Kodierungsprobleme behoben**: Mehrere Kodierungsprobleme mit einigen Websites im Parser, im Modus mcp und in den extract-Befehlen wurden behoben (Behebt auch #80 und #81)+- **Schnelleres Parsen**: Viele Änderungen in verschiedenen Bereichen machen die Bibliothek schneller. Das zeigen auch die aktualisierten Benchmarks++### 🔨 Sonstige Änderungen {#v0.3.2-misc}++- **Aktualisierte Benchmarks**: Die Leistungsmessungen wurden aktualisiert, um die aktuellen Geschwindigkeitsgewinne mit den neuesten Versionen ähnlicher Bibliotheken zu vergleichen+- **Viel Code überarbeitet und ungenutzten Code durch bessere Implementierungen ersetzt**: Weniger und übersichtlicherer Code, einfachere Wartung+- **YouTube-Video hinzugefügt**: Die MCP-Dokumentation wurde um Videoinhalte ergänzt.+- **Neue Issue-Vorlage**: Eine einfache Vorlage für Benutzer, die die bestehenden Vorlagen nicht nutzen können.+- **CI-Workflow optimiert**: Der Test-Workflow überspringt jetzt Ausführungen, wenn nur die Dokumentation oder andere Dateien ohne Code geändert wurden.+- **Abhängigkeiten aktualisiert**: Verschiedene Abhängigkeiten wurden auf die neuesten Versionen aktualisiert.+- **Codestil verbessert**: Neue ruff-Regeln wurden auf alle Dateien angewendet.+- **Pre-commit-Hooks**: Die Pre-commit-Konfiguration wurde aktualisiert.++### 🎯 Inkompatible Änderungen {#v0.3.2-breaking-changes}++- Der Parameter `max_pages` wurde aus der synchronen Version von `StealthySession` entfernt, um das Verhalten an `DynamicSession` anzugleichen. In der synchronen Version ist er nicht sinnvoll++## [v0.3.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.1) - 2025-09-02 {#v0.3.1}++1. Ein Problem bei der Installation von scrapling ohne das Extra `shell` wurde behoben (#76 )+2. Alle Browser-Fetcher und ihre Sitzungsklassen haben ein neues Argument für eine JS-Datei, die beim Erstellen der Seite ausgeführt wird (#56) :++```python+from scrapling.fetchers import StealthyFetcher++StealthyFetcher.fetch('https://example.com', init_script="/absolute/path/to/js/script.js")+```++## [v0.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3) - 2025-09-01 {#v0.3}++🎉 **Große Version - Vollständige Überarbeitung der Architektur**++Scrapling v0.3 ist das bisher größte Update des Projekts. Die Architektur wurde komplett neu geschrieben, die Leistung deutlich verbessert und viele neue Funktionen ergänzt, darunter die KI-Integration und eine interaktive Shell für Web-Scraping.++Diese Version enthält mehrere inkompatible Änderungen. Bitte lesen Sie die Versionshinweise sorgfältig.++### 🚀 Wichtige neue Funktionen {#v0.3-major-new-features}++#### Architektur auf Basis von Sitzungen {#v0.3-session-based-architecture}+- **Neue Sitzungsklassen**: Vollständig neu geschrieben, mit Unterstützung für dauerhafte Sitzungen+ - `FetcherSession` - HTTP-Anfragen mit dauerhaftem Zustand, sowohl für synchronen als auch für asynchronen Code+ - `DynamicSession`/`AsyncDynamicSession` - Browser-Automatisierung, bei der der Browser offen bleibt, bis Sie fertig sind+ - `StealthySession`/`AsyncStealthySession` - Browser-Nutzung im Stealth-Modus, bei der der Browser offen bleibt, bis Sie fertig sind+- **Asynchrone Verwaltung von Browser-Tabs**: Das neue Argument `max_pages` stellt einen Pool von Tabs bereit, die für gleichzeitige Browser-Abrufe abwechselnd genutzt werden+- **Gleichzeitige Sitzungen**: Führen Sie mehrere voneinander getrennte Sitzungen gleichzeitig aus++Weitere Informationen finden Sie im Abschnitt `Fetching` auf der Website.++#### Viele neue Funktionen zur Tarnung und gegen Bot-Erkennung {#v0.3-a-lot-of-new-stealth-anti-bot-capabilities}+- **🤖 Cloudflare-Prüfungen lösen**: Automatisches [Lösen von Cloudflare-Turnstile-Prüfungen](fetching/stealthy.md#cloudflare-and-stealth-options) in `StealthyFetcher` und seinen Sitzungsklassen+- **Browser-Fingerprints nachbilden**: Die vollständig neue Klasse [Fetcher](fetching/static.md) bildet TLS-Fingerprints echter Browser nach, erzeugt zur Browserversion passende Header und unterstützt HTTP/3 und mehr+- **Verbesserter Stealth-Modus**: Der Stealth-Modus von `DynamicFetcher` und seinen Sitzungsklassen ist jetzt robuster und zuverlässiger (auch als `PlayWrightFetcher` bekannt)++#### KI-Integration und MCP-Server {#v0.3-ai-integration-mcp-server}+- **Integrierter MCP-Server**: Ein Server für das Model Context Protocol für KI-gestütztes Web-Scraping+- **6 leistungsfähige Werkzeuge**: `get`, `bulk_get`, `fetch`, `bulk_fetch`, `stealthy_fetch`, `bulk_stealthy_fetch`+- **Intelligente Inhaltsextraktion**: Wandeln Sie Webseiten oder Elemente in Markdown oder HTML um, oder extrahieren Sie eine bereinigte Fassung des Textinhalts+- **Unterstützung für CSS-Selektoren**: Wählen Sie mit der Scrapling-Engine gezielt einzelne Elemente aus, bevor Sie den Inhalt an die KI übergeben+- **Bot-Schutz umgehen**: Bewältigen Sie Cloudflare Turnstile und andere Schutzmaßnahmen+- **Proxy-Unterstützung**: Nutzen Sie Proxys für Anonymität und Anfragen aus bestimmten Regionen+- **Browser nachbilden**: Bilden Sie echte Browser mit TLS-Fingerprints, echten Headern passend zur Browserversion und mehr nach+- **Parallele Verarbeitung**: Lesen Sie mehrere URLs gleichzeitig aus, um effizienter zu arbeiten+- [und mehr...](ai/mcp-server.md)++#### Neue interaktive Shell für Web-Scraping {#v0.3-new-interactive-web-scraping-shell}+- **Eine neue Shell**: Eine angepasste IPython-Shell mit vielen praktischen integrierten Kurzbefehlen wie `get`, `post`, `put`, `delete`, `fetch` und `stealthy_fetch`+- **Intelligente Seitenverwaltung**: Die neuen Befehle `page` und `pages` speichern automatisch die aktuelle Seite und den Verlauf aller Anfragen aus der Shell+- **Curl-Integration**: Wandeln Sie curl-Befehle aus den DevTools des Browsers mit den Funktionen `uncurl` und `curl2fetcher` in `Fetcher`-Anfragen um+- [und mehr...](cli/interactive-shell.md)++#### Websites im Terminal auslesen, ohne zu programmieren {#v0.3-scrape-from-the-terminal-without-programming}+- **Neue Extract-Befehle**: Web-Scraping im Terminal ohne Programmierung+ - `scrapling extract get/post/put/delete` - Einfache HTTP-Anfragen+ - `scrapling extract fetch` - Dynamische Inhalte auslesen+ - `scrapling extract stealthy-fetch` - Bot-Schutz umgehen+- **Lädt Webseiten herunter** und speichert ihren Inhalt in Dateien.+- **Wandelt HTML in lesbare Formate um**, etwa Markdown, behält es als HTML bei oder extrahiert nur den Textinhalt der Seite.+- **Unterstützt eigene CSS-Selektoren**, um bestimmte Teile der Seite zu extrahieren.+- **Verarbeitet HTTP-Anfragen und Seitenabrufe über Browser.**+- **Umfassend anpassbar** mit eigenen Headern, Cookies, Proxys und weiteren Optionen. Fast alle Optionen, die im Code verfügbar sind, können Sie auch im Terminal nutzen.+- [und mehr...](cli/extract-commands.md)++### 🔧 Technische Verbesserungen {#v0.3-technical-improvements}++#### Leistungsverbesserungen {#v0.3-performance-enhancements}+- **Fetcher ist jetzt 4-mal schneller** - Ja, Sie haben richtig gelesen!+- **DynamicFetcher ist jetzt etwa 60 % schneller** - Je nach Konfiguration deutlich schneller, besonders im Stealth-Modus+- **StealthyFetcher ist jetzt 20–30 % schneller** - Dank der neuen Struktur und unserer eigenen Implementierung, die wir nun statt der Python-Schnittstelle von `Camoufox` einsetzen+- **Zusammen 50 % oder mehr Geschwindigkeitsgewinn** bei den wichtigsten Auswahlmethoden (`find_by_text`, `find_similar`, `find_by_regex`, `relocate` usw.) 🚀+- **Etwa 10 % mehr Geschwindigkeit bei CSS/XPath-Methoden für den ersten Treffer** - `css_first` und `xpath_first` sind jetzt schneller als `css` und `xpath`+- **Die Methode `get_all_text()` ist 40 % schneller** bei der Inhaltsextraktion+- **20 % mehr Geschwindigkeit** beim adaptiven Wiederfinden von Elementen+- **Navigationseigenschaften optimiert** - Eigenschaften wie `next`, `previous`, `below_elements` und weitere sind jetzt spürbar schneller+- **5-mal schnellere Textbereinigung**+- **Geringerer Speicherbedarf** durch optimierte Imports und weniger Verwaltungsaufwand+- **⚡ Blitzschnelle Imports**: Kürzere Startzeit durch optimiertes Laden von Modulen+- **Bessere Benchmarks**: Durch all diese Verbesserungen ist Scrapling im Vergleich zu anderen Bibliotheken noch viel schneller als zuvor (1775-mal schneller als BeautifulSoup und 5,1-mal schneller als AutoScraper, siehe [Benchmarks](benchmarks.md))++#### Architektur, Codequalität und Bedienung {#v0.3-architecture-code-quality-and-quality-of-life}+- **Dauerhafter Kontext**: Alle Browser-Fetcher verwenden jetzt standardmäßig einen dauerhaften Kontext. (Löst auch #64)+- **Schnelle Prüfung aller Browser-Fetcher mit msgspec**, bevor Anfragen ausgeführt werden. So lassen sich Fehler leichter finden.+- **Alle Cookies**, die Fetcher zurückgeben, entsprechen jetzt dem Format, das derselbe Fetcher akzeptiert. Sie können Cookies also abrufen und erneut an alle Fetcher und ihre Sitzungsklassen übergeben.+- **Schnellere Codeprüfung und Formatierung** durch den Wechsel zu `ruff`+- **Modernes Build-System**: Wechsel von setup.py zu pyproject.toml 📦+- **Bessere GitHub Actions und Workflows** für einfachere Entwicklung und Tests+- **🎨 Verbesserte Typangaben**: Vollständige Typangaben nach modernen Python-Standards für bessere IDE-Unterstützung und mehr Zuverlässigkeit+- **Aufgeräumter Code**: Nicht mehr genutzten Code entfernt und Kernfunktionen optimiert 🧹+- **🚀 Abwärtskompatibilität**: Kurzformen ergänzt, damit älterer Code weiter funktioniert++### Inkompatible Änderungen {#v0.3-breaking-changes}++#### Erforderliche Python-Version {#v0.3-minimum-python-version}+- **Python 3.10+ erforderlich**: Python 3.9 und ältere Versionen werden nicht mehr unterstützt++#### Namen von Klassen und Methoden {#v0.3-class-and-method-naming}+Diese Umbenennungen sollen die Namen klarer und einheitlicher machen, besonders für neue Nutzer.++- **`Adaptor` → `Selector`**: Die zentrale Parser-Klasse wurde umbenannt (kann zur Abwärtskompatibilität weiterhin als `Adaptor` importiert werden)+- **`Adaptors` → `Selectors`**: Die Sammlungsklasse wurde umbenannt (kann zur Abwärtskompatibilität weiterhin als `Adaptors` importiert werden)+- **`auto_match` → `adaptive`**: Parameter in allen Methoden umbenannt+- **`adaptor_arguments` → `selector_config`**: Konfigurationsparameter umbenannt+- **`automatch_domain` → `adaptive_domain`**: Domain-Parameter umbenannt+- **`additional_arguments` → `additional_args`**: Parametername verkürzt+- **⚠️ `text/body` → `content`**: Der Parameter des Selector-Konstruktors akzeptiert jetzt sowohl `str` als auch `bytes`+- **`PlayWrightFetcher` → `DynamicFetcher`**: Die Klasse für Browser-Automatisierung wurde umbenannt (kann zur Abwärtskompatibilität weiterhin als `PlayWrightFetcher` importiert werden)+- **DynamicFetcher enthält die NSTBrowser-Logik und ihre Argumente nicht mehr**, da es keinen Sinn mehr hat, sie beizubehalten.+- **Das Argument headless von StealthyFetcher akzeptiert 'virtual' nicht mehr**, da wir die Camoufox-Bibliothek nur noch verwenden, um den Installationspfad des Browsers und die übrigen Startoptionen zu ermitteln++### 🐛 Fehlerbehebungen {#v0.3-bug-fixes}++- Das Zählen verschachtelter Kindelemente in ignorierten Tags für `get_all_text` korrigiert (#61)+- Installationsprobleme durch Leerzeichen im Pfad zur ausführbaren Python-Datei behoben (#57)+- Threading-Probleme im Speichersystem bei der Verarbeitung von Rekursionen mit aktivierter adaptiver Funktion behoben+- Probleme mit der Rangfolge von Argumenten in `FetcherSession` durch das Sentinel-Muster behoben+- Die Verarbeitung von Proxy-Typen in `StealthyFetcher` korrigiert+- Konflikte zwischen den Argumenten `referer` und `google_search` behoben+- Probleme beim asynchronen Einfügen von Skripten zur Tarnung behoben++## [v0.2.99](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.99) - 2025-04-08 {#v0.2.99}++**Dieses Update ist für alle wichtig, die Scrapling in vollem Umfang nutzen möchten.**++### Was sich geändert hat {#v0.2.99-what-s-changed}+#### Neue Website mit vollständiger Dokumentation {#v0.2.99-new-full-documentation-website}+- Ja, endlich 😄 Schauen Sie [hier](index.md) vorbei+#### Einheitliche Import-Logik für Fetcher {#v0.2.99-unified-import-logic-for-fetchers}+- Sie können jetzt alle Fetcher mit `from scrapling.fetchers import Fetcher, AsyncFetcher, StealthyFetcher, PlayWrightFetcher` importieren und ohne Initialisierung direkt verwenden, etwa mit `page = Fetcher.get(...)`.<br/> Dies ersetzt den alten Import `from scrapling.defaults import Fetcher, AsyncFetcher, StealthyFetcher, PlayWrightFetcher`.+#### Inkompatible Änderung: automatch ist jetzt standardmäßig deaktiviert {#v0.2.99-breaking-change-automatch-is-now-turned-off-by-default}+- Es gibt jetzt eine neue Vorgehensweise, um automatch oder andere Parser-Optionen über Fetcher zu aktivieren. Einzelheiten finden Sie auf der [Dokumentationsseite](fetching/choosing.md#parser-configuration-in-all-fetchers).+> Die alten Imports und die alte Logik bleiben zur Abwärtskompatibilität nutzbar, geben aber eine Warnung aus.+#### Neue Optionen für Fetcher {#v0.2.99-new-options-added-to-fetchers}+- Sowohl `StealthyFetcher` als auch `PlayWrightFetcher` haben jetzt beim Abrufen das neue Argument `wait`. Damit wartet der Fetcher eine bestimmte Zeit in Millisekunden, bevor er die Seite schließt und die Antwort zurückgibt.+- Die Methoden von `StealthyFetcher`, `fetch` und `async_fetch`, haben jetzt das Argument `additional_arguments`. Damit können Sie zusätzliche Einstellungen an Camoufox übergeben, die Vorrang vor den Scrapling-Einstellungen haben (#54 )+#### Fehlerbehebungen {#v0.2.99-bugs-squashed}+- Einen Fehler beim Erfassen von Weiterleitungen in `async_fetch` in den Klassen `StealthyFetcher` und `PlayWrightFetcher` behoben.++**_Vielen Dank für Ihre Unterstützung und Spenden!_**++## [v0.2.98](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.98) - 2025-03-17 {#v0.2.98}++**Dieses Update ist für alle wichtig, die Scrapling in vollem Umfang nutzen möchten**++### Was sich geändert hat {#v0.2.98-what-s-changed}+#### Verschiedene Verbesserungen bei Speicherbedarf und Geschwindigkeit {#v0.2.98-various-memory-usage-and-speed-optimizations}+- Alle Auswahlmethoden benötigen nur noch etwa 40 % des bisherigen Speichers und sind etwas schneller.+- Alle Untermodule der Bibliothek werden jetzt erst bei Bedarf geladen. Sie laden also nur, was Sie verwenden. Zum Beispiel:+Vor dem Update benötigte der Import `from scrapling import Adaptor` `30-40mb` RAM, weil dabei auch alle Fetcher und weitere Teile geladen wurden. Jetzt sind es nur noch `~1.2mb`.+- Durch das letzte Update benötigte die Bibliothek bei einem großen Anfrage-Pool nur noch etwa 32 % des bisherigen Speichers. Jetzt haben wir den Cache weiter angepasst, um noch weniger zu verbrauchen.+- Der Parser ist insgesamt um 2-5 % schneller++**_Vielen Dank für Ihre Unterstützung und Spenden!_**++## [v0.2.97](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.97) - 2025-03-15 {#v0.2.97}++**Dieses Update ist für alle wichtig, die Scrapling in vollem Umfang nutzen möchten**++### Was sich geändert hat {#v0.2.97-what-s-changed}+#### Weniger Speicherbedarf und etwas mehr Geschwindigkeit bei allen Fetchern. {#v0.2.97-lower-memory-usage-and-small-speed-increase-across-all-fetchers}+- Neue Grenzen für die Cache-Größe in der gesamten Bibliothek senken den Speicherbedarf deutlich, wenn Sie viele Anfragen oder Operationen ausführen.+- Große Teile der Fetcher wurden überarbeitet, um die Wartung zu erleichtern und die Geschwindigkeit etwas zu erhöhen.++#### Fehlerbehebungen {#v0.2.97-bugs-fixed}+- Einen Fehler in `TextHandler` behoben: Wenn die Klasse allein importiert wurde, wandelte sie Werte, die keine Zeichenketten waren, in eine leere Zeichenkette um. Jetzt wird jeder Wert für `TextHandler` zuerst in eine Zeichenkette und dann in `TextHandler` umgewandelt. Das gilt für jeden übergebenen Wert. Schließlich soll `TextHandler`, wie der Name sagt, nur mit Zeichenketten arbeiten! (#45 )+- Einen Fehler behoben, bei dem die `retries`-Argumente in den meisten Methoden von AsyncFetcher nicht berücksichtigt wurden.++#### Sonstiges {#v0.2.97-miscellaneous}+- Die Typangaben für die meisten Argumente aller Fetcher wurden klarer und genauer gemacht.++**_Vielen Dank für Ihre Unterstützung und Spenden!_**++## [v0.2.96](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.96) - 2025-03-05 {#v0.2.96}++**Dieses Update ist für alle wichtig, die Scrapling in vollem Umfang nutzen möchten**++### Was sich geändert hat {#v0.2.96-what-s-changed}+1. Die Option `-f` für `scrapling install` ergänzt, um die Neuinstallation der Browser-Abhängigkeiten zu erzwingen. Ich empfehle, jetzt `scrapling install -f` auszuführen, damit Sie den großen Geschwindigkeitsgewinn von `StealthyFetcher` mit der neuen Camoufox-Browserversion nutzen können :)+2. Einen Fehler in `TextHandler` behoben, bei dem Slicing ein `TextHandlers`-Objekt statt eines `TextHandler`-Objekts zurückgab. Auch die Typangabe wurde korrigiert (#41 )+3. Ein Problem behoben, bei dem `scrapling install` in manchen Fällen eine Python-Shell öffnete!++## [v0.2.95](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.95) - 2025-02-25 {#v0.2.95}++**Dieses Update ist für alle wichtig, die Scrapling in vollem Umfang nutzen möchten**++### Was sich geändert hat {#v0.2.95-what-s-changed}+1. Einen Fehler in `Fetcher` behoben, bei dem die mit dem Argument `stealthy_headers` erzeugten Header einige vom Nutzer gesetzte Header wie `Accept` überschrieben (#39 )+2. Die Erzeugung der Header etwas verbessert. Das sollte die Geschwindigkeit leicht erhöhen.++## [v0.2.94](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.94) - 2025-02-22 {#v0.2.94}++**Dieses Update ist für alle wichtig, die Scrapling in vollem Umfang nutzen möchten**++### Was sich geändert hat {#v0.2.94-what-s-changed}+1. Die Eigenschaft `history` für alle Fetcher ergänzt, um Weiterleitungen anzuzeigen (#32 )+2. Die Logik des Arguments `case_sensitive` für alle `re`/`re_first`-Methoden korrigiert. Wenn Sie dieses Argument genutzt haben, kann Ihr Code jetzt andere Ergebnisse liefern (aber vielleicht haben Sie das verdient, wenn Sie den Fehler bemerkt und kein Issue eröffnet haben, LOL).+3. Abhängigkeiten aktualisiert und `coop` in der Camoufox-Engine (StealthyFetcher) wieder aktiviert.++## [v0.2.93](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.93) - 2025-01-31 {#v0.2.93}++**Dieses Update ist für alle wichtig, die Scrapling in vollem Umfang nutzen möchten**++### Was sich geändert hat {#v0.2.93-what-s-changed}+1. Der Rückgabetyp ist jetzt im gesamten Parser einheitlich. Sie erhalten immer einen dieser Typen: `Adaptor`, `Adaptors`, `TextHandler`, `TextHandlers`, `None` oder eine Liste bei gemischten Ergebnissen, etwa durch einen kombinierten CSS-Selektor. Das erleichtert das Programmieren mit weniger manuellen Typprüfungen, macht die Bibliothek stabiler und ermöglicht immer das Verketten von Methoden.+2. Große Teile des Parsers, besonders die Klasse `Adaptor`, wurden überarbeitet und sind jetzt übersichtlicher und vor allem schneller. Fast alle Methoden und Eigenschaften, besonders die Suchmethoden, sind jetzt 5-40 % schneller. Manche haben noch mehr zugelegt: `find_by_regex` ist etwa 60 % schneller! Die automatch-Funktion ist etwa 5 % schneller.+3. Logikfehler in den Methoden `find_all`/`find` behoben, durch die übergebene Filter manchmal mit ODER und manchmal mit UND verknüpft wurden. Jetzt müssen alle zurückgegebenen Elemente alle übergebenen Filter erfüllen.+4. Alle Methoden für reguläre Ausdrücke geben jetzt `TextHandler`/`TextHandlers` zurück, damit sich Methoden leichter verketten lassen.+5. **Die neue Eigenschaft** `below_elements` ergänzt. Sie gibt ein `Adaptors`-Objekt mit allen Elementen unterhalb des aktuellen Elements im DOM-Baum zurück.+6. Alle Methoden und Eigenschaften, die HTML-Quelltext als Zeichenkette zurückgaben, geben ihn jetzt als `TextHandler` zurück. So können Sie darauf leichter reguläre Ausdrücke und weitere Funktionen anwenden.+7. StealthyFetcher ist jetzt etwas schneller und besser getarnt. Außerdem können Sie jetzt auf Captchas in iframes klicken, etwa auf **Cloudflare Turnstile**.+8. Die automatische Vervollständigung und die Typangaben wurden in fast der Hälfte der Bibliothek deutlich verbessert, besonders bei `Adaptor`, `TextHandler` und `TextHandlers`.+9. Ein `TextHandler` gibt beim Slicing, bei Indexzugriffen oder bei Verwendung der Methode `split` jetzt ein weiteres `TextHandler`-Objekt statt einer normalen Python-Zeichenkette zurück. Fast alle üblichen Zeichenkettenoperationen und Methoden geben jetzt weitere `Texthandler`-Objekte statt normaler Zeichenketten zurück, damit sich Methoden und Funktionen immer verketten lassen.+10. Einige kleine Fehler und Tippfehler behoben. Zum Beispiel führte Fetcher async_put eine POST-Anfrage statt einer PUT-Anfrage aus 😶🌫️+11. Die README etwas verbessert, bis ich die Dokumentationswebsite fertig habe.++Dies sollte nur ein kleines Update vor Version 0.3 werden, aber ich wollte es noch etwas besser machen.++## [v0.2.92](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.92) - 2024-12-26 {#v0.2.92}++### Was sich geändert hat {#v0.2.92-what-s-changed}+- Antworten von Browser-Fetchern nutzen jetzt zuverlässigere Datenquellen, wenn die geladene Seite viele iframes enthält.+- **Die Installation von `Scrapling` ist jetzt noch einfacher: Installieren Sie es mit pip, führen Sie dann `scrapling install` im Terminal aus, und Sie können loslegen!**+- Eine ungenaue Typangabe im Parser korrigiert.++## [v0.2.91](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.91) - 2024-12-19 {#v0.2.91}++### Was sich geändert hat {#v0.2.91-what-s-changed}+- Einen Fehler behoben, bei dem die Protokollmeldung zum Seitenabruf nur bei der ersten Anfrage erschien.+- Beim Aufrufen einer Seite gibt die Playwright-API standardmäßig die erste Antwort zurück, die den an `goto` übergebenen Ladezustand `["load", "domcontentloaded", "networkidle"]` erfüllt. Wenn eine Website zuerst eine Warteseite wie die von Cloudflare zeigt und danach zur eigentlichen Website weiterleitet, gibt Playwright den ersten Statuscode zurück, etwa 403. Dieses Update löst das Problem für `PlaywrightFetcher` und `StealthyFetcher`, die beide die Playwright-API nutzen. Das Ergebnis hängt also nicht mehr vom Standardverhalten von Playwright ab.+- Unterstützung für SOCKS-Proxys in der Klasse `Fetcher` ergänzt.+- Die Typangabe des Arguments `wait_selector_state` korrigiert, damit die automatische Vervollständigung die richtigen möglichen Werte anzeigt.++## [v0.2.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.9) - 2024-12-16 {#v0.2.9}++### Was sich geändert hat {#v0.2.9-what-s-changed}+##### Neue Funktionen {#v0.2.9-new-features}+1. Die **lang erwartete** Unterstützung für asynchronen Code ist da! Es gibt jetzt die Klasse `AsyncFetcher` als asynchrone Variante von `Fetcher`. Außerdem haben `StealthyFetcher` und `PlayWrightFetcher` die neue Methode `async_fetch` mit denselben Optionen.++```python+>> from scrapling import StealthyFetcher+>> page = await StealthyFetcher().async_fetch('https://www.browserscan.net/bot-detection') # the async version of fetch+>> page.status == 200+True+```++2. Die Klasse `StealthyFetcher` hat jetzt das Argument `geoip` in ihren Abrufmethoden. Wenn es aktiviert ist, verwendet die Klasse automatisch Längengrad, Breitengrad, Zeitzone, Land und regionale Einstellungen der IP-Adresse und passt dann die WebRTC-IP-Adresse entsprechend an. Sie bestimmt außerdem die Browsersprache anhand der Verteilung der Sprachen in der Zielregion und stellt sie entsprechend ein.+3. Das Argument `retries` zu den Klassen `Fetcher`/`AsyncFetcher` hinzugefügt. Damit können Sie festlegen, wie oft jede über `httpx` ausgeführte Anfrage erneut versucht wird.+4. Die Methode `url_join` zu `Adaptor` und den Fetchern hinzugefügt. Sie verbindet eine relative URL mit der aktuellen URL zu einer vollständigen absoluten URL!+5. Die Methode `keep_cdata` zu `Adaptor` und den Fetchern hinzugefügt, damit Sie bei Bedarf verhindern können, dass der Parser CDATA entfernt.+6. In `Adaptor`/`Response` gibt die Methode `body` jetzt nach Möglichkeit die rohe HTML-Antwort zurück, ohne sie in der Bibliothek zu verarbeiten.+7. Protokollierung zur Klasse `Response` hinzugefügt. Wenn Sie Fetcher verwenden, erhalten Sie jetzt eine Protokollmeldung mit Informationen zur Antwort.+Beispiel:++ ```python+ >> from scrapling.defaults import Fetcher+ >> Fetcher.get('https://books.toscrape.com/index.html')+ [2024-12-16 13:33:36] INFO: Fetched (200) <GET https://books.toscrape.com/index.html> (referer: https://www.google.com/search?q=toscrape)+ >>+ ```++8. Wenn Sie übliche Zeichenkettenmethoden auf einem `TextHandler` verwenden, etwa `.replace()`, erhalten Sie jetzt ein weiteres `TextHandler`-Objekt. Zuvor wurde eine normale Zeichenkette zurückgegeben.+9. Deutliche Geschwindigkeitsverbesserungen in der gesamten Bibliothek und insgesamt bessere Tarnung in den Fetcher-Klassen.+10. Einfache Funktionen wie `extract_first`\`extract` ergänzt, die dasselbe Ergebnis wie das übergeordnete Objekt zurückgeben. Sie sind nur dazu da, Code bei Bedarf leichter von Scrapy/Parsel nach Scrapling zu kopieren, da diese Funktionen dort verwendet werden!+11. Da große Teile des Codes überarbeitet wurden und Caching an den richtigen Stellen eingesetzt wird, sind viele Anfragen auf einmal jetzt deutlich schneller.++##### Inkompatible Änderungen {#v0.2.9-breaking-changes}+- Python 3.8 wird nicht mehr unterstützt. (Hauptsächlich, weil Playwright die Unterstützung beendet hat, aber diese Version war ohnehin problematisch.)+- Das Argument `debug` wurde aus der gesamten Bibliothek entfernt. Wenn Sie Debugging aktivieren möchten, führen Sie nach dem Import der Bibliothek Folgendes aus:++ ```python+ >>> import logging+ >>> logging.getLogger("scrapling").setLevel(logging.DEBUG)+ ```++##### Fehlerbehebungen {#v0.2.9-bugs-squashed}+1. WebGL ist jetzt standardmäßig aktiviert, da viele Schutzsysteme inzwischen prüfen, ob es aktiviert ist.+2. Einige Fehler und Tippfehler in der Dokumentation und README korrigiert.++##### Verbesserungen der Bedienung {#v0.2.9-quality-of-life-changes}+1. Die gesamte Protokollierung läuft jetzt unter dem Logger-Namen `scrapling`, damit sie sich einfacher und übersichtlicher steuern lässt. Zuvor wurde der Root-Logger verwendet.+2. Den Testordner übersichtlicher aufgebaut und Tests für die neuen Funktionen ergänzt. Alle Tests wurden übersichtlicher neu geschrieben und weitere Tests für eine höhere Abdeckung hinzugefügt.+3. Einen großen Teil des Codes überarbeitet, damit er übersichtlicher und leichter zu warten ist.++> All diese Änderungen waren ursprünglich für 0.3 geplant. Ich habe sie aber schon hier aufgenommen, weil es bis zur nächsten Version noch etwas dauern wird. Als Nächstes werde ich die ausführliche Dokumentationswebsite fertigstellen und dann an Version 0.3 arbeiten.++## [v0.2.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.8) - 2024-11-30 {#v0.2.8}++### Was sich geändert hat {#v0.2.8-what-s-changed}+- Dieses kleine Update enthält einige wichtige Verbesserungen für die Nutzung des Codes und korrigiert einen Tippfehler in der Haupt-README (#20).++## [v0.2.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.7) - 2024-11-26 {#v0.2.7}++### Was sich geändert hat {#v0.2.7-what-s-changed}+##### Neue Funktionen {#v0.2.7-new-features}+- Wenn Sie das Argument `wait_selector` mit den Klassen `StealthyFetcher` und `PlayWrightFetcher` verwenden, wartet Scrapling danach erneut wie üblich darauf, dass JavaScript vollständig geladen und ausgeführt wird. Wenn Sie das Argument `network_idle` verwenden, wartet Scrapling anschließend auch erneut auf diesen Zustand. Sind alle Zustände bereits erreicht, gibt es natürlich keine Wartezeit.+- In `StealthyFetcher` können Sie mit dem Argument `disable_ads` jetzt Werbung zulassen oder blockieren. Die Option ist standardmäßig aktiviert und installiert die Erweiterung `ublock origin`.+- Die regionalen Einstellungen von `PlayWrightFetcher` können Sie jetzt mit dem Argument `locale` festlegen. Der Standardwert bleibt `en-US`.+- Einfache Anfragen über `Fetcher` akzeptieren jetzt Proxys im Format `http://username:password@localhost:8030`.+- Der Stealth-Modus von `PlayWrightFetcher` wurde etwas verbessert.++##### Fehlerbehebungen und Verbesserungen {#v0.2.7-bugs-squashed-improvements}+1. Die Aktivierung von Proxys in der Klasse `PlayWrightFetcher` hängt jetzt nicht mehr davon ab, ob der Modus `stealth` aktiviert ist (danke an [@AbdullahY36](https://github.com/AbdullahY36) für den Hinweis).+2. `ResponseEncoding` prüft jetzt, ob die in der Antwort angegebene Kodierung für die Seite verwendet werden kann. Führt sie zu einem Fehler, verwendet Scrapling `utf-8`.++## [v0.2.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.6) - 2024-11-24 {#v0.2.6}++### Was sich geändert hat {#v0.2.6-what-s-changed}+##### Neue Funktionen {#v0.2.6-new-features}+- `PlayWrightFetcher` kann jetzt den echten Browser direkt verwenden. Übergeben Sie dazu das Argument `real_chrome` an `PlayWrightFetcher.fetch`. Dafür muss Chrome installiert sein. Scrapling startet eine Instanz Ihres Chrome-Browsers, und Sie können die meisten Optionen wie gewohnt verwenden. (Zuvor war dies nur mit dem Argument `cdp_url` möglich.)+- Die Versionsangabe der für echte Browser erzeugten Header erhöht.++##### Fehlerbehebungen {#v0.2.6-bugs-squashed}+1. Das Format der von `BrowserForge` erzeugten Browser-Header war veraltet. Dadurch erkannten einige Schutzsysteme Scrapling. Deshalb wird `BrowserForge` jetzt nur noch verwendet, um einen echten User-Agent zu erzeugen.+2. Das Argument `hide_canvas` ist jetzt standardmäßig deaktiviert, da Googles ReCaptcha es erkennt.++## [v0.2.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.5) - 2024-11-23 {#v0.2.5}++### Was sich geändert hat {#v0.2.5-what-s-changed}++##### Fehlerbehebungen {#v0.2.5-bugs-squashed}+- Einen Fehler beim Argument 'wait_selector' behoben, wenn es mehr als 1 Element fand. Dies betrifft die Klassen `StealthyFetcher` und `PlayWrightFetcher`.+- Den Kodierungstyp korrigiert, wenn der Header `content_type` einen Wert mit Parametern wie `charset` enthält (danke an @andyfcx für [#12](https://github.com/D4Vinci/Scrapling/issues/12) ).++##### Verbesserungen der Bedienung {#v0.2.5-quality-of-life}+- Weitere Tests für neue Teile des Codes ergänzt. Die Tests werden jetzt in Threads ausgeführt.+- Ich habe die Docstrings angepasst, damit Sphinx apidoc und ähnliche Werkzeuge sie korrekt darstellen können.++##### Neue Mitwirkende {#v0.2.5-new-contributors}+- @andyfcx hat in [#13 ](https://github.com/D4Vinci/Scrapling/pull/13) erstmals mitgewirkt++## [v0.2.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.4) - 2024-11-20 {#v0.2.4}++### Was sich geändert hat {#v0.2.4-what-s-changed}++##### Fehlerbehebungen {#v0.2.4-bugs-squashed}+- Einen Fehler beim Abrufen der Antwort-Bytes nach Verwendung des Arguments `network_idle` in den Klassen `StealthyFetcher` und `PlayWrightFetcher` behoben. <br/> Er verursachte die folgende Fehlermeldung:++ ```+ Response.body: Protocol error (Network.getResponseBody): No resource with given identifier found+ ```++- Die PlayWright-API gibt bei Antworten manchmal einen leeren Statustext zurück. In diesem Fall ermittelt `Scrapling` ihn jetzt selbst. Dies betrifft die Klassen `StealthyFetcher` und `PlayWrightFetcher`.++## [v0.2.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.3) - 2024-11-19 {#v0.2.3}++### Was sich geändert hat {#v0.2.3-what-s-changed}++##### Fehlerbehebungen {#v0.2.3-bugs-squashed}+- Einen Fehler bei der Installation mit pip behoben, durch den der Stealth-Modus des PlayWright-Fetchers überhaupt nicht funktionierte.++## [v0.2.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.2) - 2024-11-16 {#v0.2.2}++### Was sich geändert hat {#v0.2.2-what-s-changed}+##### Neue Funktionen {#v0.2.2-new-features}+- Wenn Sie dem erzeugten `Adaptor`-Objekt keine Argumente übergeben und die Standardwerte nutzen möchten, können Sie für übersichtlicheren Code stattdessen diesen Import verwenden++ ```python+ >> from scrapling.default import Fetcher, StealthyFetcher, PlayWrightFetcher+ >> page = Fetcher.get('https://example.com', stealthy_headers=True)+ ```++ Andernfalls++ ```python+ >> from scrapling import Fetcher, StealthyFetcher, PlayWrightFetcher+ >> page = Fetcher(auto_match=False).get('https://example.com', stealthy_headers=True)+ ```++##### Fehlerbehebungen {#v0.2.2-bugs-squashed}+1. Einen Fehler mit dem `Response`-Objekt behoben, der gestern mit Patch v0.2.1 eingeführt wurde und in manchen Fällen bei verschachtelter Auswahl oder Analyse auftrat.++## [v0.2.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.1) - 2024-11-15 {#v0.2.1}++### Was sich geändert hat {#v0.2.1-what-s-changed}+##### Neue Funktionen {#v0.2.1-new-features}+1. Das von allen Fetchern zurückgegebene `Response`-Objekt entspricht jetzt dem `Adaptor`-Objekt, hat aber zusätzlich diese Attribute: `status`, `reason`, `cookies`, `headers` und `request_headers`. Die Attribute `cookies`, `headers` und `request_headers` sind immer vom Typ `dictionary`. <br/>Ihr Code kann jetzt also so aussehen:++ ```python+ >> from scrapling import Fetcher+ >> page = Fetcher().get('https://example.com', stealthy_headers=True)+ >> print(page.status)+ 200+ >> products = page.css('.product')+ ```++ Statt wie bisher++ ```python+ >> from scrapling import Fetcher+ >> fetcher = Fetcher().get('https://example.com', stealthy_headers=True)+ >> print(fetcher.status)+ 200+ >> page = fetcher.adaptor+ >> products = page.css('.product')+ ```++ Die Eigenschaft `.adaptor` funktioniert zur Abwärtskompatibilität aber weiterhin.++2. Die Klassen `StealthyFetcher` und `PlayWrightFetcher` akzeptieren jetzt beim Abrufen ein Argument `proxy`, das eine Zeichenkette oder ein Dictionary sein kann.+3. Die Klasse `StealthyFetcher` hat jetzt das Argument `os_randomize` in der Methode `fetch`. Wenn es aktiviert ist, wählt Scrapling die Betriebssystem-Fingerprints zufällig aus. Standardmäßig passen die Fingerprints zum aktuellen Betriebssystem.++##### Fehlerbehebungen {#v0.2.1-bugs-squashed}+1. Einen Fehler beim Übergeben von Headern mit der Klasse `Fetcher` behoben.+2. Einen Fehler beim Parsen von JSON-Antworten aus Fetcher-Klassen behoben.++##### Verbesserungen der Bedienung {#v0.2.1-quality-of-life-changes}+1. Die Textfunktion versuchte bisher, HTML-Kommentare vor der Rückgabe des Textes zu entfernen. Das führte in manchen Fällen zu Fehlern und machte den Code unnötig kompliziert. Jetzt verwendet sie wieder das Standardverhalten von lxml. **Alle Operationen, die den Text von Elementen nutzen, etwa Selektoren, sind dadurch etwas schneller.** Wenn Scrapling HTML-Kommentare aus Elementen vor der Textrückgabe entfernen soll, um das ungewöhnliche Aufteilen des Textes in lxml/parsel/scrapy zu vermeiden, lassen Sie das Argument `keep_comments` einfach wie standardmäßig auf True gesetzt.++## [v0.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2) - 2024-11-11 {#v0.2}++### Was sich geändert hat {#v0.2-what-s-changed}+##### Neue Funktionen {#v0.2-new-features}+1. Die neue Funktion `Fetchers` mit 3 Haupttypen ist da. Damit ruft Scrapling Seiten für Sie ab, mit VIELEN Optionen!+ - Die Klasse `Fetcher` für einfache HTTP-Anfragen+ - Die Klasse `StealthyFetcher` ist ein vollständig getarnter Fetcher, der eine [zur Tarnung angepasste Firefox-Version](https://github.com/daijro/camoufox) nutzt.+ - Die Klasse `PlayWrightFetcher` ermöglicht Browser-Anfragen mit unverändertem PlayWright, mit meinem Stealth-Modus für PlayWright, mit echten Browsern über CDP und mit [NSTBrowser](https://app.nstbrowser.io/r/1vO5e5) über dessen [Docker-Browserless-Image](https://hub.docker.com/r/nstbrowser/browserless)!+2. Die völlig neuen Methoden `find_all`/`find` hinzugefügt, mit denen Sie Elemente auf der Seite ganz einfach wie durch dunkle Magie finden!+3. Die Methoden `filter` und `search` zur Klasse `Adaptors` hinzugefügt, um Gruppen von `Adaptor`-Objekten leichter gemeinsam zu verarbeiten.+4. Die Methoden `css_first` und `xpath_first` für eine einfachere Nutzung hinzugefügt.+5. Den neuen Klassentyp `TextHandlers` hinzugefügt. Damit können Sie `TextHandler`-Objekte gemeinsam verarbeiten, ähnlich wie mit der Klasse `Adaptors`.+6. Die Methoden `generate_full_css_selector` und `generate_full_xpath_selector` hinzugefügt.++##### Fehlerbehebungen {#v0.2-bugs-squashed}+1. Die Klasse `Adaptors` gibt mit `re_first` jetzt das erste passende Ergebnis aus allen enthaltenen `Adaptor`-Objekten zurück. Zuvor gab sie fälschlicherweise die Ergebnisse von `re_first` aller `Adaptor`-Objekte zurück.+2. Wenn Sie Text aus ausgewählten Elementen abrufen, etwa mit der CSS-Funktion `::text` über Methoden wie `.css` oder `.xpath`, gibt das `Adaptor`-Objekt jetzt `TextHandlers` statt einer Liste von Zeichenketten zurück. Sie können also jetzt `page.css('something::text').re_first(r'regex_pattern').json()` statt `page.css('something::text')[0].re_first(r'regex_pattern').json()` verwenden.+3. Die Argumente von re/re_first in `Adaptor`/`Adaptors` stimmen jetzt mit denen von `TextHandler` überein. Sie haben also jetzt die Argumente `clean_match` und `case_sensitive`.+4. Das Argument `auto_match` ist jetzt bei der Initialisierung von `Adaptor` standardmäßig aktiviert. Sie müssen es aber weiterhin bei der Elementauswahl aktivieren, wenn Sie die Funktion nutzen möchten. (Kein Fehler, sondern eine Designentscheidung.)+5. Viele Typangaben an verschiedenen Stellen korrigiert, um die automatische Vervollständigung beim Programmieren mit Scrapling zu verbessern.++##### Verbesserungen der Bedienung {#v0.2-quality-of-life-changes}+1. Die Methoden `css_selector` und `xpath_selector` in `generate_css_selector` und `generate_xpath_selector` umbenannt. Das macht die Namen klarer und stört die automatische Vervollständigung beim Programmieren nicht mehr.+2. Den größten Teil des alten Codes in ein Unterpaket `core` verschoben und weitere Designentscheidungen getroffen, um den Code übersichtlicher und die spätere Wartung einfacher zu machen.+3. Den Testordner übersichtlicher aufgebaut und Tests für die neuen Funktionen ergänzt. Außerdem werden tox-Umgebungen jetzt auf GitHub zwischengespeichert, damit die automatischen Tests bei jedem Commit schneller laufen.++## [v0.1.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.2) - 2024-10-16 {#v0.1.2}++**Änderungsverlauf**:++- Einen Fehler behoben, bei dem das Argument `keep_comments` nicht wie vorgesehen funktionierte.+- Die Textfunktion so angepasst, dass sie HTML-Kommentare vor dem Extrahieren des Textes automatisch aus Elementen entfernt, um das abweichende Verhalten von Lxml zu vermeiden. Zum Beispiel:++ ```python+ >>> page = Adaptor('<span>CONDITION: <!-- -->Excellent</span>', keep_comments=True)+ >>> page.css('span::text')+ ['CONDITION: ', 'Excellent']+ ```++ Dies war zuvor wegen des Standardverhaltens von Lxml das Ergebnis. Jetzt wird der vollständige Text 'CONDITION: Excellent' zurückgegeben.+ Dieses Verhalten ist auch aus parsel\scrapy bekannt. Deshalb wollte ich es hier abfangen.++- Einen Fehler behoben, bei dem die von der Bibliothek erzeugte SQLite-Datenbankdatei bei `pip uninstall scrapling` oder ähnlichen Befehlen nicht gelöscht wurde.++## [v0.1.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.1) - 2024-10-14 {#v0.1.1}++Kleine Korrekturen++## [v0.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1) - 2024-10-13 {#v0.1}++**Vollständiger Änderungsverlauf**: <https://github.com/D4Vinci/Scrapling/commits/v0.1>diff --git a/docs/locales/es/changelog.md b/docs/locales/es/changelog.mdnew file mode 100644index 0000000..dc83d70--- /dev/null+++ b/docs/locales/es/changelog.md@@ -0,0 +1,1279 @@+---+title: "Historial de cambios de Scrapling"+description: "Notas de las versiones de Scrapling, con nuevas funciones, correcciones y cambios incompatibles."+---++# Historial de cambios {#changelog}++Todos los cambios importantes de Scrapling, tomados de las [versiones de GitHub](https://github.com/D4Vinci/Scrapling/releases).++## [v0.4.15](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.15) - 2026-08-23 {#v0.4.15}++**Una de las mayores versiones de este año: un servidor MCP renovado, Markdown listo para RAG en una línea, un solucionador de Cloudflare mejorado y pestañas del navegador que siguen abiertas para la automatización 🚀**++!!! warning "Advertencia"++ **Esta versión introduce cambios incompatibles en el servidor MCP. Consulta la sección de [cambios incompatibles](https://github.com/D4Vinci/Scrapling/blob/v0.4.15/docs/ai/mcp-server.md#breaking-changes) antes de actualizar.**++### 🚀 Novedades y mejoras de uso {#v0.4.15-new-stuff-and-quality-of-life-changes}++- **Las pestañas del navegador ahora siguen abiertas y se reutilizan entre solicitudes** (consulta la [documentación](fetching/stealthy.md#session-management)):+ - Todas las sesiones del navegador conservan sus pestañas tras una solicitud, y la siguiente reutiliza una pestaña libre en lugar de abrir otra.+ - Cada solicitud vuelve a aplicar sus propios ajustes (tiempos de espera, cabeceras y bloqueo de recursos) a la pestaña que recibe, por lo que los ajustes no pasan de una solicitud a otra.+ - Las pestañas que dan error se cierran y se reemplazan, y el nuevo método `close_pages()` cierra todas las pestañas abiertas.+ - La página que obtuviste sigue cargada, de modo que una función `page_setup` en la siguiente solicitud se ejecuta sobre ella antes de navegar a otra página. Esto permite encadenar pasos de automatización entre solicitudes.++- **Convierte cualquier página en Markdown limpio y listo para LLM con `Response.markdown()`** (consulta la [documentación](ai/building-rag-systems.md)):++ ```python+ from scrapling.fetchers import Fetcher++ markdown = Fetcher.get("https://example.com").markdown(main_content_only=True)+ ```++ - Primero se eliminan siempre los scripts, los estilos y el contenido oculto de inyección de prompts, con la misma limpieza que hace el servidor MCP.+ - Pasa `css_selector` para convertir solo los elementos que necesitas.+ - Disponible mediante el nuevo extra `rag` (`pip install "scrapling[rag]"`), también incluido en los extras `ai`/`shell`/`all`.++- **Nueva plantilla `SiteToMarkdownSpider` para rastrear un sitio completo y crear una colección de documentos Markdown para procesos RAG** (consulta la [documentación](ai/building-rag-systems.md)):++ ```python+ from scrapling.spiders import SiteToMarkdownSpider++ class DocsSpider(SiteToMarkdownSpider):+ name = "docs"+ start_urls = ["https://example.com/docs/"]+ allowed_domains = {"example.com"}+ output_dir = "docs_markdown"++ result = DocsSpider().start()+ result.items.to_jsonl("docs.jsonl")+ ```++ - Produce un elemento por página con `url`/`title`/`markdown`, y el ajuste opcional `output_dir` escribe un archivo Markdown por página.+ - `max_pages` limita el rastreo y, como se basa en `CrawlSpider`, redefinir `rules()` te da control total sobre los enlaces que se siguen.++- **El servidor MCP se ha rediseñado (cambio incompatible)** (consulta los [cambios incompatibles](https://github.com/D4Vinci/Scrapling/blob/v0.4.15/docs/ai/mcp-server.md#breaking-changes) y la [documentación](ai/mcp-server.md)):+ - Las 13 herramientas ahora se dividen en dos modos: herramientas de una sola ejecución (`fetch`, `bulk_fetch`, `stealthy_fetch`, `bulk_stealthy_fetch`), que siempre abren su propio navegador y muestran sus valores predeterminados reales, y herramientas de sesión, que usan una sesión abierta una sola vez.+ - La nueva herramienta `session_fetch` obtiene páginas mediante una sesión del navegador, mientras que `open_session` ahora solo guarda los ajustes del navegador y devuelve los ajustes efectivos de la sesión al agente de IA.+ - La herramienta `get` pasa a llamarse `make_request` y ahora admite cualquier método HTTP.+ - Las nuevas herramientas `open_request_session` y `session_make_request` dan a la IA sesiones HTTP persistentes que conservan las cookies y la huella del navegador entre solicitudes.+ - Esto también evita que las operaciones de obtención restablezcan los ajustes de la sesión, un problema que @Yigtwxx corrigió primero en [#418](https://github.com/D4Vinci/Scrapling/pull/418).++- **El transporte HTTP del servidor MCP ahora exige autenticación y escucha en localhost de forma predeterminada (cambio incompatible)**, por @yamantaka-singh en [#414](https://github.com/D4Vinci/Scrapling/pull/414) (corrige [#413](https://github.com/D4Vinci/Scrapling/issues/413); consulta la [documentación](ai/mcp-server.md#authentication)):+ - Pasa `--auth-token` (o la variable de entorno `SCRAPLING_MCP_AUTH_TOKEN`) para exigir un token bearer, o `--no-auth` si quieres servirlo sin autenticación de forma explícita.+ - Pasa `--host 0.0.0.0` para aceptar conexiones desde la red.++### 🐛 Correcciones de errores {#v0.4.15-bug-fixes}++- **La resolución de Cloudflare Turnstile/Interstitial ahora funciona sin importar la configuración regional del navegador y ya no entra en un bucle infinito con desafíos interactivos en modo headless**. Las páginas del navegador sigiloso también dejan de fallar durante la resolución, con aportes de @subediparas5 en [#412](https://github.com/D4Vinci/Scrapling/pull/412). (Corrige [#411](https://github.com/D4Vinci/Scrapling/issues/411) y [#422](https://github.com/D4Vinci/Scrapling/issues/422))+- **Corregido el problema por el que `find`/`find_all` con `class_` omitían sin avisar elementos con varias clases**, por @yetval en [#410](https://github.com/D4Vinci/Scrapling/pull/410), **y los valores vacíos de `class_` y las cadenas CSS sin escapar**, por @yamantaka-singh en [#417](https://github.com/D4Vinci/Scrapling/pull/417).+- **Corregida la pérdida de metadatos de la solicitud al reutilizar respuestas en caché en `development_mode`**, por @Yigtwxx en [#419](https://github.com/D4Vinci/Scrapling/pull/419).+- **Corregidas las solicitudes HTTP con `retries` inferior a 1 que fallaban sin enviar la solicitud**, por @Yigtwxx en [#420](https://github.com/D4Vinci/Scrapling/pull/420).++### Documentación {#v0.4.15-docs}++- **Se han reorganizado las secciones del sitio**: la nueva sección "Uso con IA" contiene el servidor MCP, la nueva página de [habilidad para agentes](ai/agent-skill.md) y la guía para [crear sistemas RAG](ai/building-rag-systems.md). La guía de migración desde BeautifulSoup pasó junto a la integración con Scrapy en "Integraciones y migraciones".+- **Añadido un [historial de cambios](changelog.md)** al repositorio con las notas de todas las versiones publicadas hasta ahora.++## [v0.4.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.14) - 2026-08-10 {#v0.4.14}++**Una versión de mantenimiento rápida para corregir la instalación con `uv` 🔧**++### 🐛 Correcciones de errores {#v0.4.14-bug-fixes}++- **Corregido el problema por el que `uv` rechazaba instalar v0.4.13 de forma predeterminada y usaba una versión anterior sin avisar**. La versión anterior exigía una versión preliminar de `curl_cffi`, que `uv` no permite salvo que lo actives de forma explícita.+Todas las dependencias ahora se resuelven con versiones estables. (Corrige [#407](https://github.com/D4Vinci/Scrapling/issues/407))++## [v0.4.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.13) - 2026-08-09 {#v0.4.13}++**Una nueva actualización con spiders para feeds y un servidor MCP más inteligente 🎉**++### 🚀 Novedades y mejoras de uso {#v0.4.13-new-stuff-and-quality-of-life-changes}++- **Nuevas plantillas de spiders para feeds**. `XMLFeedSpider` recorre los nodos de cualquier feed XML (RSS, Atom, feeds de productos, etc.), y `CSVFeedSpider` recorre las filas CSV como diccionarios. Ambos descomprimen automáticamente los feeds comprimidos con gzip. (Consulta la [documentación](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import XMLFeedSpider++ class RSSSpider(XMLFeedSpider):+ name = "rss"+ start_urls = ["https://example.com/feed.xml"]++ async def parse_node(self, response, node):+ yield {"title": node.findtext("title"), "link": node.findtext("link")}++ result = RSSSpider().start()+ ```++- **El servidor MCP se ha actualizado a MCP SDK v2 y ahora es más inteligente**. El servidor incluye instrucciones que enseñan a tu agente de IA a usar las herramientas con eficiencia; cada herramienta declara anotaciones para que clientes como Claude Code puedan aprobar automáticamente las que solo leen; las descripciones son más breves para ahorrar tokens; y el servidor informa de su versión y logotipo a los clientes MCP. (Consulta la [documentación](ai/mcp-server.md))+- **Añadido el comando `scrapling-mcp`**, que ejecuta directamente `scrapling mcp`, para registrar Scrapling en clientes y registros MCP que esperan un único comando con una sola línea.+- **Las versiones de Playwright/Patchright y de los navegadores ya no están fijadas**. El User-Agent generado ahora siempre coincide con la versión exacta de Chromium que controla tu instalación de Playwright/Patchright, por lo que Scrapling ya no fija sus versiones y puedes actualizarlas libremente. Ejecuta `scrapling install --force` después de actualizar para renovar los navegadores.++### 🐛 Correcciones de errores {#v0.4.13-bug-fixes}++- **Corregido el fallo al importar Scrapling con un ValueError de `browserforge`** cuando el paquete de datos de huellas se queda atrás respecto a las versiones de los navegadores. (Corrige [#394](https://github.com/D4Vinci/Scrapling/issues/394), [#396](https://github.com/D4Vinci/Scrapling/issues/396) y [#400](https://github.com/D4Vinci/Scrapling/issues/400))+- **Corregido el tamaño incorrecto de los grupos de páginas en las herramientas de navegador por lotes de MCP**, que hacía fallar `bulk_fetch` con lotes de más de 50 URL y que `bulk_stealthy_fetch` obtuviera todas las URL desde una sola pestaña, por @Yigtwxx en [#393](https://github.com/D4Vinci/Scrapling/pull/393).++### Proyecto {#v0.4.13-project}++- **Nueva [política de contribuciones con IA](https://github.com/D4Vinci/Scrapling/blob/main/AI_POLICY.md)**: las contribuciones asistidas por IA son bienvenidas, pero debes indicarlo en la solicitud de cambios o en la incidencia; los envíos que parezcan generados por IA sin indicarlo se etiquetan y se cierran.++## [v0.4.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.12) - 2026-07-26 {#v0.4.12}++**Una versión centrada en que tus spiders se adapten mejor a los sitios que rastrean**++### 🚀 Novedades y mejoras de uso {#v0.4.12-new-stuff-and-quality-of-life-changes}++- **Los spiders ahora pueden ajustar su propia velocidad con AutoThrottle.** En lugar de adivinar un `download_delay` que puede ser demasiado lento o provocar un bloqueo, el spider mide cuánto tarda cada sitio en responder y ajusta la espera de cada dominio por su cuenta. Cuando un sitio empieza a bloquearte o limitar tus solicitudes, duplica la espera (o espera exactamente lo que indique la cabecera `Retry-After`) hasta que deje de hacerlo, y después vuelve a acelerar. Tu `download_delay` y cualquier `Crawl-delay` de robots.txt siguen siendo el mínimo. (Consulta la [documentación](spiders/advanced.md#autothrottle))++ ```python+ class MySpider(Spider):+ name = "adaptive"+ start_urls = ["https://example.com"]+ autothrottle_enabled = True+ autothrottle_start_delay = 2.0+ autothrottle_max_delay = 30.0+ autothrottle_block_backoff = True+ ```++- **Exporta tus resultados a CSV y XML**, además de los exportadores JSON/JSONL que ya tenías. Los elementos que no comparten todas las claves se siguen exportando sin perder datos, y los valores anidados se escriben como JSON. (Consulta la [documentación](spiders/getting-started.md))++ ```python+ result = MySpider().start()+ result.items.to_csv("products.csv")+ result.items.to_xml("products.xml")+ ```++- **El servidor MCP ahora puede exigir autenticación**, para que puedas exponerlo de forma segura en lugar de mantenerlo solo en tu equipo. Se rechaza cualquier solicitud sin el token, y también puedes limitar los nombres de host a los que responde el servidor. (Consulta la [documentación](ai/mcp-server.md))++ ```bash+ scrapling mcp --http --auth-token "$(openssl rand -hex 32)"+ ```++- **Los navegadores ahora aceptan URL de CDP por HTTP**, además de las de WebSocket. Así, junto a los endpoints `wss://` de los proveedores de navegadores gestionados, puedes conectar cualquier fetcher de navegador o sesión MCP a un Chrome que hayas iniciado con `--remote-debugging-port=9222`.++- **Las imágenes Docker publicadas ahora llevan una etiqueta con su versión**, en lugar de solo `latest`, para que puedas fijar la versión exacta que quieras, por @JanRK en [#384](https://github.com/D4Vinci/Scrapling/pull/384).++### 🐛 Correcciones de errores {#v0.4.12-bug-fixes}++- **Corregida la pérdida de todas las cookies en las respuestas en caché** cuando procedían de un motor de navegador, lo que rompía sin avisar la lógica de sesión o autenticación que dependía de ellas al usar el modo de desarrollo de los spiders, por @amitvijapur en [#379](https://github.com/D4Vinci/Scrapling/pull/379). (Corrige [#376](https://github.com/D4Vinci/Scrapling/issues/376))++- **Corregido el problema por el que `StealthyFetcher` imponía la configuración regional `en-US`** a todos los navegadores en lugar de seguir la del sistema. Esto hacía que los sitios detectaran una diferencia entre tu configuración regional y tu dirección IP y te trataran como sospechoso, por ejemplo con respuestas 429 de Google. (Corrige [#381](https://github.com/D4Vinci/Scrapling/issues/381))++- **Corregido un mensaje de error engañoso en el sistema de almacenamiento** y eliminada una llamada sin uso que quedaba tras las inserciones, por @fix2015 en [#377](https://github.com/D4Vinci/Scrapling/pull/377).++### Rendimiento {#v0.4.12-performance}++- **El tiempo de ejecución de `get_all_text()` ahora crece en proporción al número de nodos, O(nodes)** en lugar de recorrer los ancestros de cada nodo de texto, lo que lo hace unas 5-6 veces más rápido en páginas con muchos niveles anidados, por @yetval en [#378](https://github.com/D4Vinci/Scrapling/pull/378).++## [v0.4.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.11) - 2026-07-12 {#v0.4.11}++**Una actualización importante con la primera plantilla de spider para una plataforma, un parser más rápido y correcciones importantes 🎉**++### 🚀 Novedades y mejoras de uso {#v0.4.11-new-stuff-and-quality-of-life-changes}++- **¡Añadido `ShopifySpider`, la primera plantilla de spider para una plataforma!** Extrae todos los productos de cualquier tienda Shopify mediante su API JSON sin usar el HTML del sitio. Crea una subclase, define el dominio de la tienda y listo (consulta la [documentación](spiders/platform-templates.md))++ ```python+ from scrapling.spiders import ShopifySpider++ class MyStore(ShopifySpider):+ target_website = "example.com"++ result = MyStore().start()+ ```++- **Añadido `--executable-path` a los comandos de navegador de la CLI**. Tanto `scrapling extract fetch` como `scrapling extract stealthy-fetch` ahora aceptan un ejecutable de navegador personalizado compatible con Chromium, y usan la variable de entorno `SCRAPLING_EXECUTABLE_PATH` cuando no pasas la opción. Así ofrecen lo mismo que el servidor MCP (resuelve [#371](https://github.com/D4Vinci/Scrapling/issues/371))++ ```bash+ scrapling extract fetch "https://example.com" page.html --executable-path "/path/to/chromium"+ ```++### 🤖 Mejoras de uso {#v0.4.11-quality-of-life-changes}+- **`find_by_text` y `find_by_regex` ahora son hasta unas 2 veces más rápidos** cuando `first_match` está activado (valor predeterminado), porque los elementos se convierten en objetos solo cuando hace falta y la búsqueda se detiene en la primera coincidencia, por @yetval en [#370](https://github.com/D4Vinci/Scrapling/pull/370)+- **Actualizadas las pruebas de rendimiento con las cifras nuevas frente a las últimas versiones de todas las bibliotecas.**+- **Actualizadas las reglas de contribución**++### 🐛 Correcciones de errores {#v0.4.11-bug-fixes}++- **Corregidos los fallos de las herramientas de obtención del servidor MCP en páginas con caracteres de control**, que daban el error `All strings must be XML compatible`, por @yetval en [#368](https://github.com/D4Vinci/Scrapling/pull/368) (corrige [#366](https://github.com/D4Vinci/Scrapling/issues/366))++## [v0.4.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.10) - 2026-07-04 {#v0.4.10}++**Una nueva actualización con una integración con Scrapy y varias correcciones de la comunidad 🎉**++### 🚀 Novedades y mejoras de uso {#v0.4.10-new-stuff-and-quality-of-life-changes}++- **Añadida una integración con Scrapy** para usar la API de análisis de Scrapling en tus proyectos Scrapy actuales sin reescribirlos. Aplica el decorador `scrapling_response` a cualquier callback de un spider y la respuesta que recibe se convierte en una `Response` de Scrapling, mientras Scrapy sigue gestionando el rastreo (consulta la [documentación](integrations/scrapy.md)):++ ```python+ import scrapy+ from scrapling.integrations.scrapy import scrapling_response++ class QuotesSpider(scrapy.Spider):+ name = "quotes"+ start_urls = ["https://quotes.toscrape.com"]++ @scrapling_response+ def parse(self, response): # `response` is now a Scrapling Response+ first_quote = response.find_by_text("The world as we have created it", partial=True)+ for quote in [first_quote, *first_quote.find_similar()]:+ yield {"text": quote.get_all_text(strip=True)}+ ```++- **El servidor MCP ahora puede usar un navegador personalizado compatible con Chromium** para todas las herramientas basadas en navegador. Defínelo una vez con `scrapling mcp --executable-path "/path/to/chromium"` o con la variable de entorno `SCRAPLING_EXECUTABLE_PATH`, o por solicitud con el argumento `executable_path`, por @samrusani en [#360](https://github.com/D4Vinci/Scrapling/pull/360) (resuelve [#347](https://github.com/D4Vinci/Scrapling/issues/347))+- **Actualizados todos los navegadores y las huellas**. Ejecuta `scrapling install --force` después de actualizar para renovarlos.++### 🐛 Correcciones de errores {#v0.4.10-bug-fixes}++- **Corregido el texto ilegible (mojibake) de los fetchers de navegador en sitios que no usan UTF-8**, por @yehudalevy-collab en [#365](https://github.com/D4Vinci/Scrapling/pull/365) (corrige [#364](https://github.com/D4Vinci/Scrapling/issues/364)).+- **Corregido el problema por el que `LinkExtractor` no filtraba extensiones de archivo compuestas como `.tar.gz`**, por @renbkna en [#359](https://github.com/D4Vinci/Scrapling/pull/359) (corrige [#349](https://github.com/D4Vinci/Scrapling/issues/349)).+- **Corregida la pérdida de solicitudes en curso en los puntos de guardado de rastreos pausados, para que ya no se omitan al reanudar**, por @yetval en [#358](https://github.com/D4Vinci/Scrapling/pull/358).+- **Corregido el cálculo incorrecto de las esperas de rastreo a partir de las directivas `Request-rate` de robots.txt** mediante la actualización de Protego, con pruebas ajustadas por @Disaster-Terminator en [#355](https://github.com/D4Vinci/Scrapling/pull/355).++### Documentación {#v0.4.10-docs}++- **Aclarada la interacción de `init_script` con el contexto de ejecución aislado de Patchright en modo sigiloso**, por @mturac en [#353](https://github.com/D4Vinci/Scrapling/pull/353) (resuelve [#350](https://github.com/D4Vinci/Scrapling/issues/350)).+- **Añadido el método de instalación de la habilidad para agentes mediante [skills.sh](https://skills.sh/D4Vinci/Scrapling)**, por @ob-aion en [#363](https://github.com/D4Vinci/Scrapling/pull/363).++## [v0.4.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.9) - 2026-06-07 {#v0.4.9}++**Una actualización de mantenimiento llena de correcciones de problemas que comunicó la comunidad 🛠️**++### 🚀 Novedades y mejoras de uso {#v0.4.9-new-stuff-and-quality-of-life-changes}++- **Actualizados todos los navegadores y las huellas**. Ejecuta `scrapling install --force` después de actualizar para renovarlos.+- **Añadida la opción `--version` a la CLI**, por @ETM-Code en [#303](https://github.com/D4Vinci/Scrapling/pull/303) (resuelve [#299](https://github.com/D4Vinci/Scrapling/issues/299))++### 🐛 Correcciones de errores {#v0.4.9-bug-fixes}++- **Corregido el problema por el que el argumento `proxy` de la sesión se ignoraba sin avisar en las sesiones HTTP**, lo que podía revelar tu IP real (resuelve [#295](https://github.com/D4Vinci/Scrapling/issues/295)). Ten en cuenta que combinar un `proxy` de sesión con un argumento `proxies` por solicitud (o al revés) ahora genera un error en lugar de ignorar uno de ellos sin avisar.+- **Corregidos los fallos de navegación al combinar `init_script` con `user_data_dir`** (resuelve [#294](https://github.com/D4Vinci/Scrapling/issues/294)).+- **Corregida la detección de codificación cuando los sitios ponen entre comillas el valor charset de la cabecera `Content-Type`**, por @Bortlesboat en [#323](https://github.com/D4Vinci/Scrapling/pull/323).+- **Corregido un `IndexError` en la reubicación adaptativa de elementos cuando `auto_save` está activado**, por @Mubashirrrr en [#340](https://github.com/D4Vinci/Scrapling/pull/340).+- **Corregidos los fallos al guardar los puntos de guardado y la caché de los spiders en Windows**, por @MrStarkEG en [#344](https://github.com/D4Vinci/Scrapling/pull/344).+- **Corregido el cálculo de similitud de `find_similar` para elementos con distinto número de atributos** (resuelve [#322](https://github.com/D4Vinci/Scrapling/issues/322)).++### Documentación {#v0.4.9-docs}++- **Aclarado que la instalación predeterminada solo incluye el motor de análisis**, y que los fetchers y los spiders necesitan los extras (resuelve [#343](https://github.com/D4Vinci/Scrapling/issues/343)).+- **Corregido el nombre de la imagen Docker en los ejemplos restantes**, por @evanclan en [#315](https://github.com/D4Vinci/Scrapling/pull/315).+- **Corregido un enlace roto en la guía de contribución**, por @Bortlesboat en [#320](https://github.com/D4Vinci/Scrapling/pull/320).++## [v0.4.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.8) - 2026-05-11 {#v0.4.8}++**Una gran actualización de spiders que mejora el sistema de rastreo 🕷️**++### 🚀 Novedades y mejoras de uso {#v0.4.8-new-stuff-and-quality-of-life-changes}++- **Añadida la herramienta `LinkExtractor`** en `scrapling.spiders.LinkExtractor` para extraer URL de una `Response`. Tiene muchos controles (consulta la [documentación](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import LinkExtractor++ extractor = LinkExtractor(allow=r"/posts/", deny_domains=["ads.example.com"])+ ```++- **Añadidas las plantillas de spider genéricas `CrawlSpider` y `CrawlRule`** para que ya no tengas que escribir una y otra vez el mismo código para "seguir enlaces que coincidan con este patrón". Redefine `rules()` para devolver una lista de objetos `CrawlRule`, cada uno asociado a un `LinkExtractor`. (Consulta la [documentación](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import CrawlSpider, CrawlRule, LinkExtractor++ class QuotesSpider(CrawlSpider):+ name = "blog"+ start_urls = ["https://quotes.toscrape.com/"]++ def rules(self):+ return [+ CrawlRule(LinkExtractor(allow=r"/author/"), callback=self.parse_author),+ CrawlRule(LinkExtractor(allow=r"/page/\d+/")), # pagination, no callback+ ]++ async def parse_author(self, response):+ yield {+ "name": response.css(".author-title::text").get(),+ "birthday": response.css(".author-born-date::text").get(),+ "url": response.url,+ }+ ```++- **Añadida una plantilla `SitemapSpider`** que inicia un rastreo directamente desde un mapa del sitio o URL de `robots.txt`. Admite mapas del sitio comprimidos con gzip y muchos controles y opciones. Las URL se distribuyen mediante las reglas de rastreo, como en el ejemplo de **CrawlSpider** anterior. (Consulta la [documentación](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import SitemapSpider, CrawlRule, LinkExtractor++ class NewsSitemap(SitemapSpider):+ name = "news"+ sitemap_urls = ["https://example.com/robots.txt"]++ def rules(self):+ return [+ CrawlRule(LinkExtractor(allow=r"/articles/"), callback=self.parse_article),+ ]++ async def parse_article(self, response):+ yield {"url": response.url, "title": response.css("h1::text").get()}+ ```++- **La reubicación adaptativa ahora usa un umbral de similitud del 40% de forma predeterminada**, en lugar de `0`, en todos los métodos. Esto mejora el funcionamiento de la función adaptativa. Cuando ningún elemento supera el umbral, una advertencia muestra la puntuación más alta encontrada, para que puedas reducir `percentage` de forma consciente si hace falta.++- **Actualizados todos los navegadores y las huellas**. Vuelve a ejecutar `scrapling install --force` después de actualizar para renovar los navegadores y las huellas.++### 🐛 Correcciones de errores {#v0.4.8-bug-fixes}++- **Corregido el problema por el que `Fetcher.configure(...)` no se aplicaba a las llamadas por solicitud**. La misma corrección se aplicó a `AsyncFetcher`.+- **Corregido el cálculo incorrecto de huellas de solicitudes que causaba solicitudes duplicadas en los spiders**, por @yetval en [#255](https://github.com/D4Vinci/Scrapling/pull/255).+- **Corregido el silencio del motor de extracción adaptativa ante coincidencias débiles.** Junto con el cambio de umbral anterior, ahora recibes una advertencia en lugar de un elemento engañoso como "mejor aproximación" cuando falla la reubicación.++### Documentación {#v0.4.8-docs}++- **Actualizados los ejemplos de código antiguos** de la documentación para que coincidan con la versión actual.+- **Mejorada la experiencia al copiar y pegar código** en el sitio de documentación y acortada la habilidad para agentes para que use menos tokens en cada invocación.++## [v0.4.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.7) - 2026-04-17 {#v0.4.7}++**Una actualización centrada en dar visión a tus agentes de IA 📸**++### 🚀 Novedades y mejoras de uso {#v0.4.7-new-stuff-and-quality-of-life-changes}++- **Añadida una herramienta MCP `screenshot`** que captura una página y la devuelve como un bloque MCP real de tipo `ImageContent`, para que el modelo pueda verla. La herramienta exige una sesión de navegador abierta: primero llama a `open_session` (con `dynamic` o `stealthy`) y pasa aquí el `session_id`. Admite PNG y JPEG, capturas de página completa, calidad JPEG y los controles de espera habituales (`wait`, `wait_selector`, `network_idle`, `timeout`). (Implementa [#244](https://github.com/D4Vinci/Scrapling/issues/244))+- **Añadido un parámetro `session_id` personalizado a `open_session`** para dar a las sesiones nombres útiles (`"search"`, `"checkout"`) en lugar del valor hexadecimal aleatorio de 12 caracteres que se usa por defecto. Por @hauntedhost en [#243](https://github.com/D4Vinci/Scrapling/pull/243)++### 🐛 Correcciones de errores {#v0.4.7-bug-fixes}++- **Corregida la corrupción del estado de `FetcherSession` y un fallo al cerrar una sesión de inicio diferido**. Por @yetval en [#245](https://github.com/D4Vinci/Scrapling/pull/245)+- **Corregido `TypeError: Session.request() got an unexpected keyword argument 'block_ads'`** al usar la opción `--ai-targeted` de la CLI con comandos HTTP. Por @voidborne-d en [#249](https://github.com/D4Vinci/Scrapling/pull/249) (corrige [#247](https://github.com/D4Vinci/Scrapling/issues/247))++### Traducciones {#v0.4.7-translations}++- **Añadida una traducción del README al portugués de Brasil**, por @rgomids en [#250](https://github.com/D4Vinci/Scrapling/pull/250)++## [v0.4.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.6) - 2026-04-13 {#v0.4.6}++**Una actualización centrada en el sigilo del navegador, la privacidad y la experiencia de desarrollo 🔒**++### 🚀 Novedades y mejoras de uso {#v0.4.6-new-stuff-and-quality-of-life-changes}++- **Añadido el bloqueo de anuncios integrado** para los fetchers de navegador. Pasa `block_ads=True` para bloquear solicitudes a unos 3500 dominios conocidos de anuncios y rastreadores al interceptar la ruta: sin DNS, sin TCP y con cancelación inmediata. Puedes combinarlo con `blocked_domains` para usar listas propias. El servidor MCP y el modo `--ai-targeted` de la CLI lo activan automáticamente para ahorrar tokens y acelerar la carga de las páginas.++ ```python+ page = StealthyFetcher.fetch('https://example.com', block_ads=True)+ ```++- **Añadido soporte para DNS-over-HTTPS** para evitar fugas de DNS al usar proxies. Pasa `dns_over_https=True` para dirigir las consultas DNS al servicio DoH de Cloudflare, de modo que la resolución DNS no revele tu ubicación real aunque el tráfico HTTP pase por un proxy.++ ```python+ page = StealthyFetcher.fetch('https://example.com', proxy='http://proxy:8080', dns_over_https=True)+ ```++- **Añadido el callback `page_setup`** para los fetchers de navegador. Es una función que se ejecuta antes de `page.goto()` y permite registrar detectores de eventos, rutas o scripts que deben prepararse antes de navegar. Se combina con `page_action` (que se ejecuta después de navegar). (Resuelve [#237](https://github.com/D4Vinci/Scrapling/issues/237))++ ```python+ def capture_websockets(page):+ page.on("websocket", lambda ws: print(f"WS: {ws.url}"))++ page = DynamicFetcher.fetch('https://example.com', page_setup=capture_websockets)+ ```++- **Añadidas las opciones de CLI `--block-ads` y `--dns-over-https`** a los comandos `fetch` y `stealthy-fetch`.++### 🐛 Correcciones de errores {#v0.4.6-bug-fixes}++- **Corregido el alias de tipo `Seconds`**, que rechazaba valores decimales. Pasar `wait=1.5` o `timeout=500.0` a los fetchers de navegador fallaba con un error de tipo porque el alias trataba `float` como metadatos en lugar de como un tipo. Por @kuishou68 en [#240](https://github.com/D4Vinci/Scrapling/pull/240)+- **Corregidos los segmentos ID duplicados al generar selectores con la ruta completa**. El selector de los elementos con atributos `id` se añadía dos veces al generar rutas CSS/XPath completas y producía selectores como `body > #main > #main > #target > #target`. También se corrigió la generación de condiciones `[@id='x']` sueltas (XPath no válido) en lugar de `*[@id='x']` en rutas XPath completas. Por @sjhddh en [#241](https://github.com/D4Vinci/Scrapling/pull/241)+- **Corregidos los parámetros que faltaban en las firmas del shell**. En las firmas de las funciones del shell interactivo faltaban `blocked_domains`, `block_ads`, `retries`, `retry_delay`, `capture_xhr`, `executable_path` y `dns_over_https`.++## [v0.4.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.5) - 2026-04-07 {#v0.4.5}++**Una actualización con una gran mejora de uso para quienes desarrollan spiders y un par de correcciones importantes 🎉**++### 🚀 Novedades y mejoras de uso {#v0.4.5-new-stuff-and-quality-of-life-changes}++- **Modo de desarrollo de spiders**: probar cambios en la lógica de `parse()` de un spider antes exigía volver a consultar los servidores del sitio en cada ejecución. Esto es lento, genera tráfico y puede hacer que limiten tus solicitudes mientras todavía ajustas los selectores. El nuevo modo de desarrollo guarda cada respuesta en disco en la primera ejecución y la reutiliza desde el disco en las siguientes. Así puedes ajustar los callbacks y ejecutar tantas veces como quieras sin hacer ninguna solicitud de red. Actívalo con un atributo de clase:++ ```python+ class MySpider(Spider):+ name = "my_spider"+ start_urls = ["https://example.com"]+ development_mode = True++ async def parse(self, response):+ yield {"title": response.css("title::text").get("")}+ ```++ La caché se guarda en `.scrapling_cache/{spider.name}/` de forma predeterminada, y puedes cambiar su ubicación con `development_cache_dir`. Dos contadores nuevos, `cache_hits` y `cache_misses`, muestran cómo ha funcionado la caché. Al reutilizarla, se omiten `download_delay`, los límites de solicitudes y la ruta de reintentos de solicitudes bloqueadas, para que las pruebas sean tan rápidas como permita el disco. No publiques un spider con `development_mode = True`: es una herramienta de desarrollo, no una caché para producción. Consulta la [documentación](spiders/advanced.md#development-mode) para ver todos los detalles.++- **Redirecciones más seguras de forma predeterminada**: el valor predeterminado de `follow_redirects` ahora es `"safe"` en todos los fetchers HTTP, el servidor MCP y el shell. Las redirecciones se siguen, pero se rechazan las que apuntan a IP internas o privadas (loopback, redes privadas y link-local). Esto te protege frente a SSRF al extraer datos de URL que aportan los usuarios. Pasa `follow_redirects="all"` para recuperar el comportamiento anterior, o `False` para desactivar las redirecciones por completo.++### 🐛 Correcciones de errores {#v0.4.5-bug-fixes}++- **La detención forzada ya no pierde tu punto de guardado**: pulsar Ctrl+C dos veces (detención forzada) en un spider con `crawldir` activado antes podía coincidir con la escritura del punto de guardado. El ámbito de cancelación terminaba la tarea antes de completar el pickle, dejaba `paused=False` y activaba la limpieza que *elimina* el punto de guardado anterior. Así, detener por la fuerza un rastreo largo podía perder todo el progreso que intentabas guardar. El motor ahora escribe el punto de guardado **antes** de llamar a `cancel_scope.cancel()`, de modo que una detención forzada siempre conserva el último estado pendiente. Por @voidborne-d en [#230](https://github.com/D4Vinci/Scrapling/pull/230).++## [v0.4.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.4) - 2026-04-05 {#v0.4.4}++**Una nueva actualización con mejoras importantes en los spiders y correcciones de errores 🎉**++### 🚀 Novedades y mejoras de uso {#v0.4.4-new-stuff-and-quality-of-life-changes}+- **Añadido el cumplimiento de robots.txt al sistema de spiders** con la nueva opción `robots_txt_obey`. Al activarla, el spider obtiene y respeta automáticamente las reglas de robots.txt antes de rastrear, incluidas las directivas `Disallow`, `Crawl-delay` y `Request-rate`. Los archivos robots.txt se obtienen de forma concurrente y se guardan en caché por dominio durante todo el rastreo. Por @AbdullahY36 en [#226](https://github.com/D4Vinci/Scrapling/pull/226)+- **Añadida la preparación previa de la caché de robots.txt**, para obtener y analizar los archivos robots.txt de todos los dominios de start_urls antes de iniciar el bucle de rastreo. Así se evitan esperas en la primera solicitud a cada dominio.+- **Añadida la nueva estadística `robots_disallowed_count`** a `CrawlStats` para contar cuántas solicitudes bloquearon las reglas de robots.txt durante el rastreo.++Puedes verlo en el sitio desde [aquí](spiders/getting-started.md#robotstxt-compliance)++### 🐛 Correcciones de errores {#v0.4.4-bug-fixes}+- **Corregido un problema importante de MRO con `ProxyRotator`**, en el que el método provisional `_build_context_with_proxy` ocultaba la implementación real de las clases hijas y hacía que la rotación de proxies siempre lanzara `NotImplementedError` (corrige [#215](https://github.com/D4Vinci/Scrapling/issues/215)). Gracias, @yetval+- **Corregida una fuga en el grupo de páginas** al usar rotación de proxies por solicitud en sesiones de navegador. Las páginas creadas en contextos temporales no se eliminaban del grupo al limpiar, por lo que se acumulaban referencias obsoletas con el tiempo. Por @yetval en [#223](https://github.com/D4Vinci/Scrapling/pull/223)+- **Corregida una comprobación de tipo que faltaba** en el fetcher estático: `curl_cffi` podía devolver `None` desde `session.request()` y causar errores más adelante.++### Otros cambios {#v0.4.4-other}+- Actualizadas las dependencias para incluir las últimas huellas y otras novedades.+- Añadido `protego` como nueva dependencia del grupo opcional `fetchers` para analizar robots.txt.++## [v0.4.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.3) - 2026-03-30 {#v0.4.3}++**Una nueva actualización con muchos cambios importantes 🎉**++### 🚀 Novedades y mejoras de uso {#v0.4.3-new-stuff-and-quality-of-life-changes}+- **Añadida una nueva herramienta MCP** para abrir un navegador normal o sigiloso persistente y seguir usándolo con las demás herramientas, y otra nueva herramienta para cerrarlo. ([Ejemplos](https://github.com/D4Vinci/Scrapling/blob/v0.4.3/docs/ai/mcp-server.md#examples))+- **Añadida una nueva herramienta MCP** para listar todas las sesiones de navegador existentes, pensada para usarse con las herramientas nuevas.+- **Añadida una nueva opción a las sesiones de navegador** para recoger automáticamente todas las solicitudes en segundo plano que ocurren durante una solicitud (resuelve [#159](https://github.com/D4Vinci/Scrapling/pull/159)) [[Ejemplos](https://github.com/D4Vinci/Scrapling/blob/v0.4.3/docs/fetching/dynamic.md#capturing-xhrfetch-requests)].+- **Añadido un nuevo limpiador** para proteger el servidor MCP de ataques comunes de inyección de prompts eliminando el contenido oculto o invisible.+- **Añadida una nueva opción de línea de comandos**, llamada `--ai-targeted`, a los comandos de extracción web para preparar el contenido para la IA y protegerlo frente a ataques comunes de inyección de prompts, como hace el servidor MCP.+- **Añadida una nueva opción a las sesiones de navegador**, llamada `executable_path`, para definir una ruta de navegador personalizada (resuelve [#202](https://github.com/D4Vinci/Scrapling/pull/202))+- **Reorganizado** el código del servidor MCP para facilitar su mantenimiento, y unificadas todas las herramientas para que sean asíncronas.+- **Reorganizado** el código de los comandos de la CLI para facilitar su mantenimiento y reducirlo en 210 líneas.++### 🐛 Correcciones de errores {#v0.4.3-bug-fixes}+- Corregido un error para conservar el método HTTP entre reintentos en la sesión del spider, por @karesansui-u en [#201](https://github.com/D4Vinci/Scrapling/pull/201)+- Añadido un límite máximo de reintentos al obtener el contenido de la página para evitar un bucle infinito, por @haosenwang1018 y @D4Vinci en [#197](https://github.com/D4Vinci/Scrapling/pull/197)+- Sustituido el `raise` sin argumento por `return False` en `_restore_from_checkpoint`, por @haosenwang1018 en [#196](https://github.com/D4Vinci/Scrapling/pull/196)+- Sustituido `get_all` por `getall` en `Texthandler` para coincidir con la clase Selector.++### Mejoras de las pruebas y su cobertura {#v0.4.3-coverage-tests-improvement}+- Añadidas pruebas de casos límite de `_normalize_credentials`, por @Bortlesboat en [#192](https://github.com/D4Vinci/Scrapling/pull/192)+- Añadidas pruebas del ciclo de guardado y recuperación y del almacenamiento principal, por @haosenwang1018 en [#193](https://github.com/D4Vinci/Scrapling/pull/193)+- Añadida cobertura de las rutas de regex de `TextHandler` y de `TextHandlers.re()`, por @haosenwang1018 en [#194](https://github.com/D4Vinci/Scrapling/pull/194)+- Añadidas pruebas de casos límite de `filter`, `iterancestors` y `find_similar`, por @awanawana en [#200](https://github.com/D4Vinci/Scrapling/pull/200)++### Mejoras de la habilidad para agentes {#v0.4.3-agent-skill-improvement}+- Corregidos enlaces Markdown rotos en las referencias de la habilidad, por @yetval en [#204](https://github.com/D4Vinci/Scrapling/pull/204)+- Mejorada la estructura de la habilidad para superar mejor la validación de [Clawhub](https://clawhub.ai/d4vinci/scrapling-official).+- La habilidad ahora exige usar la opción de línea de comandos `--ai-targeted` al extraer datos mediante comandos.++### Mejoras de la documentación {#v0.4.3-docs-improvement}+- Añadida una traducción del README al coreano, por @greatsk55 en [#187](https://github.com/D4Vinci/Scrapling/pull/187)+- Corregidos los espacios entre caracteres CJK y latinos en los README chino y japonés.+- Corregidos enlaces rotos del diseño anterior del sitio.++## [v0.4.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.2) - 2026-03-08 {#v0.4.2}++**Una nueva actualización de mantenimiento con cambios importantes**++#### Correcciones de errores {#v0.4.2-bug-fixes}+- La función `get_all_text()` ahora recoge también los nodos de texto que siguen a los elementos. Así, el servidor MCP y los comandos pueden leer texto que antes se perdía ([#168](https://github.com/D4Vinci/Scrapling/pull/168)). Gracias, @mhillebrand+- Referer ahora devuelve la URL base de Google en lugar de una URL de búsqueda de Google. La lógica anterior era incorrecta y podía generar una señal que facilitara detectar la huella del navegador ([#179](https://github.com/D4Vinci/Scrapling/pull/179)). Gracias, @Bortlesboat+- Se corrigió un problema al unir las opciones de inicio adicionales en todos los navegadores. Gracias, @rostchri+- Se corrigió un problema con las anotaciones de tipos que causaba fallos en versiones de Python anteriores a 3.12. (Resuelve [#163](https://github.com/D4Vinci/Scrapling/issues/163))++#### Otros cambios {#v0.4.2-other}+- Se añadió una habilidad para agentes para Claude Code / OpenClaw y otras herramientas de agentes de IA.+- Se añadió la habilidad para agentes a Clawhub.+- Se actualizaron todos los navegadores y Playwright a sus últimas versiones.+- Se añadió una traducción al francés del archivo README principal.++## [v0.4.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.1) - 2026-02-27 {#v0.4.1}++**Una nueva actualización con muchos cambios importantes**++### 🚀 Novedades y mejoras de uso {#v0.4.1-new-stuff-and-quality-of-life-changes}+- **Mayor precisión de las expresiones regulares** para detectar desafíos de Cloudflare (Gracias a @Rinz27 [#133](https://github.com/D4Vinci/Scrapling/pull/133))+- **Mayor velocidad y eficiencia** al resolver desafíos de Cloudflare. Ahora es casi el doble de rápido.+- **Mejoras al resolver desafíos de Cloudflare** para los casos en que un sitio muestra la página de Cloudflare dos veces antes de redirigir al sitio principal.+- **Mejoras en el modo de sigilo y la velocidad del navegador sigiloso** al eliminar los archivos JS inyectados.+- **Mejoras en el esquema MCP** para que OpenCode lo acepte (Gracias a @robin-ede [#137](https://github.com/D4Vinci/Scrapling/pull/137))+- **Mayor compatibilidad del esquema MCP con el protocolo** para que VS Code Copilot y otras herramientas estrictas lo acepten. (Resuelve #150 )+- **Gran reducción del consumo de tokens del servidor MCP** al eliminar etiquetas HTML innecesarias cuando la opción `main_content_only` está activada.+- Se corrigió la página de PyPI y se añadieron los archivos necesarios para registrar el servidor MCP en el registro de servidores MCP.+- Se añadió un ejemplo de código que muestra cómo instalar las dependencias de los navegadores desde código, en lugar de usar la línea de comandos, para facilitar la automatización.+- Se mejoraron todos los workflows usando las últimas versiones de las acciones (Gracias a @salmanmkc [#143](https://github.com/D4Vinci/Scrapling/pull/143)/[#144](https://github.com/D4Vinci/Scrapling/pull/144))++## [v0.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4) - 2026-02-15 {#v0.4}++**La mayor versión de Scrapling hasta la fecha: framework de spiders, rotación de proxies y grandes mejoras en el analizador**++Esta versión incorpora un framework de spiders y rastreo totalmente asíncrono, gestión inteligente de proxies y cambios importantes en la API que hacen Scrapling más potente y coherente. Lee con atención la sección de cambios incompatibles antes de actualizar.++### 🕷️ Framework de spiders {#v0.4-spider-framework}++Un nuevo framework de rastreo asíncrono basado en `anyio` para extraer datos de forma organizada y a gran escala:++```python+from scrapling.spiders import Spider, Response++class MySpider(Spider):+ name = "demo"+ start_urls = ["https://example.com/"]++ async def parse(self, response: Response):+ for item in response.css('.product'):+ yield {"title": item.css('h2::text').get()}++MySpider().start()+```++- **API de spiders similar a Scrapy**: Define spiders con `start_urls`, callbacks `parse` asíncronos, objetos `Request`/`Response` y una cola de prioridad.+- **Rastreo concurrente**: Límites de concurrencia, control de la frecuencia por dominio y pausas entre descargas configurables.+- **Compatibilidad con varias sesiones**: Una interfaz común para peticiones HTTP y navegadores sigilosos sin interfaz gráfica en un solo spider. Dirige las peticiones a distintas sesiones mediante su ID. Permite iniciar las sesiones solo cuando se necesitan.+- **Pausar y reanudar**: Guarda el estado del rastreo mediante puntos de guardado. Pulsa Ctrl+C para cerrar de forma ordenada y vuelve a iniciar para continuar donde lo dejaste.+- **Modo streaming**: Recibe los datos extraídos en cuanto llegan mediante `async for item in spider.stream()`, con estadísticas en tiempo real. Ideal para interfaces, pipelines y rastreos largos.+- **Detección de peticiones bloqueadas**: Detecta y reintenta las peticiones bloqueadas de forma automática, con lógica personalizable.+- **Exportación integrada**: Exporta los resultados mediante hooks y tu propio pipeline, o usa la exportación integrada a JSON/JSONL con `result.items.to_json()` / `result.items.to_jsonl()`, respectivamente.+- **Hooks del ciclo de vida**: `on_start()`, `on_close()`, `on_error()`, `on_scraped_item()` y otros hooks para controlar todo el ciclo de vida del rastreo.+- **Estadísticas detalladas del rastreo**: Registra peticiones, respuestas, bytes, códigos de estado, proxies, detalles por dominio y sesión, recuentos por nivel de log y más.+- **Compatibilidad con uvloop**: Pasa `use_uvloop=True` a `spider.start()` para acelerar la ejecución asíncrona cuando esté disponible.++Se ha añadido una nueva sección al sitio web con todos los detalles. Haz clic [aquí](spiders/architecture.md)++### 🔄 Rotación de proxies {#v0.4-proxy-rotation}++* Nueva clase `ProxyRotator` con rotación segura entre hilos. Funciona con todos los fetchers y sesiones:++ ```python+ from scrapling import ProxyRotator+ rotator = ProxyRotator(["http://proxy1:8080", "http://proxy2:8080"])+ Fetcher.get(url, proxy_rotator=rotator)+ ```++* **Estrategias de rotación personalizadas**: Crea tu propia lógica de rotación de proxies+* **Cambio de proxy por petición**: Pasa `proxy=` a cualquier llamada individual a `get()`/`post()`/`fetch()` para reemplazar el proxy de la sesión en esa petición.++### 🌐 Mejoras en los fetchers de navegador {#v0.4-browser-fetcher-improvements}++* **Bloqueo de dominios**: Nuevo parámetro `blocked_domains` en `DynamicFetcher`/`StealthyFetcher` para bloquear peticiones a dominios concretos. Los subdominios se incluyen automáticamente.+* **Reintentos automáticos**: Los fetchers de navegador ahora reintentan las peticiones que fallan mediante los parámetros `retries` (valor predeterminado: 3) y `retry_delay` (valor predeterminado: 1s). Incluye detección de errores relacionados con proxies.+* **Metadatos de la respuesta**: El diccionario `Response.meta` guarda automáticamente el proxy usado e incorpora los metadatos de la petición.+* **Response.follow()**: Crea objetos `Request` para peticiones posteriores con gestión automática del referer, diseñados para el sistema de spiders.+* **Sin reproducción automática**: Las sesiones de navegador ahora bloquean el contenido con reproducción automática, que antes causaba problemas.+* **Velocidad**: Mejoras en el sigilo y la velocidad al ajustar las opciones de inicio del navegador.++### 🔧 Correcciones de errores y mejoras {#v0.4-bug-fixes-improvements}+- **Optimización del analizador**: Se optimizó el analizador para operaciones repetidas, mejorando su rendimiento.+- **Páginas con errores**: Se corrigió un error que impedía cerrar el navegador cuando las páginas daban errores.+- **Cuerpo vacío**: Se gestionan las respuestas con el cuerpo vacío.+- **Bucle de Playwright**: Se resolvió un problema que dejaba abierto el bucle de Playwright cuando fallaba la conexión CDP+- **Seguridad de tipos**: Se corrigieron todos los errores de mypy y se añadieron anotaciones de tipos en los cuerpos de funciones que no las tenían. Se añadieron mypy y pyright al workflow de CI.++### ⚠️ Cambios incompatibles {#v0.4-breaking-changes}++* **Se eliminaron `css_first`/`xpath_first`**: Usa `css('.selector').first`, `css('.selector')[0]` o `css('.selector').get()` en su lugar.+* **Todas las selecciones devuelven ahora `Selectors`**: `css('::text')`, `xpath('//text()')`, `css('::attr(href)')` y `xpath('//@href')` ahora devuelven `Selectors`, que envuelve los nodos de texto en objetos `Selector` con `tag="#text"`, en lugar de `TextHandlers`. Esto hace que la API sea coherente entre los métodos de selección y las anotaciones de tipos.+* **`Response.body` siempre es `bytes`**: Antes podía ser `str` o `bytes`; ahora siempre devuelve `bytes`.+* **Comportamiento de `get()`/`getall()`**: En `Selector`, `get()` devuelve `TextHandler` (HTML serializado o un valor de texto) y `getall()` devuelve `TextHandlers`. Alias: `extract_first = get`, `extract = getall`. Se eliminó el antiguo `get_all()` de `Selectors`.+* **`Selectors.first`/`.last`**: Propiedades de acceso seguras que devuelven `Selector | None` en lugar de lanzar `IndexError`.+* **Nuevos nombres para las constantes internas**: `DEFAULT_FLAGS` → `DEFAULT_ARGS`, `DEFAULT_STEALTH_FLAGS` → `STEALTH_ARGS`, `HARMFUL_DEFAULT_ARGS` → `HARMFUL_ARGS`, `DEFAULT_DISABLED_RESOURCES` → `EXTRA_RESOURCES`.++### 🔨 Otros cambios {#v0.4-other-changes}++* **Cambios en las dependencias**: Se reemplazó `tldextract` por `tld`, se eliminó el archivo interno `_html_utils.py` para usar `w3lib.html.replace_entities` y se añadió `typing_extensions` como requisito obligatorio.+* **Renovación de la documentación**: Migración completa de MkDocs a Zensical, nueva sección sobre spiders, actualización de todas las páginas existentes y nuevas referencias de la API.++## [v0.3.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.14) - 2026-01-03 {#v0.3.14}++**Una pequeña actualización de mantenimiento para corregir problemas que aparecieron en algunos equipos con v0.3.13**++- Se desactivó el modo incógnito en `StealthyFetcher` y sus clases de sesión, porque impedía conservar las cookies entre páginas en equipos Windows. Esto no ocurría en MacOS ni Linux (Corrige [#123](https://github.com/D4Vinci/Scrapling/issues/123); gracias a @frugality4121 por avisar y a @gembleman por señalar la solución).+- Se fijó la última versión de browserforge para resolver el problema con los modelos de cabeceras antiguos en instalaciones que ya tenían una versión antigua de browserforge.++## [v0.3.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.13) - 2026-01-01 {#v0.3.13}++**Una gran actualización con mejoras en muchas partes, pero también con numerosos cambios incompatibles por buenas razones. Lee lo siguiente antes de actualizar**++* Por varios motivos, hemos decidido dejar de usar Camoufox por completo a partir de ahora. Puede que volvamos a usarlo en el futuro si su desarrollo continúa. Si prefieres seguir usando Camoufox como antes de esta versión, encontrarás instrucciones en esta [sección](https://github.com/D4Vinci/Scrapling/blob/v0.3.13/docs/fetching/stealthy.md#using-camoufox-as-an-engine).++* Antes usábamos patchright en el modo de sigilo de `DynamicFetcher` y sus clases de sesión. Ahora hemos eliminado ese modo de estas clases y hemos empezado a usar patchright en `StealthyFetcher` y sus clases de sesión, con MUCHAS mejoras, como verás, que aumentan el sigilo sobre lo que ya ofrece patchright.++**Esto hace que `StealthyFetcher` y sus clases de sesión sean un 101% más rápidos, usen menos memoria y espacio y tengan unas ~400 líneas de código menos. Pero, sobre todo, son más estables que cuando usábamos Camoufox.**++Esto también reduce el tiempo de instalación del comando `scrapling install` y el tamaño de la imagen Docker, mejora la ejecución de las pruebas en el CI de GitHub y hace que scrapling resulte menos confuso para los nuevos usuarios.++### Cambios incompatibles {#v0.3.13-breaking-changes}+1. Se eliminó el argumento `stealth` de `DynamicFetcher` y su clase de sesión, mientras que el argumento `hide_canvas` pasó a `StealthyFetcher` y sus clases de sesión.+2. El argumento `disable_webgl` pasó de `DynamicFetcher` a la clase `StealthyFetcher` y se renombró como `allow_webgl`. Lo mismo ocurre en todas las clases de sesión.+3. La clase `StealthyFetcher` es ahora, en esencia, la nueva versión sigilosa de `DynamicFetcher`, así que se eliminaron los argumentos `block_images`, `humanize`, `addons`, `os_randomize`, `disable_ads` y `geoip`. Intenté reproducirlos en Chromium, pero cada uno tenía su propio problema. Esto podría cambiar en las próximas versiones anteriores a v0.4.++Ahora, las buenas noticias: hemos mejorado y corregido muchas cosas :)++### Mejoras {#v0.3.13-improvements}+- Ya sabes que `StealthyFetcher` y sus clases de sesión son ahora un 101% más rápidos, pero `DynamicFetcher` y su clase de sesión también son un 20% más rápidos.+- Se mejoró el algoritmo que resuelve los desafíos de Cloudflare para que termine antes y cubra más casos. Además, gracias a la reorganización del código, ¡puedes esperar que resuelva los captcha el doble de rápido!+- Todos los fetchers usan ahora menos memoria.+- ¡El servidor MCP usa menos tokens para ahorrar más dinero!+- La imagen Docker es ahora un 60% más pequeña.+- Se actualizó todo el sitio de documentación con las novedades. También se aclararon las explicaciones, se acortaron muchas secciones, se añadieron más ejemplos y argumentos que faltaban, se incorporaron gráficos a la referencia de la API y se hicieron muchas otras mejoras. El sitio ahora carga un 130% más rápido, consume menos datos y está mejor preparado para SEO.++### Correcciones {#v0.3.13-fixes}+- Se añadieron los argumentos que faltaban en los atajos de la consola de web scraping y se hicieron más precisos.+- Se corrigió un problema por el que el argumento `google_search` generaba un referer de Google incluso cuando la URL era localhost o una IP.++## [v0.3.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.12) - 2025-12-18 {#v0.3.12}++### Qué ha cambiado {#v0.3.12-what-s-changed}+- Se añadió a las clases `DynamicSession`/`AsyncDynamicSession` un argumento llamado `timezone_id`. Permite configurar la zona horaria del navegador para que coincida con la del proxy o VPN que usas. Así, los sitios no pueden detectar el proxy por una diferencia de zona horaria.+- Se mejoró la conversión automática de respuestas a JSON.+- Se cambió el nombre de la función interna `__create__` a `start` en las clases de sesión de los fetchers para facilitar su uso fuera del contexto `with`.+- Se actualizaron `curl_cffi` y otras dependencias a sus últimas versiones.++## [v0.3.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.11) - 2025-12-03 {#v0.3.11}++### Qué ha cambiado {#v0.3.11-what-s-changed}+- Se mejoró la lógica para gestionar errores de tiempo de espera cuando se usa `network_idle` en un sitio inestable, como uno con contenido multimedia en reproducción.+- Se corrigió el autocompletado del atajo `stealthy_fetch` en la consola de web scraping++## [v0.3.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.10) - 2025-11-26 {#v0.3.10}++**Una actualización de mantenimiento con muchos cambios importantes y posibles cambios incompatibles**++- **Se resolvieron** todos los problemas de codificación mediante un enfoque mejor que gestiona las páginas que no declaran correctamente su codificación (Gracias a @Kemsty2 por el esfuerzo de señalarlo en [#110](https://github.com/D4Vinci/Scrapling/issues/110) [#111](https://github.com/D4Vinci/Scrapling/pull/111) )+- **Se resolvió** un problema de lógica al reemplazar parámetros de sesión con parámetros de petición en todos los fetchers de navegador, presente desde v0.3+- **Se corrigieron** las firmas de los atajos de la consola interactiva de web scraping, logrando un autocompletado completo de esos atajos. Este problema también estaba presente desde v0.3.+- **Se actualizó** la versión de la base de datos Maxmind, lo que mejora el argumento `geoip` de `StealthyFetcher` y sus clases de sesión.+- **Se actualizaron** todos los navegadores usados a las últimas versiones disponibles.+- **CAMBIOS INCOMPATIBLES**: Todos los fetchers pasaron por una gran reorganización del código, que dio lugar a algunos cambios interesantes que podrían afectar a tu código:+ 1. El código de Scrapling tiene ahora unas ~750 líneas menos e incluye muchos cambios que facilitan el mantenimiento futuro y reducen un poco el uso de recursos.+ 2. La validación de todos los fetchers y sus clases de sesión es mucho más rápida, lo que mejora su velocidad general.+ 3. Para lograrlo, los fetchers ya no aceptan argumentos posicionales aparte de `url`. El resto debe pasarse por nombre, así que tu código debe usar `Fetcher.get('https://google.com', stealthy_headers=True)` y no `Fetcher.get('https://google.com', True)`, ¡si lo hacías así por algún motivo!+ 4. Desde v0.3 existía una diferencia molesta entre los fetchers de navegador y sus clases de sesión: el argumento para pasar ajustes del analizador por petición se llamaba `custom_config`, pero en las clases de sesión se llamaba `selector_config`. Esta reorganización permitió unificar el nombre como `selector_config` sin romper tu código. Ahora el nombre principal es `selector_config`, con compatibilidad para el antiguo argumento `custom_config`. El autocompletado solo estará disponible para `selector_config`.+ 5. Además, para lograr todo esto, las anotaciones de tipos de las funciones de los fetchers ahora se generan de forma dinámica. Si el autocompletado de tu IDE no funciona bien, asegúrate de usar una versión reciente. Hemos probado casi todos los IDE y editores conocidos.++> También hemos actualizado todas las tablas de rendimiento con los datos actuales frente a las últimas versiones de todas las bibliotecas alternativas.++## [v0.3.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.9) - 2025-11-17 {#v0.3.9}++**Una nueva actualización con muchos cambios importantes**++### 🚀 Novedades y mejoras de uso {#v0.3.9-new-stuff-and-quality-of-life-changes}+- El argumento `impersonate` de `Fetcher` y `FetcherSession` ahora acepta una lista de navegadores. La biblioteca elige uno al azar para cada petición.++```python+from scrapling.fetchers import FetcherSession++with FetcherSession(impersonate=['chrome', 'firefox', 'safari']) as s:+ s.get('https://github.com/D4Vinci/Scrapling')+```++- Un nuevo argumento en el método `clean` de `TextHandler` permite eliminar fácilmente las entidades HTML del texto actual.+- Grandes mejoras en la documentación, con explicaciones más precisas de muchas partes y traducciones automáticas del archivo `README.md` principal.++### 🐛 Correcciones de errores {#v0.3.9-bug-fixes}+- Se corrigió un problema importante al obtener respuestas de los fetchers de navegador. Ahora se detecta de forma inteligente el tipo de contenido para que `response.body` solo contenga el contenido renderizado del navegador cuando sea HTML. En los demás casos, contiene el contenido sin procesar de la última petición. Esto permite descargar archivos binarios y de texto sin que aparezcan envueltos en etiquetas HTML, y seguir obteniendo el contenido renderizado del sitio cuando lo necesitas.++### 🔨 Otros cambios {#v0.3.9-misc}+- Se actualizó la guía de contribución para hacerla más clara y sencilla.+- Se añadió un workflow para exigir el uso de las herramientas de calidad de código, las mismas que se usan como hooks de pre-commit.++## [v0.3.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.8) - 2025-10-27 {#v0.3.8}++**Una nueva actualización con muchos cambios importantes**++### 🚀 Novedades y mejoras de uso {#v0.3.8-new-stuff-and-quality-of-life-changes}+- En todos los fetchers de navegador, los sitios cuyas peticiones nunca terminan de cargar ya no hacen fallar el código cuando usas `network_idle`.+- Se cambió la lógica para recoger y comprobar el contenido de las páginas en los fetchers de navegador, para que los navegadores sean tan estables en Windows como en Linux/MacOS. Esta diferencia de comportamiento se debe a la implementación de Playwright en Windows.+- Se reorganizó toda la lógica de validación, lo que aceleró las peticiones de todos los fetchers de navegador entre un 8-15%+- Se añadió la opción `extra_flags` a `DynamicFetcher` y su sesión para agregar opciones de Chrome personalizadas a las existentes al iniciar el navegador.+- Se restauró la lógica anterior de rutas para capturar respuestas cuando se usa `page_action`, que había cambiado en la última versión. Esto permite recoger el contenido más reciente de la página si `page_action` lo cambia sin hacer una petición. (Gracias a @gembleman por señalarlo en [#100](https://github.com/D4Vinci/Scrapling/issues/100) y [#102](https://github.com/D4Vinci/Scrapling/pull/102) )++### 🐛 Correcciones de errores {#v0.3.8-bug-fixes}+- Se corrigió un error de escritura en `load_dom` dentro de async_fetch de DynamicSession+- Se corrigió un problema al resolver desafíos de Cloudflare que hacía esperar indefinidamente a que desaparecieran los captcha incrustados que permanecen visibles tras resolverse. Ahora se espera 30 segundos y, después, se asume que es un captcha de ese tipo (Corrige #100 )++### 🔨 Otros cambios {#v0.3.8-misc}+- La imagen Docker se publica ahora de forma automática en Dockerhub y en el registro de contenedores de GitHub para facilitar su uso.+- Se añadió una [nueva página de documentación](https://github.com/D4Vinci/Scrapling/blob/v0.3.8/docs/tutorials/external.md) que explica cómo usar el navegador Scrapeless con Scrapling.++## [v0.3.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.7) - 2025-10-12 {#v0.3.7}++**Una nueva actualización con muchos cambios importantes**++### 🚀 Novedades y mejoras de uso {#v0.3.7-new-stuff-and-quality-of-life-changes}+- Se rediseñó el argumento `solve_cloudflare` de `StealthyFetcher` para resolver todo tipo de implementaciones personalizadas de Turnstile.+- Se reorganizó todo el código para que pase las comprobaciones de Pyright, mejorando el uso de todos los IDE y corrigiendo muchos errores.+- Se reorganizó la lógica de las peticiones para hacerla más clara y rápida (También resuelve #97 )+- Se añadió la opción `user_data_dir` a todas las clases de sesión de navegador para reutilizar los datos del navegador de sesiones anteriores, como cookies y almacenamiento. Si no la indicas, Playwright usa un directorio aleatorio en cada ejecución, como hacía antes.+- Se añadió la opción de personalización `additional_args` a `Dynamic fetcher` y su clase de sesión para pasar argumentos adicionales al contexto de Playwright, como ya se podía hacer con `StealthyFetcher`.+- Se mejoró la lógica de rutas que recoge la última respuesta de navegación de todos los navegadores. Esto permite pasar las respuestas sin procesar al analizador, en lugar de hacerlo después de que las procese el navegador como antes. Resulta muy útil para respuestas de texto y JSON.++### 🐛 Correcciones de errores {#v0.3.7-bug-fixes}+- La nueva lógica de rutas resolvió un problema al obtener el contenido de sitios inestables en algunos equipos Windows.+- Las reorganizaciones del código de esta versión corrigieron muchos errores difíciles de detectar y problemas extraños de autocompletado en algunos IDE.+- Muchas correcciones en el sitio de documentación++## [v0.3.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.6) - 2025-10-01 {#v0.3.6}++### 🚀 Novedades {#v0.3.6-new-stuff}+- Se mejoró el argumento `solve_cloudflare` de `StealthyFetcher` y sus clases de sesión para resolver todos los tipos de desafíos Turnstile y de páginas intermedias de Cloudflare 🎉+- El servidor MCP ahora permite usar `Streamable HTTP` para ofrecer acceso al servidor fácilmente.+- Se añadió compatibilidad con Docker. Ahora se crea y publica una imagen en Docker Hub de forma automática con cada versión, que incluye todos los navegadores++### 🐛 Correcciones de errores {#v0.3.6-bug-fixes}+- Se corrigió un problema de codificación del analizador que ocurría en algunos casos, el conocido error `invalid start byte`+- Se reorganizaron varias partes de la biblioteca para corregir fugas de memoria. Ahora consume notablemente menos memoria según tu configuración (También resuelve #92 )+- Se mejoraron las anotaciones de tipos en muchas partes del código para facilitar el trabajo en el IDE (También resuelve #93 )++## [v0.3.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.5) - 2025-09-20 {#v0.3.5}++**Una versión necesaria que corrige varios problemas**++### 🚀 Novedades {#v0.3.5-new-stuff}+- Todos los fetchers de navegador (`DynamicFetcher`/`StealthyFetcher`/...) y sus clases de sesión obtienen ahora las páginas un 15-20% más rápido:+ 1. La gestión de páginas es mucho más rápida gracias a la mejora de lógica de @AbdullahY36 en #87+ 2. Se optimizó la lógica de validación general y se mejoró la creación de páginas para las peticiones síncronas. Juntos, estos cambios aportaron grandes mejoras de velocidad++- Grandes mejoras en el modo de sigilo de `DynamicFetcher` y sus clases de sesión al reemplazar `rebrowser-playwright` por `PatchRight`:+ 1. Antes de esta actualización, `rebrowser-playwright` se desactivaba al activar `stealth` y `real_chrome`, porque no funcionaban bien juntos. Con `PatchRight` ya no existe este problema+ 2. Ahora puedes interactuar con los Shadow Roots cerrados, porque `PatchRight` los gestiona automáticamente.++### 🐛 Correcciones de errores {#v0.3.5-bug-fixes}+- Se corrigió un error al usar el método `re` de la clase `Selectors`.+- Se corrigió un error de los comandos `uncurl` y `curl2fetcher` en la consola de web scraping que hacía interpretar mal la opción `--data-raw` de curl.+- Se corrigió un error del comando `view` en la consola de web scraping que aparecía según la codificación del sitio.+- Se corrigió un error de conversión de contenido que afectaba al modo `mcp` y a los comandos `extract`.++### Nuevos colaboradores {#v0.3.5-new-contributors}+- @AbdullahY36 hizo su primera contribución en #87++## [v0.3.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.4) - 2025-09-16 {#v0.3.4}++**Una versión necesaria que corrige varios problemas**++### 🚀 Novedades {#v0.3.4-new-stuff}+- Se añadieron todas las clases de sesión de los fetchers a la consola interactiva para poder usarlas directamente, sin importarlas.++### 🐛 Correcciones de errores {#v0.3.4-bug-fixes}+- Se añadió una solución alternativa para un error de la API de Playwright en Windows al obtener contenido mientras se resolvían desafíos de Cloudflare.+- Se corrigió un problema de codificación del comando `view` en la consola interactiva+- Se corrigió un error del argumento `max_pages` en `AsyncStealthySession` que hacía fallar el código.+- Se corrigió un problema de las últimas actualizaciones que hacía que las propiedades `html_content` y `prettify` de `Selector` devolvieran bytes según la codificación. Ambas vuelven a devolver cadenas de texto.++## [v0.3.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.3) - 2025-09-15 {#v0.3.3}++- Se eliminó la lógica que cerraba la pestaña predeterminada del navegador en los fetchers de navegador, porque causaba un fallo. No ocurría en Mac; solo se pudo reproducir en Windows y Linux++## [v0.3.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.2) - 2025-09-15 {#v0.3.2}++Notas de la versión v0.3.2++### 🚀 Novedades {#v0.3.2-new-stuff}++- **Dependencias opcionales de los fetchers**: Todos los fetchers forman ahora parte de grupos de dependencias opcionales, lo que reduce el tamaño del paquete base. El módulo base `scrapling` contiene solo el analizador. Para usar los fetchers o las opciones de línea de comandos, ejecuta `pip install "scrapling[fetchers]"`. Consulta las instrucciones detalladas de instalación [aquí](index.md#installation)+- **Configuración por página en las sesiones**: Las clases de sesión de los fetchers de navegador permiten configurar cada página por separado. Todos los parámetros de las peticiones se validan ahora como los de las sesiones. Tienes más detalles en el sitio de documentación [aquí](fetching/stealthy.md#full-list-of-arguments)+ <br>Ejemplo:++ ```python+ with StealthySession(headless=True, solve_cloudflare=True) as session:+ page = session.fetch('https://nopecha.com/demo/cloudflare', google_search=False)+ ```++- **Mejoras en los fetchers de navegador**+ - Una nueva opción permite elegir si se debe esperar a que termine la ejecución de JavaScript en las páginas. Está activada de forma predeterminada, como antes++ ```python+ with DynamicSession(headless=True, disable_resources=False, network_idle=True) as session:+ page = session.fetch('https://quotes.toscrape.com/', load_dom=False)+ ```++ - El modo de sigilo es ahora más fiable en `DynamicFetcher` y sus clases de sesión.+ - `DynamicFetcher` y `StealthyFetcher` usan ahora menos recursos, al encontrar y cerrar automáticamente la pestaña predeterminada que abren los contextos persistentes de la API de Playwright+ - Se corrigió un error importante de lógica en la rotación de páginas de los fetchers de navegador. Las páginas anteriores ahora se reemplazan por otras nuevas, ya que las pestañas reutilizadas podían conservar ajustes de usos anteriores+ - `StealthyFetcher` y sus clases de sesión son ahora un poco más rápidos (5%)++- **Mejoras en la propiedad `.body`**: Ahora devuelve el contenido recibido tal cual, sin procesarlo, lo que permite descargar archivos y gestionar peticiones que no devuelven HTML. Este ejemplo muestra cómo descargar una imagen:++ ```python+ from scrapling.fetchers import Fetcher++ page = Fetcher.get('https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/poster.png')+ with open(file='poster.png', mode='wb') as f:+ f.write(page.body)+ ```++### 🐛 Correcciones de errores {#v0.3.2-bug-fixes}++- **Problemas de codificación resueltos**: Se corrigieron varios problemas de codificación con algunos sitios en el analizador, el modo mcp y los comandos extract (También resuelve #80 y #81)+- **Análisis más rápido**: Gracias a muchos cambios en distintas partes, la biblioteca es ahora más rápida, como muestran las pruebas de rendimiento actualizadas++### 🔨 Otros cambios {#v0.3.2-misc}++- **Pruebas de rendimiento actualizadas**: Se actualizaron las mediciones para comparar las mejoras de velocidad actuales con las últimas versiones de bibliotecas similares+- **Se reorganizó gran parte del código y se reemplazó el código sin uso por mejores implementaciones**: Menos código, más claro y más fácil de mantener+- **Nuevo vídeo de YouTube**: Se añadió contenido en vídeo a la documentación de MCP.+- **Nueva plantilla de incidencias**: Una plantilla sencilla para quienes no pueden usar las actuales.+- **Optimización del workflow de CI**: El workflow de pruebas ya no se ejecuta cuando solo cambia la documentación u otros archivos que no son código.+- **Dependencias actualizadas**: Se actualizaron varias dependencias a sus últimas versiones.+- **Mejoras en el estilo de código**: Se aplicaron nuevas reglas de ruff en todos los archivos.+- **Hooks de pre-commit**: Se actualizó la configuración de pre-commit.++### 🎯 Cambios incompatibles {#v0.3.2-breaking-changes}++- Se eliminó el parámetro `max_pages` de la versión síncrona de `StealthySession` para igualarla a `DynamicSession`, porque no tiene sentido en la versión síncrona++## [v0.3.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.1) - 2025-09-02 {#v0.3.1}++1. Se corrigió un problema al instalar scrapling sin el extra `shell` (#76 )+2. Se añadió un argumento a todos los fetchers de navegador y sus clases de sesión para pasar un archivo JS que se ejecuta al crear la página (#56) :++```python+from scrapling.fetchers import StealthyFetcher++StealthyFetcher.fetch('https://example.com', init_script="/absolute/path/to/js/script.js")+```++## [v0.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3) - 2025-09-01 {#v0.3}++🎉 **Versión principal - Renovación completa de la arquitectura**++Scrapling v0.3 es la mayor actualización en la historia del proyecto. Incluye una reescritura completa de la arquitectura, mejoras importantes de rendimiento y nuevas funciones potentes, como la integración con IA y una consola interactiva de web scraping.++Esta versión incluye varios cambios incompatibles. Lee las notas de la versión con atención.++### 🚀 Principales novedades {#v0.3-major-new-features}++#### Arquitectura basada en sesiones {#v0.3-session-based-architecture}+- **Nuevas clases de sesión**: Reescritura completa que añade soporte para sesiones persistentes+ - `FetcherSession` - Peticiones HTTP con gestión de estado persistente, tanto para código síncrono como asíncrono+ - `DynamicSession`/`AsyncDynamicSession` - Automatización del navegador, que permanece abierto hasta que termines+ - `StealthySession`/`AsyncStealthySession` - Navegación sigilosa, con el navegador abierto hasta que termines+- **Gestión asíncrona de pestañas del navegador**: Nuevo grupo de pestañas mediante el argumento `max_pages`, que alterna entre ellas para hacer peticiones concurrentes con el navegador+- **Sesiones concurrentes**: Ejecuta varias sesiones aisladas al mismo tiempo++Consulta la sección `Fetching` del sitio web para más detalles.++#### Muchas funciones nuevas de sigilo y evasión de sistemas antibots {#v0.3-a-lot-of-new-stealth-anti-bot-capabilities}+- **🤖 Resolución de Cloudflare**: [Resolución automática de desafíos de Cloudflare Turnstile](fetching/stealthy.md#cloudflare-and-stealth-options) en `StealthyFetcher` y sus clases de sesión+- **Imitación de huellas del navegador**: Imita las huellas TLS de navegadores reales, usa cabeceras que coincidan con su versión y aprovecha el soporte para HTTP/3 y otras funciones con la nueva clase [Fetcher](fetching/static.md)+- **Modo sigiloso mejorado**: El modo sigiloso de `DynamicFetcher` y sus clases de sesión ahora es más sólido y fiable (también conocido como `PlayWrightFetcher`)++#### Integración con IA y servidor MCP {#v0.3-ai-integration-mcp-server}+- **Servidor MCP integrado**: Servidor Model Context Protocol para web scraping asistido por IA+- **6 herramientas potentes**: `get`, `bulk_get`, `fetch`, `bulk_fetch`, `stealthy_fetch`, `bulk_stealthy_fetch`+- **Extracción inteligente de contenido**: Convierte páginas o elementos web a Markdown o HTML, o extrae una versión limpia del texto+- **Soporte para selectores CSS**: Usa el motor de Scrapling para seleccionar elementos concretos con precisión antes de enviar el contenido a la IA+- **Evasión de sistemas antibots**: Gestiona Cloudflare Turnstile y otras protecciones+- **Soporte para proxies**: Usa proxies para mantener el anonimato y elegir la ubicación geográfica+- **Imitación de navegadores**: Imita navegadores reales con huellas TLS, cabeceras reales que coincidan con su versión y más+- **Procesamiento en paralelo**: Extrae datos de varias URL al mismo tiempo para ganar eficiencia+- [y más...](ai/mcp-server.md)++#### Nueva consola interactiva de web scraping {#v0.3-new-interactive-web-scraping-shell}+- **Nueva consola**: Consola IPython personalizada con muchos atajos inteligentes integrados, como `get`, `post`, `put`, `delete`, `fetch` y `stealthy_fetch`+- **Gestión inteligente de páginas**: Nuevos comandos `page` y `pages` para guardar automáticamente la página actual y el historial de todas las peticiones hechas desde la consola+- **Integración con Curl**: Usa las funciones `uncurl` y `curl2fetcher` para convertir comandos curl de las herramientas de desarrollo del navegador en peticiones de `Fetcher`+- [y más...](cli/interactive-shell.md)++#### Extrae datos desde la terminal sin programar {#v0.3-scrape-from-the-terminal-without-programming}+- **Nuevos comandos de extracción**: Extrae datos desde la terminal sin programar+ - `scrapling extract get/post/put/delete` - Peticiones HTTP sencillas+ - `scrapling extract fetch` - Extracción de contenido dinámico+ - `scrapling extract stealthy-fetch` - Evasión de sistemas antibots+- **Descarga páginas web** y guarda su contenido en archivos.+- **Convierte HTML a formatos legibles** como Markdown, lo conserva como HTML o extrae solo el texto de la página.+- **Admite selectores CSS personalizados** para extraer partes concretas de la página.+- **Gestiona peticiones HTTP y la obtención de páginas con navegadores.**+- **Muy configurable**, con cabeceras, cookies, proxies y otras opciones personalizadas. Casi todas las opciones disponibles en el código también están disponibles desde la terminal.+- [y más...](cli/extract-commands.md)++### 🔧 Mejoras técnicas {#v0.3-technical-improvements}++#### Mejoras de rendimiento {#v0.3-performance-enhancements}+- **Fetcher ahora es 4 veces más rápido** - ¡Sí, has leído bien!+- **DynamicFetcher ahora es ~60% más rápido** - Una versión mucho más rápida según tu configuración (sobre todo el modo sigiloso)+- **StealthyFetcher ahora es 20–30% más rápido** - Gracias a la nueva estructura y al uso de nuestra propia implementación en lugar de la interfaz Python de `Camoufox`+- **Mejora conjunta de velocidad de 50%+** en los métodos principales de selección (`find_by_text`, `find_similar`, `find_by_regex`, `relocate`, etc.) 🚀+- **Aumento de ~10% en la velocidad de los métodos que obtienen la primera coincidencia CSS/XPath** - `css_first` y `xpath_first` ahora son más rápidos que `css` y `xpath`+- **El método `get_all_text()` es 40% más rápido** al extraer contenido+- **Mejora de velocidad del 20%** al volver a localizar elementos de forma adaptativa+- **Optimización de las propiedades de navegación** - Propiedades como `next`, `previous`, `below_elements` y otras ahora son notablemente más rápidas+- **Limpieza de texto 5 veces más rápida**+- **Mejor uso de la memoria** con importaciones optimizadas y menos trabajo adicional+- **⚡ Importaciones muy rápidas**: Menor tiempo de inicio gracias a una carga de módulos optimizada+- **Mejores resultados en las pruebas de rendimiento**: Todas las mejoras de velocidad hacen que Scrapling sea mucho más rápido que antes frente a otras bibliotecas (1775 veces más rápido que BeautifulSoup y 5.1 veces más rápido que AutoScraper; consulta las [pruebas de rendimiento](benchmarks.md))++#### Arquitectura, calidad del código y mejoras de uso {#v0.3-architecture-code-quality-and-quality-of-life}+- **Contexto persistente**: Todos los fetchers basados en navegador usan ahora un contexto persistente por defecto. (También resuelve #64)+- **Uso de msgspec para validar muy rápido la configuración de todos los fetchers basados en navegador** antes de ejecutar las peticiones, lo que facilita detectar errores.+- **Todas las cookies** que devuelven los fetchers tienen ahora el formato que acepta ese mismo fetcher. Así puedes obtener cookies y volver a pasarlas a todos los fetchers y sus clases de sesión.+- **Análisis y formato de código más rápidos** tras migrar a `ruff`+- **Sistema de construcción moderno**: Migración de setup.py a pyproject.toml 📦+- **Mejores acciones y flujos de trabajo de GitHub** para facilitar el desarrollo y las pruebas+- **🎨 Mejores anotaciones de tipos**: Cobertura completa de tipos con estándares modernos de Python para mejorar el soporte del IDE y la fiabilidad+- **Código más limpio**: Eliminación de código sin uso y optimización de las funciones principales 🧹+- **🚀 Compatibilidad con versiones anteriores**: Nuevos atajos para mantener la compatibilidad con código antiguo++### Cambios incompatibles {#v0.3-breaking-changes}++#### Versión mínima de Python {#v0.3-minimum-python-version}+- **Se requiere Python 3.10+**: Se elimina el soporte para Python 3.9 y anteriores++#### Nombres de clases y métodos {#v0.3-class-and-method-naming}+Estos cambios de nombre buscan dar más claridad y coherencia, sobre todo para los usuarios nuevos.++- **`Adaptor` → `Selector`**: Se cambia el nombre de la clase principal de análisis (aún se puede importar como `Adaptor` para mantener la compatibilidad)+- **`Adaptors` → `Selectors`**: Se cambia el nombre de la clase de colección (aún se puede importar como `Adaptors` para mantener la compatibilidad)+- **`auto_match` → `adaptive`**: Se cambia el nombre del parámetro en todos los métodos+- **`adaptor_arguments` → `selector_config`**: Se cambia el nombre del parámetro de configuración+- **`automatch_domain` → `adaptive_domain`**: Se cambia el nombre del parámetro de dominio+- **`additional_arguments` → `additional_args`**: Se acorta el nombre del parámetro+- **⚠️ `text/body` → `content`**: El parámetro del constructor de Selector ahora acepta tanto `str` como `bytes`+- **`PlayWrightFetcher` → `DynamicFetcher`**: Se cambia el nombre de la clase de automatización del navegador (aún se puede importar como `PlayWrightFetcher` para mantener la compatibilidad)+- **DynamicFetcher ya no incluye la lógica ni los argumentos de NSTBrowser**, porque ya no tiene sentido mantenerlos.+- **El argumento headless de StealthyFetcher ya no acepta 'virtual'** porque ahora solo usamos la biblioteca Camoufox para obtener la ruta de instalación del navegador y las demás opciones de inicio++### 🐛 Correcciones de errores {#v0.3-bug-fixes}++- Se corrige el recuento de hijos anidados en etiquetas ignoradas por `get_all_text` (#61)+- Se corrige el problema de instalación causado por espacios en la ruta del ejecutable de Python (#57)+- Se resuelven problemas de hilos en el almacenamiento, con gestión de la recursión cuando la función adaptativa está activada+- Se corrigen problemas de prioridad de argumentos mediante el patrón Sentinel en `FetcherSession`+- Se corrige la gestión de tipos de proxy en `StealthyFetcher`+- Se corrigen conflictos entre los argumentos `referer` y `google_search`+- Se corrigen problemas al inyectar scripts de sigilo de forma asíncrona++## [v0.2.99](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.99) - 2025-04-08 {#v0.2.99}++**Esta es una actualización importante para que todos puedan disfrutar plenamente de Scrapling tal como se diseñó.**++### Qué ha cambiado {#v0.2.99-what-s-changed}+#### Nuevo sitio web con toda la documentación {#v0.2.99-new-full-documentation-website}+- Sí, por fin 😄 Puedes verlo [aquí](index.md)+#### Importación unificada de fetchers {#v0.2.99-unified-import-logic-for-fetchers}+- Ahora puedes importar todos los fetchers con `from scrapling.fetchers import Fetcher, AsyncFetcher, StealthyFetcher, PlayWrightFetcher` y usarlos directamente, como en `page = Fetcher.get(...)`, sin crear una instancia.<br/> Esto sustituye a la importación anterior `from scrapling.defaults import Fetcher, AsyncFetcher, StealthyFetcher, PlayWrightFetcher`.+#### Cambio incompatible: automatch ahora está desactivado por defecto {#v0.2.99-breaking-change-automatch-is-now-turned-off-by-default}+- Ahora hay una nueva forma de activar automatch desde los fetchers y las demás opciones de análisis. Consulta la [documentación](fetching/choosing.md#parser-configuration-in-all-fetchers) para más detalles.+> Las importaciones y la lógica anteriores siguen disponibles, con una advertencia, para mantener la compatibilidad.+#### Nuevas opciones para los fetchers {#v0.2.99-new-options-added-to-fetchers}+- Ahora `StealthyFetcher` y `PlayWrightFetcher` tienen un nuevo argumento llamado `wait` al obtener páginas. Hace que el fetcher espere un tiempo concreto en milisegundos antes de cerrar la página y devolver la respuesta.+- Los métodos de `StealthyFetcher` llamados `fetch` y `async_fetch` tienen ahora el argumento `additional_arguments` para pasar opciones adicionales a Camoufox. Estas tienen prioridad sobre la configuración de Scrapling (#54 )+#### Correcciones de errores {#v0.2.99-bugs-squashed}+- Se corrige un error al detectar redirecciones en `async_fetch` de las clases `StealthyFetcher` y `PlayWrightFetcher`.++**_¡Gracias por todo tu apoyo y tus donaciones!_**++## [v0.2.98](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.98) - 2025-03-17 {#v0.2.98}++**Esta es una actualización importante para que todos puedan disfrutar plenamente de Scrapling tal como se diseñó**++### Qué ha cambiado {#v0.2.98-what-s-changed}+#### Mejoras en el uso de memoria y la velocidad {#v0.2.98-various-memory-usage-and-speed-optimizations}+- El uso de memoria de todos los métodos de selección es ahora ~40% del anterior, con un pequeño aumento de velocidad.+- Se aplica la carga diferida a todos los submódulos de la biblioteca: ahora solo se carga lo que usas. Por ejemplo:+Antes de la actualización, la importación `from scrapling import Adaptor` usaba `30-40mb` de RAM porque también cargaba todos los fetchers y otros componentes. Ahora usa `~1.2mb`.+- La última actualización hizo que la biblioteca usara ~32% de la memoria que usaba antes con un grupo grande de peticiones. Ahora ajustamos más la caché para usar todavía menos.+- Pequeño aumento general de velocidad del analizador, de 2-5%++**_¡Gracias por todo tu apoyo y tus donaciones!_**++## [v0.2.97](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.97) - 2025-03-15 {#v0.2.97}++**Esta es una actualización importante para que todos puedan disfrutar plenamente de Scrapling tal como se diseñó**++### Qué ha cambiado {#v0.2.97-what-s-changed}+#### Menor uso de memoria y un pequeño aumento de velocidad en todos los fetchers {#v0.2.97-lower-memory-usage-and-small-speed-increase-across-all-fetchers}+- Los nuevos límites de tamaño de la caché en toda la biblioteca reducen mucho el uso de memoria al hacer grandes cantidades de peticiones u operaciones.+- Se reorganizan grandes partes de los fetchers para facilitar su mantenimiento y aumentar un poco la velocidad.++#### Correcciones de errores {#v0.2.97-bugs-fixed}+- Se corrige un error de `TextHandler` que convertía un valor no textual en una cadena vacía al importarlo por separado. Ahora cualquier valor que se pase a `TextHandler` se convierte primero en una cadena y luego en `TextHandler`. Esto se aplica a todos los valores: ¡`TextHandler`, como indica su nombre, está pensado para trabajar solo con texto! (#45 )+- Se corrige un error que hacía que la mayoría de los métodos de AsyncFetcher ignoraran el argumento `retries`.++#### Otros cambios {#v0.2.97-miscellaneous}+- Se actualizan las anotaciones de tipos de la mayoría de los argumentos en todos los fetchers para que sean más claras y precisas.++**_¡Gracias por todo tu apoyo y tus donaciones!_**++## [v0.2.96](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.96) - 2025-03-05 {#v0.2.96}++**Esta es una actualización importante para que todos puedan disfrutar plenamente de Scrapling tal como se diseñó**++### Qué ha cambiado {#v0.2.96-what-s-changed}+1. Se añade la opción `-f` a `scrapling install` para forzar la reinstalación de las dependencias del navegador. Te recomiendo ejecutar `scrapling install -f` ahora para aprovechar la gran mejora de velocidad de `StealthyFetcher` con la nueva versión del navegador Camoufox :)+2. Se corrige un error de `TextHandler` que devolvía `TextHandlers` en lugar de `TextHandler` al obtener una porción del texto, y se corrige su anotación de tipo (#41 )+3. Se corrige un problema que hacía que `scrapling install` abriera una consola Python en algunos casos.++## [v0.2.95](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.95) - 2025-02-25 {#v0.2.95}++**Esta es una actualización importante para que todos puedan disfrutar plenamente de Scrapling tal como se diseñó**++### Qué ha cambiado {#v0.2.95-what-s-changed}+1. Se corrige un error de `Fetcher` que hacía que las cabeceras generadas por el argumento `stealthy_headers` sobrescribieran algunas cabeceras del usuario, como `Accept` (#39 )+2. Se mejora un poco la lógica de generación de cabeceras, lo que debería aumentar ligeramente la velocidad.++## [v0.2.94](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.94) - 2025-02-22 {#v0.2.94}++**Esta es una actualización importante para que todos puedan disfrutar plenamente de Scrapling tal como se diseñó**++### Qué ha cambiado {#v0.2.94-what-s-changed}+1. Se añade la propiedad `history` a todos los fetchers para mostrar las redirecciones (#32 )+2. Se corrige la lógica del argumento `case_sensitive` en todos los métodos `re`/`re_first`. Si lo usabas, esto puede cambiar los resultados de tu código (aunque quizá te lo merezcas por haber visto que no funcionaba bien sin abrir una incidencia, jajaja)+3. Se actualizan las dependencias y se vuelve a activar `coop` en el motor Camoufox (StealthyFetcher).++## [v0.2.93](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.93) - 2025-01-31 {#v0.2.93}++**Esta es una actualización importante para que todos puedan disfrutar plenamente de Scrapling tal como se diseñó**++### Qué ha cambiado {#v0.2.93-what-s-changed}+1. El tipo de retorno es ahora coherente en todo el motor de análisis. Siempre recibirás uno de estos tipos: `Adaptor`, `Adaptors`, `TextHandler`, `TextHandlers`, `None`, o una lista si hay resultados mixtos, como con un selector CSS combinado. Esto facilita la programación con menos comprobaciones manuales de tipos, hace que la biblioteca sea más estable y permite encadenar métodos en todos los casos.+2. Se reorganiza la mayor parte del motor de análisis, sobre todo la clase `Adaptor`, para que sea más limpio y, lo más importante, más rápido. Casi todos los métodos y propiedades, sobre todo los de búsqueda, ganan entre 5-40% de velocidad. Algunos mejoran aún más, como `find_by_regex`, que gana ~60%. La función automatch gana alrededor de ~5%.+3. Se corrigen errores en la lógica de `find_all`/`find` que aplicaban los filtros con OR en unos casos y con AND en otros. Ahora todos los elementos devueltos deben cumplir todos los filtros que pases.+4. Todos los métodos relacionados con regex devuelven ahora `TextHandler`/`TextHandlers` para facilitar el encadenamiento de métodos.+5. **Se añade una nueva** propiedad `below_elements`, que devuelve un objeto `Adaptors` con todos los elementos situados bajo el elemento actual en el árbol DOM.+6. Todos los métodos y propiedades que devolvían código HTML como cadena ahora lo devuelven como `TextHandler`, para que puedas aplicar regex y otras operaciones con facilidad...+7. StealthyFetcher ahora es un poco más rápido y sigiloso. También permite pulsar CAPTCHA dentro de iframes, como **Cloudflare Turnstile**.+8. Se mejoran mucho el autocompletado y las anotaciones de tipos en casi la mitad de la biblioteca, sobre todo en `Adaptor`, `TextHandler` y `TextHandlers`.+9. Al obtener una porción de `TextHandler`, acceder por índice o usar el método `split`, ahora recibes otro `TextHandler` en lugar de una cadena estándar de Python. Casi todas las operaciones y métodos estándar de cadenas devuelven ahora otro `Texthandler` para que siempre puedas encadenar métodos y funciones.+10. Se corrigen algunos errores pequeños y erratas. Por ejemplo, async_put de Fetcher hacía una petición post en lugar de put 😶🌫️+11. Se mejora un poco el README mientras termino el sitio web de documentación.++Iba a ser una pequeña actualización antes de la versión 0.3, pero decidí mejorarla un poco más.++## [v0.2.92](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.92) - 2024-12-26 {#v0.2.92}++### Qué ha cambiado {#v0.2.92-what-s-changed}+- Las respuestas de los fetchers basados en navegador usan ahora fuentes de datos más fiables cuando la página cargada contiene muchos iframes.+- **¡Instalar `Scrapling` ahora es aún más fácil: instálalo con pip, ejecuta `scrapling install` en la terminal y listo!**+- Se corrige una anotación de tipo imprecisa en el analizador.++## [v0.2.91](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.91) - 2024-12-19 {#v0.2.91}++### Qué ha cambiado {#v0.2.91-what-s-changed}+- Se corrige un error que hacía que el mensaje de registro de obtención de páginas solo apareciera en la primera petición.+- Por defecto, la API de Playwright devuelve la primera respuesta que cumple el estado de carga indicado al método `goto`: `["load", "domcontentloaded", "networkidle"]`. Si un sitio tiene una página de espera, como la de Cloudflare, que luego te redirige al sitio real, Playwright devuelve el primer código de estado, que podría ser 403. Esta actualización resuelve el problema en `PlaywrightFetcher` y `StealthyFetcher`, ya que ambos usan la API de Playwright. El resultado ya no depende de ese comportamiento por defecto.+- Se añade soporte para proxies SOCKS en la clase `Fetcher`.+- Se corrige la anotación de tipo del argumento `wait_selector_state` para que el autocompletado muestre los valores correctos que puedes usar.++## [v0.2.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.9) - 2024-12-16 {#v0.2.9}++### Qué ha cambiado {#v0.2.9-what-s-changed}+##### Nuevas funciones {#v0.2.9-new-features}+1. ¡Llega el **tan esperado** soporte asíncrono para Scrapling! Ahora tienes `AsyncFetcher`, la versión asíncrona de `Fetcher`, y tanto `StealthyFetcher` como `PlayWrightFetcher` tienen un nuevo método llamado `async_fetch` con las mismas opciones.++```python+>> from scrapling import StealthyFetcher+>> page = await StealthyFetcher().async_fetch('https://www.browserscan.net/bot-detection') # the async version of fetch+>> page.status == 200+True+```++2. La clase `StealthyFetcher` tiene ahora el argumento `geoip` en sus métodos de obtención. Al activarlo, usa automáticamente la longitud, latitud, zona horaria, país y configuración regional de la IP, y modifica la dirección IP que expone WebRTC. También calcula y simula el idioma del navegador según la distribución de hablantes de cada idioma en la región de destino.+3. Se añade el argumento `retries` a las clases `Fetcher`/`AsyncFetcher` para que puedas fijar el número de reintentos de cada petición hecha con `httpx`.+4. Se añade el método `url_join` a `Adaptor` y a los fetchers. Recibe una URL relativa y la combina con la URL actual para crear una URL absoluta completa.+5. Se añade el método `keep_cdata` a `Adaptor` y a los fetchers para evitar que el analizador elimine cdata cuando necesites conservarlo.+6. En `Adaptor`/`Response`, el método `body` devuelve ahora la respuesta HTML original cuando es posible, sin procesarla en la biblioteca.+7. Se añade registro de eventos a la clase `Response`. Al usar los fetchers, ahora recibes un registro con información sobre la respuesta.+Ejemplo:++ ```python+ >> from scrapling.defaults import Fetcher+ >> Fetcher.get('https://books.toscrape.com/index.html')+ [2024-12-16 13:33:36] INFO: Fetched (200) <GET https://books.toscrape.com/index.html> (referer: https://www.google.com/search?q=toscrape)+ >>+ ```++8. Al usar métodos estándar de cadenas sobre un `TextHandler`, como `.replace()`, ahora recibes otro `TextHandler`. Antes devolvían una cadena estándar.+9. Grandes mejoras de velocidad en toda la biblioteca y mejoras de sigilo en las clases de fetchers en general.+10. Se añaden funciones de compatibilidad como `extract_first`\`extract` que devuelven el mismo resultado que el objeto original. Se incluyen solo para facilitar la copia de código de Scrapy/Parsel a Scrapling cuando haga falta, porque allí se usan estas funciones.+11. Las peticiones por lotes ahora son mucho más rápidas gracias a la reorganización de gran parte del código y al uso de caché en los lugares adecuados.++##### Cambios incompatibles {#v0.2.9-breaking-changes}+- Se elimina el soporte para Python 3.8. (Sobre todo porque Playwright dejó de admitirlo, aunque ya era una versión problemática)+- Se elimina el argumento `debug` de toda la biblioteca. Si quieres activar la depuración, haz esto después de importarla:++ ```python+ >>> import logging+ >>> logging.getLogger("scrapling").setLevel(logging.DEBUG)+ ```++##### Correcciones de errores {#v0.2.9-bugs-squashed}+1. WebGL ahora está activado por defecto porque muchas protecciones comprueban si está habilitado.+2. Se corrigen algunos errores y erratas en la documentación y el README.++##### Mejoras de uso {#v0.2.9-quality-of-life-changes}+1. Todos los registros usan ahora el logger llamado `scrapling` para facilitar su control. Antes usábamos el logger raíz.+2. Se reorganiza la carpeta de pruebas para que sea más clara y se añaden pruebas de las nuevas funciones. Se reescriben todas las pruebas de forma más limpia y se añaden más para aumentar la cobertura.+3. Se reorganiza gran parte del código para que sea más limpio y fácil de mantener.++> Todos estos cambios estaban previstos para la versión 0.3, pero decidí incluirlos aquí porque aún falta un tiempo para la siguiente versión. El próximo paso es terminar el sitio web de documentación detallada y luego trabajar en la versión 0.3++## [v0.2.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.8) - 2024-11-30 {#v0.2.8}++### Qué ha cambiado {#v0.2.8-what-s-changed}+- Pequeña actualización con mejoras de uso necesarias en el código y la corrección de una errata en el README principal (#20)++## [v0.2.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.7) - 2024-11-26 {#v0.2.7}++### Qué ha cambiado {#v0.2.7-what-s-changed}+##### Nuevas funciones {#v0.2.7-new-features}+- Si usas el argumento `wait_selector` con las clases `StealthyFetcher` y `PlayWrightFetcher`, Scrapling vuelve a esperar a que JS se cargue y se ejecute por completo, como de costumbre. Si usas `network_idle`, también vuelve a esperar ese estado después. Si todos los estados ya se cumplen, no espera.+- Ahora puedes activar y desactivar los anuncios en `StealthyFetcher` con el argumento `disable_ads`. El bloqueo está activado por defecto e instala la extensión `ublock origin`.+- Ahora puedes definir la configuración regional de `PlayWrightFetcher` con el argumento `locale`. El valor por defecto sigue siendo `en-US`.+- Las peticiones básicas hechas con `Fetcher` ahora aceptan proxies con el formato `http://username:password@localhost:8030`.+- Se mejora un poco el modo sigiloso de `PlayWrightFetcher`.++##### Correcciones de errores y mejoras {#v0.2.7-bugs-squashed-improvements}+1. Activar proxies en la clase `PlayWrightFetcher` ya no depende de si el modo `stealth` está activado o no (gracias a [@AbdullahY36](https://github.com/AbdullahY36) por avisar)+2. Ahora `ResponseEncoding` comprueba si la codificación indicada en la respuesta sirve para la página. Si esa codificación provoca un error, Scrapling usa `utf-8` por defecto++## [v0.2.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.6) - 2024-11-24 {#v0.2.6}++### Qué ha cambiado {#v0.2.6-what-s-changed}+##### Nuevas funciones {#v0.2.6-new-features}+- Ahora `PlayWrightFetcher` puede usar directamente el navegador real si pasas `real_chrome` a la función `PlayWrightFetcher.fetch`, pero necesitas tener Chrome instalado. Scrapling inicia una instancia de tu navegador Chrome y puedes usar la mayoría de las opciones como siempre. (Antes solo tenías el argumento `cdp_url` para hacerlo)+- Se actualiza la versión que reflejan las cabeceras generadas para navegadores reales.++##### Correcciones de errores {#v0.2.6-bugs-squashed}+1. El formato de las cabeceras de navegador generadas por `BrowserForge` estaba desactualizado, lo que permitía que algunas protecciones detectaran Scrapling. Ahora `BrowserForge` solo se usa para generar un useragent real.+2. El argumento `hide_canvas` ahora está desactivado por defecto porque ReCaptcha de Google lo detecta.++## [v0.2.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.5) - 2024-11-23 {#v0.2.5}++### Qué ha cambiado {#v0.2.5-what-s-changed}++##### Correcciones de errores {#v0.2.5-bugs-squashed}+- Se controla un error del argumento 'wait_selector' cuando coincide con más de 1 elemento. Afecta a las clases `StealthyFetcher` y `PlayWrightFetcher`.+- Se corrige el tipo de codificación cuando la cabecera `content_type` contiene parámetros como `charset` (gracias a @andyfcx por [#12](https://github.com/D4Vinci/Scrapling/issues/12) )++##### Mejoras de uso {#v0.2.5-quality-of-life}+- Se añaden pruebas para cubrir nuevas partes del código y las pruebas pasan a ejecutarse en hilos.+- Se actualizan los docstrings para que se muestren correctamente en apidoc de Sphinx y herramientas similares.++##### Nuevos colaboradores {#v0.2.5-new-contributors}+- @andyfcx hizo su primera contribución en [#13 ](https://github.com/D4Vinci/Scrapling/pull/13)++## [v0.2.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.4) - 2024-11-20 {#v0.2.4}++### Qué ha cambiado {#v0.2.4-what-s-changed}++##### Correcciones de errores {#v0.2.4-bugs-squashed}+- Se corrige un error al obtener los bytes de la respuesta después de usar `network_idle` en las clases `StealthyFetcher` y `PlayWrightFetcher`. <br/> Provocaba el siguiente mensaje de error:++ ```+ Response.body: Protocol error (Network.getResponseBody): No resource with given identifier found+ ```++- La API de PlayWright a veces devuelve respuestas con el texto de estado vacío. Ahora `Scrapling` lo calcula por su cuenta si eso ocurre. Afecta a las clases `StealthyFetcher` y `PlayWrightFetcher`.++## [v0.2.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.3) - 2024-11-19 {#v0.2.3}++### Qué ha cambiado {#v0.2.3-what-s-changed}++##### Correcciones de errores {#v0.2.3-bugs-squashed}+- Se corrige un error de instalación con pip que impedía por completo el funcionamiento del modo sigiloso de PlayWright Fetcher.++## [v0.2.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.2) - 2024-11-16 {#v0.2.2}++### Qué ha cambiado {#v0.2.2-what-s-changed}+##### Nuevas funciones {#v0.2.2-new-features}+- Si no quieres pasar argumentos al objeto `Adaptor` generado y prefieres los valores por defecto, puedes usar esta importación para que el código sea más limpio++ ```python+ >> from scrapling.default import Fetcher, StealthyFetcher, PlayWrightFetcher+ >> page = Fetcher.get('https://example.com', stealthy_headers=True)+ ```++ En caso contrario++ ```python+ >> from scrapling import Fetcher, StealthyFetcher, PlayWrightFetcher+ >> page = Fetcher(auto_match=False).get('https://example.com', stealthy_headers=True)+ ```++##### Correcciones de errores {#v0.2.2-bugs-squashed}+1. Se corrige un error del objeto `Response`, introducido en el parche v0.2.1 de ayer, que aparecía en algunos casos de selección o análisis anidados.++## [v0.2.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.1) - 2024-11-15 {#v0.2.1}++### Qué ha cambiado {#v0.2.1-what-s-changed}+##### Nuevas funciones {#v0.2.1-new-features}+1. El objeto `Response` que devuelven todos los fetchers ahora es igual al objeto `Adaptor`, pero con estos atributos adicionales: `status`, `reason`, `cookies`, `headers` y `request_headers`. Los atributos `cookies`, `headers` y `request_headers` siempre son de tipo `dictionary`. <br/>Así, tu código ahora puede ser:++ ```python+ >> from scrapling import Fetcher+ >> page = Fetcher().get('https://example.com', stealthy_headers=True)+ >> print(page.status)+ 200+ >> products = page.css('.product')+ ```++ En lugar del código anterior++ ```python+ >> from scrapling import Fetcher+ >> fetcher = Fetcher().get('https://example.com', stealthy_headers=True)+ >> print(fetcher.status)+ 200+ >> page = fetcher.adaptor+ >> products = page.css('.product')+ ```++ He mantenido la propiedad `.adaptor` para conservar la compatibilidad con versiones anteriores.++2. Las clases `StealthyFetcher` y `PlayWrightFetcher` ahora aceptan un argumento `proxy` en el método de obtención, que puede ser una cadena o un diccionario.+3. La clase `StealthyFetcher` tiene ahora el argumento `os_randomize` en el método `fetch`. Si lo activas, Scrapling elige al azar las huellas de sistema operativo. Por defecto, las huellas coinciden con el sistema operativo actual.++##### Correcciones de errores {#v0.2.1-bugs-squashed}+1. Se corrige un error al pasar cabeceras con la clase `Fetcher`.+2. Se corrige un error al analizar respuestas JSON recibidas de las clases de fetchers.++##### Mejoras de uso {#v0.2.1-quality-of-life-changes}+1. Las funciones de texto intentaban eliminar los comentarios HTML antes de devolver el texto, pero eso causaba errores en algunos casos y complicaba el código sin necesidad. Ahora vuelven al comportamiento por defecto de lxml: **notarás un pequeño aumento de velocidad en las operaciones que dependen del texto de los elementos, como los selectores**. Si quieres que Scrapling quite los comentarios HTML antes de devolver el texto para evitar la extraña división de texto de lxml/parsel/scrapy, deja el argumento `keep_comments` en True, como está por defecto.++## [v0.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2) - 2024-11-11 {#v0.2}++### Qué ha cambiado {#v0.2-what-s-changed}+##### Nuevas funciones {#v0.2-new-features}+1. ¡Llega la función `Fetchers`, con 3 nuevos tipos principales para que Scrapling obtenga páginas por ti con MUCHAS opciones!+ - La clase `Fetcher`, para peticiones HTTP básicas+ - La clase `StealthyFetcher`, un fetcher totalmente sigiloso que usa una [versión modificada de Firefox para navegar con sigilo](https://github.com/daijro/camoufox).+ - La clase `PlayWrightFetcher`, para hacer peticiones con el navegador mediante PlayWright sin modificar, PlayWright con un modo sigiloso creado por mí, navegadores reales por CDP y [NSTBrowser](https://app.nstbrowser.io/r/1vO5e5) con su [docker browserless](https://hub.docker.com/r/nstbrowser/browserless).+2. Se añaden los métodos completamente nuevos `find_all`/`find` para encontrar elementos en la página con facilidad y un poco de magia negra.+3. Se añaden los métodos `filter` y `search` a la clase `Adaptors` para facilitar las operaciones por lotes en grupos de objetos `Adaptor`.+4. Se añaden los métodos `css_first` y `xpath_first` para facilitar el uso.+5. Se añade la nueva clase `TextHandlers`, que permite hacer operaciones por lotes con objetos `TextHandler`, igual que la clase `Adaptors`.+6. Se añaden los métodos `generate_full_css_selector` y `generate_full_xpath_selector`.++##### Correcciones de errores {#v0.2-bugs-squashed}+1. En la clase `Adaptors`, `re_first` devuelve ahora la primera coincidencia entre todos los objetos `Adaptor` que contiene, en lugar de devolver por error los resultados de `re_first` de todos los objetos `Adaptor`.+2. Si seleccionas contenido de texto de los elementos (como con la función CSS `::text`) mediante un método como `.css` o `.xpath`, el objeto `Adaptor` devuelve ahora la clase `TextHandlers` en lugar de una lista de cadenas. Así puedes usar `page.css('something::text').re_first(r'regex_pattern').json()` en lugar de `page.css('something::text')[0].re_first(r'regex_pattern').json()`+3. Los argumentos re/re_first de `Adaptor`/`Adaptors` ahora son coherentes con los de `TextHandler`. Ahora tienes los argumentos `clean_match` y `case_sensitive`.+4. El argumento `auto_match` está activado por defecto al crear `Adaptor`, pero aún debes activarlo al seleccionar elementos si quieres usarlo. (No es un error, sino una decisión de diseño)+5. Se corrigen muchas anotaciones de tipos para mejorar el autocompletado al programar con Scrapling.++##### Mejoras de uso {#v0.2-quality-of-life-changes}+1. Se cambian los nombres de los métodos `css_selector` y `xpath_selector` a `generate_css_selector` y `generate_xpath_selector` para dar más claridad y no interferir con el autocompletado al programar.+2. Se reorganiza la mayor parte del código antiguo en un subpaquete `core`, junto con otras decisiones de diseño para facilitar el mantenimiento futuro.+3. Se reorganiza la carpeta de pruebas y se añaden pruebas de las nuevas funciones. Ahora los entornos de tox se guardan en caché en GitHub para acelerar las pruebas automáticas de cada commit.++## [v0.1.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.2) - 2024-10-16 {#v0.1.2}++**Historial de cambios**:++- Se corrige un error que impedía que el argumento `keep_comments` funcionara como debía.+- Se ajusta la función de texto para eliminar automáticamente los comentarios HTML de los elementos antes de extraer su texto y evitar el comportamiento distinto de Lxml. Por ejemplo:++ ```python+ >>> page = Adaptor('<span>CONDITION: <!-- -->Excellent</span>', keep_comments=True)+ >>> page.css('span::text')+ ['CONDITION: ', 'Excellent']+ ```++ Antes se obtenía este resultado por el comportamiento por defecto de Lxml, pero ahora se devuelve el texto completo 'CONDITION: Excellent'+ Este comportamiento también se conoce en parsel\scrapy, así que quería resolverlo aquí.++- Se corrige un error que impedía eliminar el archivo de base de datos SQLite creado por la biblioteca al ejecutar `pip uninstall scrapling` o un comando similar.++## [v0.1.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.1) - 2024-10-14 {#v0.1.1}++Pequeñas correcciones++## [v0.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1) - 2024-10-13 {#v0.1}++**Historial completo de cambios**: <https://github.com/D4Vinci/Scrapling/commits/v0.1>diff --git a/docs/locales/fr/changelog.md b/docs/locales/fr/changelog.mdnew file mode 100644index 0000000..c3029a7--- /dev/null+++ b/docs/locales/fr/changelog.md@@ -0,0 +1,1279 @@+---+title: "Historique des changements de Scrapling"+description: "Notes des versions de Scrapling, avec les nouvelles fonctionnalités, les corrections et les changements incompatibles."+---++# Historique des changements {#changelog}++Tous les changements importants de Scrapling, tirés des [versions publiées sur GitHub](https://github.com/D4Vinci/Scrapling/releases).++## [v0.4.15](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.15) - 2026-08-23 {#v0.4.15}++**L’une des plus grandes versions de l’année : un serveur MCP repensé, du Markdown prêt pour RAG en une ligne, une meilleure résolution des défis Cloudflare et des onglets qui restent ouverts pour l’automatisation 🚀**++!!! warning "Avertissement"++ **Cette version introduit des changements incompatibles dans le serveur MCP. Consultez la section [changements incompatibles](https://github.com/D4Vinci/Scrapling/blob/v0.4.15/docs/ai/mcp-server.md#breaking-changes) avant de mettre à jour.**++### 🚀 Nouveautés et améliorations d’utilisation {#v0.4.15-new-stuff-and-quality-of-life-changes}++- **Les onglets du navigateur restent désormais ouverts et sont réutilisés entre les requêtes** (consultez la [documentation](fetching/stealthy.md#session-management)) :+ - Toutes les sessions du navigateur conservent leurs onglets après une requête. La suivante réutilise un onglet libre au lieu d’en ouvrir un autre.+ - Chaque requête réapplique ses propres réglages (délais, en-têtes et blocage des ressources) à l’onglet qu’elle reçoit. Les réglages ne passent donc pas d’une requête à l’autre.+ - Les onglets qui rencontrent une erreur sont fermés et remplacés. La nouvelle méthode `close_pages()` ferme tous les onglets ouverts.+ - La page récupérée reste chargée. Une fonction `page_setup` de la requête suivante s’exécute donc dessus avant de naviguer ailleurs. Cela permet d’enchaîner des étapes d’automatisation entre les requêtes.++- **Convertissez n’importe quelle page en Markdown propre, prêt pour les LLM, avec `Response.markdown()`** (consultez la [documentation](ai/building-rag-systems.md)) :++ ```python+ from scrapling.fetchers import Fetcher++ markdown = Fetcher.get("https://example.com").markdown(main_content_only=True)+ ```++ - Les scripts, les styles et le contenu caché d’injection de prompts sont toujours supprimés d’abord, avec le même nettoyage que celui du serveur MCP.+ - Passez `css_selector` pour ne convertir que les éléments dont vous avez besoin.+ - Disponible via le nouvel extra `rag` (`pip install "scrapling[rag]"`), également inclus dans les extras `ai`/`shell`/`all`.++- **Nouveau modèle `SiteToMarkdownSpider` pour explorer un site entier et créer un corpus Markdown pour les pipelines RAG** (consultez la [documentation](ai/building-rag-systems.md)) :++ ```python+ from scrapling.spiders import SiteToMarkdownSpider++ class DocsSpider(SiteToMarkdownSpider):+ name = "docs"+ start_urls = ["https://example.com/docs/"]+ allowed_domains = {"example.com"}+ output_dir = "docs_markdown"++ result = DocsSpider().start()+ result.items.to_jsonl("docs.jsonl")+ ```++ - Produit un élément par page avec `url`/`title`/`markdown`. Le paramètre facultatif `output_dir` écrit un fichier Markdown par page.+ - `max_pages` limite l’exploration. Comme le modèle repose sur `CrawlSpider`, redéfinir `rules()` vous donne un contrôle complet sur les liens suivis.++- **Le serveur MCP a été repensé (changement incompatible)** (consultez les [changements incompatibles](https://github.com/D4Vinci/Scrapling/blob/v0.4.15/docs/ai/mcp-server.md#breaking-changes) et la [documentation](ai/mcp-server.md)) :+ - Les 13 outils sont maintenant répartis en deux modes : les outils à usage unique (`fetch`, `bulk_fetch`, `stealthy_fetch`, `bulk_stealthy_fetch`), qui lancent toujours leur propre navigateur et affichent leurs vrais réglages par défaut, et les outils de session, qui utilisent une session ouverte une seule fois.+ - Le nouvel outil `session_fetch` récupère les pages via une session du navigateur. `open_session` ne contient plus que les réglages du navigateur et renvoie les réglages effectifs de la session à l’agent IA.+ - L’outil `get` a été renommé `make_request` et accepte maintenant toutes les méthodes HTTP.+ - Les nouveaux outils `open_request_session` et `session_make_request` donnent à l’IA des sessions HTTP persistantes qui conservent les cookies et l’empreinte du navigateur entre les requêtes.+ - Cela évite aussi que les récupérations réinitialisent les réglages de la session, un problème d’abord corrigé par @Yigtwxx dans [#418](https://github.com/D4Vinci/Scrapling/pull/418).++- **Le transport HTTP du serveur MCP exige maintenant une authentification et écoute sur localhost par défaut (changement incompatible)**, par @yamantaka-singh dans [#414](https://github.com/D4Vinci/Scrapling/pull/414) (corrige [#413](https://github.com/D4Vinci/Scrapling/issues/413), consultez la [documentation](ai/mcp-server.md#authentication)) :+ - Passez `--auth-token` (ou la variable d’environnement `SCRAPLING_MCP_AUTH_TOKEN`) pour exiger un jeton bearer, ou `--no-auth` pour proposer volontairement le serveur sans authentification.+ - Passez `--host 0.0.0.0` pour accepter les connexions depuis le réseau.++### 🐛 Corrections de bugs {#v0.4.15-bug-fixes}++- **La résolution de Cloudflare Turnstile/Interstitial fonctionne maintenant quelle que soit la configuration régionale du navigateur et ne boucle plus indéfiniment sur les défis interactifs en mode sans interface**. Les pages du navigateur discret ne plantent plus en cours de résolution, avec des contributions de @subediparas5 dans [#412](https://github.com/D4Vinci/Scrapling/pull/412). (Corrige [#411](https://github.com/D4Vinci/Scrapling/issues/411) et [#422](https://github.com/D4Vinci/Scrapling/issues/422))+- **Correction de `find`/`find_all` avec `class_`, qui manquaient sans avertissement les éléments ayant plusieurs classes**, par @yetval dans [#410](https://github.com/D4Vinci/Scrapling/pull/410), **ainsi que des valeurs vides de `class_` et des chaînes CSS non échappées**, par @yamantaka-singh dans [#417](https://github.com/D4Vinci/Scrapling/pull/417).+- **Correction de la perte des métadonnées de requête lors de la réutilisation des réponses en cache dans `development_mode`**, par @Yigtwxx dans [#419](https://github.com/D4Vinci/Scrapling/pull/419).+- **Correction des requêtes HTTP avec `retries` inférieur à 1 qui échouaient sans envoyer la requête**, par @Yigtwxx dans [#420](https://github.com/D4Vinci/Scrapling/pull/420).++### Documentation {#v0.4.15-docs}++- **Les sections du site ont été réorganisées** : la nouvelle section « Utilisation avec l’IA » regroupe le serveur MCP, la nouvelle page [Agent Skill](ai/agent-skill.md) et le guide [Créer des systèmes RAG](ai/building-rag-systems.md). Le guide de migration depuis BeautifulSoup rejoint l’intégration Scrapy dans « Intégrations et migrations ».+- **Ajout d’un [historique des changements](changelog.md)** au dépôt, avec les notes de toutes les versions publiées jusqu’ici.++## [v0.4.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.14) - 2026-08-10 {#v0.4.14}++**Une version de maintenance rapide pour corriger l’installation avec `uv` 🔧**++### 🐛 Corrections de bugs {#v0.4.14-bug-fixes}++- **Correction du refus de `uv` d’installer v0.4.13 par défaut, qui le faisait revenir à une ancienne version sans avertissement**. La version précédente exigeait une préversion de `curl_cffi`, que `uv` n’autorise pas sans activation explicite.+Toutes les dépendances utilisent maintenant des versions stables. (Corrige [#407](https://github.com/D4Vinci/Scrapling/issues/407))++## [v0.4.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.13) - 2026-08-09 {#v0.4.13}++**Une nouvelle mise à jour avec des spiders pour les flux et un serveur MCP plus intelligent 🎉**++### 🚀 Nouveautés et améliorations d’utilisation {#v0.4.13-new-stuff-and-quality-of-life-changes}++- **Nouveaux modèles de spiders pour les flux**. `XMLFeedSpider` parcourt les nœuds de tout flux XML (RSS, Atom, flux de produits, etc.), et `CSVFeedSpider` parcourt les lignes CSV sous forme de dictionnaires. Tous deux décompressent automatiquement les flux compressés avec gzip. (Consultez la [documentation](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import XMLFeedSpider++ class RSSSpider(XMLFeedSpider):+ name = "rss"+ start_urls = ["https://example.com/feed.xml"]++ async def parse_node(self, response, node):+ yield {"title": node.findtext("title"), "link": node.findtext("link")}++ result = RSSSpider().start()+ ```++- **Le serveur MCP utilise maintenant MCP SDK v2 et devient plus intelligent**. Il fournit des instructions qui apprennent à votre agent IA à utiliser les outils efficacement ; chaque outil déclare des annotations pour que des clients comme Claude Code puissent approuver automatiquement ceux qui lisent seulement ; les descriptions sont plus courtes pour économiser des tokens ; et le serveur communique sa version et son logo aux clients MCP. (Consultez la [documentation](ai/mcp-server.md))+- **Ajout de la commande `scrapling-mcp`**, qui lance directement `scrapling mcp`. L’enregistrement de Scrapling auprès des clients et registres MCP qui attendent une seule commande tient maintenant en une ligne.+- **Les versions de Playwright/Patchright et des navigateurs ne sont plus figées**. Le User-Agent généré correspond maintenant toujours à la version exacte de Chromium pilotée par votre installation de Playwright/Patchright. Scrapling n’impose donc plus leurs versions et vous pouvez les mettre à jour librement. Exécutez `scrapling install --force` après la mise à jour pour actualiser les navigateurs.++### 🐛 Corrections de bugs {#v0.4.13-bug-fixes}++- **Correction du plantage à l’importation de Scrapling avec un ValueError de `browserforge`** lorsque le paquet de données d’empreintes est en retard sur les versions des navigateurs. (Corrige [#394](https://github.com/D4Vinci/Scrapling/issues/394), [#396](https://github.com/D4Vinci/Scrapling/issues/396) et [#400](https://github.com/D4Vinci/Scrapling/issues/400))+- **Correction de la taille incorrecte des pools de pages des outils de navigateur par lots de MCP**, qui faisait échouer `bulk_fetch` avec plus de 50 URL et obligeait `bulk_stealthy_fetch` à récupérer toutes les URL depuis un seul onglet, par @Yigtwxx dans [#393](https://github.com/D4Vinci/Scrapling/pull/393).++### Projet {#v0.4.13-project}++- **Nouvelle [politique de contribution avec l’IA](https://github.com/D4Vinci/Scrapling/blob/main/AI_POLICY.md)** : les contributions assistées par l’IA sont les bienvenues, mais vous devez le signaler dans la PR ou l’issue ; les soumissions qui semblent générées par l’IA sans le signaler sont étiquetées et fermées.++## [v0.4.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.12) - 2026-07-26 {#v0.4.12}++**Une version qui aide vos spiders à mieux s’adapter aux sites qu’ils explorent**++### 🚀 Nouveautés et améliorations d’utilisation {#v0.4.12-new-stuff-and-quality-of-life-changes}++- **Les spiders peuvent maintenant régler leur vitesse avec AutoThrottle.** Au lieu de deviner un `download_delay` qui sera trop lent ou entraînera un blocage, le spider mesure la vitesse de réponse de chaque site et ajuste lui-même le délai de chaque domaine. Quand un site commence à vous bloquer ou à limiter le rythme des requêtes, il double le délai (ou attend exactement la durée demandée par l’en-tête `Retry-After`) jusqu’à ce que cela cesse, puis accélère de nouveau. Votre `download_delay` et tout `Crawl-delay` de robots.txt restent le minimum. (Consultez la [documentation](spiders/advanced.md#autothrottle))++ ```python+ class MySpider(Spider):+ name = "adaptive"+ start_urls = ["https://example.com"]+ autothrottle_enabled = True+ autothrottle_start_delay = 2.0+ autothrottle_max_delay = 30.0+ autothrottle_block_backoff = True+ ```++- **Exportez vos résultats en CSV et XML**, en plus des exportateurs JSON/JSONL déjà disponibles. Les éléments qui ne partagent pas toutes les mêmes clés sont exportés sans perte, et les valeurs imbriquées sont écrites en JSON. (Consultez la [documentation](spiders/getting-started.md))++ ```python+ result = MySpider().start()+ result.items.to_csv("products.csv")+ result.items.to_xml("products.xml")+ ```++- **Le serveur MCP peut maintenant exiger une authentification**, pour que vous puissiez l’exposer en toute sécurité au lieu de le garder sur votre propre machine. Toute requête sans jeton est rejetée, et vous pouvez aussi limiter les noms d’hôte auxquels le serveur répond. (Consultez la [documentation](ai/mcp-server.md))++ ```bash+ scrapling mcp --http --auth-token "$(openssl rand -hex 32)"+ ```++- **Les navigateurs acceptent maintenant les URL CDP via HTTP**, en plus de celles via WebSocket. À côté des endpoints `wss://` des fournisseurs de navigateurs gérés, vous pouvez donc connecter tout fetcher de navigateur ou toute session MCP à un Chrome que vous avez lancé avec `--remote-debugging-port=9222`.++- **Les images Docker publiées portent maintenant une étiquette avec leur version**, au lieu de seulement `latest`, pour que vous puissiez fixer la version exacte voulue, par @JanRK dans [#384](https://github.com/D4Vinci/Scrapling/pull/384).++### 🐛 Corrections de bugs {#v0.4.12-bug-fixes}++- **Correction de la perte de tous les cookies dans les réponses en cache** quand elles provenaient d’un moteur de navigateur. Cela cassait sans avertissement toute logique de session ou d’authentification qui en dépendait dans le mode de développement des spiders, par @amitvijapur dans [#379](https://github.com/D4Vinci/Scrapling/pull/379). (Corrige [#376](https://github.com/D4Vinci/Scrapling/issues/376))++- **Correction de `StealthyFetcher`, qui imposait la configuration régionale `en-US`** à tous les navigateurs au lieu de suivre celle du système. Les sites voyaient alors une différence entre cette configuration et votre adresse IP et vous jugeaient suspect, par exemple avec des réponses 429 de Google. (Corrige [#381](https://github.com/D4Vinci/Scrapling/issues/381))++- **Correction d’un message d’erreur trompeur dans le système de stockage** et suppression d’un appel inutilisé qui restait après les insertions, par @fix2015 dans [#377](https://github.com/D4Vinci/Scrapling/pull/377).++### Performances {#v0.4.12-performance}++- **Le temps d’exécution de `get_all_text()` est maintenant proportionnel au nombre de nœuds, O(nodes)** au lieu de parcourir les ancêtres de chaque nœud de texte. Cela le rend environ 5-6 fois plus rapide sur les pages très imbriquées, par @yetval dans [#378](https://github.com/D4Vinci/Scrapling/pull/378).++## [v0.4.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.11) - 2026-07-12 {#v0.4.11}++**Une mise à jour importante avec le premier modèle de spider pour une plateforme, un analyseur plus rapide et des corrections importantes 🎉**++### 🚀 Nouveautés et améliorations d’utilisation {#v0.4.11-new-stuff-and-quality-of-life-changes}++- **Ajout de `ShopifySpider`, le premier modèle de spider pour une plateforme !** Extrayez tous les produits de toute boutique Shopify via son API JSON, sans toucher au HTML du site. Créez une sous-classe, définissez le domaine de la boutique et c’est prêt (consultez la [documentation](spiders/platform-templates.md))++ ```python+ from scrapling.spiders import ShopifySpider++ class MyStore(ShopifySpider):+ target_website = "example.com"++ result = MyStore().start()+ ```++- **Ajout de `--executable-path` aux commandes de navigateur de la CLI**. `scrapling extract fetch` et `scrapling extract stealthy-fetch` acceptent maintenant un exécutable de navigateur personnalisé compatible avec Chromium. Si l’option n’est pas passée, ils utilisent la variable d’environnement `SCRAPLING_EXECUTABLE_PATH`, comme le serveur MCP (résout [#371](https://github.com/D4Vinci/Scrapling/issues/371))++ ```bash+ scrapling extract fetch "https://example.com" page.html --executable-path "/path/to/chromium"+ ```++### 🤖 Améliorations d’utilisation {#v0.4.11-quality-of-life-changes}+- **`find_by_text` et `find_by_regex` sont jusqu’à environ 2 fois plus rapides** quand `first_match` est activé (par défaut), car les éléments ne sont convertis en objets qu’au besoin et la recherche s’arrête au premier résultat, par @yetval dans [#370](https://github.com/D4Vinci/Scrapling/pull/370)+- **Mise à jour des tests de performance avec les nouveaux chiffres, comparés aux dernières versions de toutes les bibliothèques.**+- **Mise à jour des règles de contribution**++### 🐛 Corrections de bugs {#v0.4.11-bug-fixes}++- **Correction des plantages des outils de récupération du serveur MCP sur les pages contenant des caractères de contrôle**, avec l’erreur `All strings must be XML compatible`, par @yetval dans [#368](https://github.com/D4Vinci/Scrapling/pull/368) (corrige [#366](https://github.com/D4Vinci/Scrapling/issues/366))++## [v0.4.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.10) - 2026-07-04 {#v0.4.10}++**Une nouvelle mise à jour avec une toute nouvelle intégration Scrapy et plusieurs corrections de la communauté 🎉**++### 🚀 Nouveautés et améliorations d’utilisation {#v0.4.10-new-stuff-and-quality-of-life-changes}++- **Ajout d’une intégration Scrapy** pour utiliser l’API d’analyse de Scrapling dans vos projets Scrapy existants sans les réécrire. Appliquez le décorateur `scrapling_response` à un callback de spider. La réponse qu’il reçoit devient une `Response` de Scrapling, tandis que Scrapy continue de gérer l’exploration (consultez la [documentation](integrations/scrapy.md)) :++ ```python+ import scrapy+ from scrapling.integrations.scrapy import scrapling_response++ class QuotesSpider(scrapy.Spider):+ name = "quotes"+ start_urls = ["https://quotes.toscrape.com"]++ @scrapling_response+ def parse(self, response): # `response` is now a Scrapling Response+ first_quote = response.find_by_text("The world as we have created it", partial=True)+ for quote in [first_quote, *first_quote.find_similar()]:+ yield {"text": quote.get_all_text(strip=True)}+ ```++- **Le serveur MCP peut maintenant utiliser un navigateur personnalisé compatible avec Chromium** pour tous les outils basés sur un navigateur. Définissez-le une fois avec `scrapling mcp --executable-path "/path/to/chromium"` ou la variable d’environnement `SCRAPLING_EXECUTABLE_PATH`, ou pour chaque requête avec l’argument `executable_path`, par @samrusani dans [#360](https://github.com/D4Vinci/Scrapling/pull/360) (résout [#347](https://github.com/D4Vinci/Scrapling/issues/347))+- **Mise à jour de tous les navigateurs et des empreintes**. Exécutez `scrapling install --force` après la mise à jour pour les actualiser.++### 🐛 Corrections de bugs {#v0.4.10-bug-fixes}++- **Correction du texte illisible (mojibake) provenant des fetchers de navigateur sur les sites qui n’utilisent pas UTF-8**, par @yehudalevy-collab dans [#365](https://github.com/D4Vinci/Scrapling/pull/365) (corrige [#364](https://github.com/D4Vinci/Scrapling/issues/364)).+- **Correction de `LinkExtractor`, qui ne filtrait pas les extensions de fichiers composées comme `.tar.gz`**, par @renbkna dans [#359](https://github.com/D4Vinci/Scrapling/pull/359) (corrige [#349](https://github.com/D4Vinci/Scrapling/issues/349)).+- **Correction de la perte des requêtes en cours dans les points de reprise des explorations en pause, pour qu’elles ne soient plus ignorées à la reprise**, par @yetval dans [#358](https://github.com/D4Vinci/Scrapling/pull/358).+- **Correction du calcul des délais d’exploration à partir des directives `Request-rate` de robots.txt** grâce à la mise à jour de Protego, avec des tests adaptés par @Disaster-Terminator dans [#355](https://github.com/D4Vinci/Scrapling/pull/355).++### Documentation {#v0.4.10-docs}++- **Clarification de l’interaction de `init_script` avec le contexte d’exécution isolé de Patchright en mode discret**, par @mturac dans [#353](https://github.com/D4Vinci/Scrapling/pull/353) (résout [#350](https://github.com/D4Vinci/Scrapling/issues/350)).+- **Ajout de la méthode d’installation de la skill pour agents via [skills.sh](https://skills.sh/D4Vinci/Scrapling)**, par @ob-aion dans [#363](https://github.com/D4Vinci/Scrapling/pull/363).++## [v0.4.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.9) - 2026-06-07 {#v0.4.9}++**Une mise à jour de maintenance riche en corrections de problèmes signalés par la communauté 🛠️**++### 🚀 Nouveautés et améliorations d’utilisation {#v0.4.9-new-stuff-and-quality-of-life-changes}++- **Mise à jour de tous les navigateurs et des empreintes**. Exécutez `scrapling install --force` après la mise à jour pour les actualiser.+- **Ajout de l’option `--version` à la CLI**, par @ETM-Code dans [#303](https://github.com/D4Vinci/Scrapling/pull/303) (résout [#299](https://github.com/D4Vinci/Scrapling/issues/299))++### 🐛 Corrections de bugs {#v0.4.9-bug-fixes}++- **Correction de l’argument `proxy` de session, ignoré sans avertissement dans les sessions HTTP**, ce qui pouvait révéler votre véritable IP (résout [#295](https://github.com/D4Vinci/Scrapling/issues/295)). Associer un `proxy` de session avec un argument `proxies` par requête (ou l’inverse) produit maintenant une erreur au lieu d’en ignorer un sans avertissement.+- **Correction des échecs de navigation en combinant `init_script` avec `user_data_dir`** (résout [#294](https://github.com/D4Vinci/Scrapling/issues/294)).+- **Correction de la détection de l’encodage quand les sites mettent la valeur charset entre guillemets dans l’en-tête `Content-Type`**, par @Bortlesboat dans [#323](https://github.com/D4Vinci/Scrapling/pull/323).+- **Correction d’un `IndexError` lors de la relocalisation adaptative d’éléments avec `auto_save` activé**, par @Mubashirrrr dans [#340](https://github.com/D4Vinci/Scrapling/pull/340).+- **Correction des plantages lors de l’enregistrement des points de reprise et du cache des spiders sous Windows**, par @MrStarkEG dans [#344](https://github.com/D4Vinci/Scrapling/pull/344).+- **Correction du calcul de similarité dans `find_similar` pour les éléments ayant un nombre différent d’attributs** (résout [#322](https://github.com/D4Vinci/Scrapling/issues/322)).++### Documentation {#v0.4.9-docs}++- **Clarification : l’installation par défaut contient seulement le moteur d’analyse**, et les fetchers et spiders nécessitent les extras (résout [#343](https://github.com/D4Vinci/Scrapling/issues/343)).+- **Correction du nom de l’image Docker dans les exemples restants**, par @evanclan dans [#315](https://github.com/D4Vinci/Scrapling/pull/315).+- **Correction d’un lien cassé dans le guide de contribution**, par @Bortlesboat dans [#320](https://github.com/D4Vinci/Scrapling/pull/320).++## [v0.4.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.8) - 2026-05-11 {#v0.4.8}++**Une grande mise à jour des spiders qui améliore le système d’exploration 🕷️**++### 🚀 Nouveautés et améliorations d’utilisation {#v0.4.8-new-stuff-and-quality-of-life-changes}++- **Ajout de l’outil `LinkExtractor`** dans `scrapling.spiders.LinkExtractor` pour extraire les URL d’une `Response`. Il offre de nombreux contrôles (consultez la [documentation](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import LinkExtractor++ extractor = LinkExtractor(allow=r"/posts/", deny_domains=["ads.example.com"])+ ```++- **Ajout des modèles de spiders génériques `CrawlSpider` et `CrawlRule`** pour ne plus réécrire le même code de « suivi des liens correspondant à ce motif ». Redéfinissez `rules()` pour renvoyer une liste d’objets `CrawlRule`, chacun associé à un `LinkExtractor`. (Consultez la [documentation](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import CrawlSpider, CrawlRule, LinkExtractor++ class QuotesSpider(CrawlSpider):+ name = "blog"+ start_urls = ["https://quotes.toscrape.com/"]++ def rules(self):+ return [+ CrawlRule(LinkExtractor(allow=r"/author/"), callback=self.parse_author),+ CrawlRule(LinkExtractor(allow=r"/page/\d+/")), # pagination, no callback+ ]++ async def parse_author(self, response):+ yield {+ "name": response.css(".author-title::text").get(),+ "birthday": response.css(".author-born-date::text").get(),+ "url": response.url,+ }+ ```++- **Ajout du modèle `SitemapSpider`**, qui démarre une exploration directement depuis un sitemap ou des URL de `robots.txt`. Il gère les sitemaps compressés avec gzip et offre de nombreux contrôles et options. Les URL sont réparties selon les règles d’exploration, comme pour **CrawlSpider** ci-dessus. (Consultez la [documentation](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import SitemapSpider, CrawlRule, LinkExtractor++ class NewsSitemap(SitemapSpider):+ name = "news"+ sitemap_urls = ["https://example.com/robots.txt"]++ def rules(self):+ return [+ CrawlRule(LinkExtractor(allow=r"/articles/"), callback=self.parse_article),+ ]++ async def parse_article(self, response):+ yield {"url": response.url, "title": response.css("h1::text").get()}+ ```++- **La relocalisation adaptative utilise maintenant un seuil de similarité de 40 % par défaut**, au lieu de `0`, dans toutes les méthodes. Cela améliore le fonctionnement du mode adaptatif. Si aucun élément ne dépasse le seuil, un avertissement indique maintenant le meilleur score trouvé, pour que vous puissiez réduire `percentage` en connaissance de cause si nécessaire.++- **Mise à jour de tous les navigateurs et des empreintes**. Exécutez de nouveau `scrapling install --force` après la mise à jour pour actualiser les navigateurs et les empreintes.++### 🐛 Corrections de bugs {#v0.4.8-bug-fixes}++- **Correction de `Fetcher.configure(...)`, qui ne s’appliquait pas aux appels par requête**. La même correction a été appliquée à `AsyncFetcher`.+- **Correction du calcul incorrect des empreintes de requêtes qui provoquait des requêtes en double dans les spiders**, par @yetval dans [#255](https://github.com/D4Vinci/Scrapling/pull/255).+- **Le moteur d’extraction adaptative signale maintenant les correspondances faibles.** Avec le changement de seuil ci-dessus, vous recevez maintenant un avertissement au lieu d’un élément trompeur présenté comme la « meilleure estimation » quand la relocalisation échoue.++### Documentation {#v0.4.8-docs}++- **Mise à jour des anciens exemples de code** dans toute la documentation pour correspondre à la version actuelle.+- **Amélioration du copier-coller de code** sur le site de documentation et réduction de la skill pour agents afin de consommer moins de tokens à chaque appel.++## [v0.4.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.7) - 2026-04-17 {#v0.4.7}++**Une mise à jour qui permet à vos agents IA de voir les pages 📸**++### 🚀 Nouveautés et améliorations d’utilisation {#v0.4.7-new-stuff-and-quality-of-life-changes}++- **Ajout de l’outil MCP `screenshot`**, qui capture une page et la renvoie sous forme de véritable bloc MCP `ImageContent` pour que le modèle puisse la voir. L’outil exige une session de navigateur ouverte : appelez d’abord `open_session` (avec `dynamic` ou `stealthy`), puis passez le `session_id` ici. Il prend en charge PNG et JPEG, les captures de page entière, la qualité JPEG et les contrôles d’attente habituels (`wait`, `wait_selector`, `network_idle`, `timeout`). (Implémente [#244](https://github.com/D4Vinci/Scrapling/issues/244))+- **Ajout d’un paramètre `session_id` personnalisé à `open_session`** pour nommer les sessions de façon utile (`"search"`, `"checkout"`) au lieu de la valeur hexadécimale aléatoire de 12 caractères utilisée par défaut. Par @hauntedhost dans [#243](https://github.com/D4Vinci/Scrapling/pull/243)++### 🐛 Corrections de bugs {#v0.4.7-bug-fixes}++- **Correction de la corruption de l’état de `FetcherSession` et d’un plantage à la fermeture d’une session à démarrage différé**. Par @yetval dans [#245](https://github.com/D4Vinci/Scrapling/pull/245)+- **Correction de `TypeError: Session.request() got an unexpected keyword argument 'block_ads'`** lors de l’utilisation de l’option `--ai-targeted` de la CLI avec les commandes HTTP. Par @voidborne-d dans [#249](https://github.com/D4Vinci/Scrapling/pull/249) (corrige [#247](https://github.com/D4Vinci/Scrapling/issues/247))++### Traductions {#v0.4.7-translations}++- **Ajout d’une traduction du README en portugais brésilien**, par @rgomids dans [#250](https://github.com/D4Vinci/Scrapling/pull/250)++## [v0.4.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.6) - 2026-04-13 {#v0.4.6}++**Une mise à jour centrée sur la discrétion du navigateur, la confidentialité et l’expérience de développement 🔒**++### 🚀 Nouveautés et améliorations d’utilisation {#v0.4.6-new-stuff-and-quality-of-life-changes}++- **Ajout du blocage de publicités intégré** aux fetchers de navigateur. Passez `block_ads=True` pour bloquer les requêtes vers environ 3 500 domaines connus de publicité et de suivi dès l’interception des routes : sans DNS, sans TCP, avec annulation immédiate. Vous pouvez le combiner avec `blocked_domains` pour vos propres listes. Le serveur MCP et le mode `--ai-targeted` de la CLI l’activent automatiquement pour économiser des tokens et accélérer le chargement des pages.++ ```python+ page = StealthyFetcher.fetch('https://example.com', block_ads=True)+ ```++- **Ajout de la prise en charge de DNS-over-HTTPS** pour éviter les fuites DNS avec les proxies. Passez `dns_over_https=True` pour envoyer les requêtes DNS au service DoH de Cloudflare. Ainsi, la résolution DNS ne révèle pas votre position réelle même quand le trafic HTTP passe par un proxy.++ ```python+ page = StealthyFetcher.fetch('https://example.com', proxy='http://proxy:8080', dns_over_https=True)+ ```++- **Ajout du callback `page_setup`** aux fetchers de navigateur. Cette fonction s’exécute avant `page.goto()` et permet d’enregistrer des écouteurs d’événements, des routes ou des scripts qui doivent être prêts avant la navigation. Elle complète `page_action` (qui s’exécute après la navigation). (Résout [#237](https://github.com/D4Vinci/Scrapling/issues/237))++ ```python+ def capture_websockets(page):+ page.on("websocket", lambda ws: print(f"WS: {ws.url}"))++ page = DynamicFetcher.fetch('https://example.com', page_setup=capture_websockets)+ ```++- **Ajout des options CLI `--block-ads` et `--dns-over-https`** aux commandes `fetch` et `stealthy-fetch`.++### 🐛 Corrections de bugs {#v0.4.6-bug-fixes}++- **Correction de l’alias de type `Seconds`**, qui rejetait les valeurs décimales. Passer `wait=1.5` ou `timeout=500.0` aux fetchers de navigateur provoquait une erreur de type, car l’alias traitait `float` comme des métadonnées plutôt que comme un type. Par @kuishou68 dans [#240](https://github.com/D4Vinci/Scrapling/pull/240)+- **Correction des segments ID en double dans la génération de sélecteurs avec un chemin complet**. Le sélecteur des éléments ayant un attribut `id` était ajouté deux fois lors de la génération de chemins CSS/XPath complets, ce qui produisait des sélecteurs comme `body > #main > #main > #target > #target`. Les chemins XPath complets produisaient aussi des conditions `[@id='x']` isolées (XPath non valide) au lieu de `*[@id='x']` ; ce problème a été corrigé. Par @sjhddh dans [#241](https://github.com/D4Vinci/Scrapling/pull/241)+- **Correction des paramètres manquants dans les signatures du shell**. Les signatures des fonctions du shell interactif ne contenaient pas `blocked_domains`, `block_ads`, `retries`, `retry_delay`, `capture_xhr`, `executable_path` et `dns_over_https`.++## [v0.4.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.5) - 2026-04-07 {#v0.4.5}++**Une mise à jour avec une grande amélioration d’utilisation pour les développeurs de spiders et quelques corrections importantes 🎉**++### 🚀 Nouveautés et améliorations d’utilisation {#v0.4.5-new-stuff-and-quality-of-life-changes}++- **Mode de développement des spiders** : modifier la logique de `parse()` d’un spider exigeait auparavant de solliciter les serveurs cibles à chaque exécution. C’était lent, générait du trafic et risquait de faire limiter vos requêtes alors que vous ajustiez encore vos sélecteurs. Le nouveau mode de développement met chaque réponse en cache sur disque à la première exécution, puis les relit sur disque à chaque exécution suivante. Vous pouvez donc ajuster les callbacks et relancer autant de fois que vous voulez sans envoyer une seule requête réseau. Activez-le avec un attribut de classe :++ ```python+ class MySpider(Spider):+ name = "my_spider"+ start_urls = ["https://example.com"]+ development_mode = True++ async def parse(self, response):+ yield {"title": response.css("title::text").get("")}+ ```++ Le cache se trouve dans `.scrapling_cache/{spider.name}/` par défaut, et vous pouvez changer son emplacement avec `development_cache_dir`. Deux nouveaux compteurs, `cache_hits` et `cache_misses`, indiquent les performances du cache. La relecture du cache ignore `download_delay`, la limitation du rythme et le chemin de nouvelle tentative des requêtes bloquées, pour que les essais soient aussi rapides que le disque le permet. Ne déployez pas un spider avec `development_mode = True` : c’est un outil de développement, pas un cache de production. Consultez la [documentation](spiders/advanced.md#development-mode) pour tous les détails.++- **Des redirections plus sûres par défaut** : `follow_redirects` vaut maintenant `"safe"` par défaut pour tous les fetchers HTTP, le serveur MCP et le shell. Les redirections restent suivies, mais celles qui ciblent des IP internes ou privées (loopback, réseaux privés, link-local) sont rejetées. Cela vous protège contre SSRF lors de l’extraction de données depuis des URL fournies par les utilisateurs. Passez `follow_redirects="all"` pour retrouver l’ancien comportement, ou `False` pour désactiver entièrement les redirections.++### 🐛 Corrections de bugs {#v0.4.5-bug-fixes}++- **L’arrêt forcé ne perd plus votre point de reprise** : appuyer deux fois sur Ctrl+C (arrêt forcé) dans un spider avec `crawldir` activé pouvait entrer en conflit avec l’écriture du point de reprise. Le contexte d’annulation arrêtait la tâche avant la fin du pickle, laissait `paused=False` et déclenchait le nettoyage qui *supprime* le point de reprise précédent. L’arrêt forcé d’une longue exploration pouvait ainsi faire perdre toute la progression que vous tentiez de sauver. Le moteur écrit maintenant le point de reprise **avant** d’appeler `cancel_scope.cancel()`, pour qu’un arrêt forcé conserve toujours le dernier état en attente. Par @voidborne-d dans [#230](https://github.com/D4Vinci/Scrapling/pull/230).++## [v0.4.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.4) - 2026-04-05 {#v0.4.4}++**Une nouvelle mise à jour avec des améliorations importantes des spiders et des corrections de bugs 🎉**++### 🚀 Nouveautés et améliorations d’utilisation {#v0.4.4-new-stuff-and-quality-of-life-changes}+- **Ajout du respect de robots.txt au système de spiders** avec la nouvelle option `robots_txt_obey`. Quand elle est activée, le spider récupère et respecte automatiquement les règles de robots.txt avant l’exploration, y compris les directives `Disallow`, `Crawl-delay` et `Request-rate`. Les fichiers robots.txt sont récupérés en parallèle et mis en cache par domaine pour toute l’exploration. Par @AbdullahY36 dans [#226](https://github.com/D4Vinci/Scrapling/pull/226)+- **Ajout du chargement préalable du cache de robots.txt**, pour récupérer et analyser les fichiers robots.txt de tous les domaines de start_urls avant le début de la boucle d’exploration. Cela évite une attente lors de la première requête vers chaque domaine.+- **Ajout de la statistique `robots_disallowed_count`** à `CrawlStats` pour compter les requêtes bloquées par les règles de robots.txt pendant l’exploration.++Consultez les détails sur le site [ici](spiders/getting-started.md#robotstxt-compliance)++### 🐛 Corrections de bugs {#v0.4.4-bug-fixes}+- **Correction d’un problème important de MRO avec `ProxyRotator`** : la méthode provisoire `_build_context_with_proxy` masquait l’implémentation réelle des classes enfants et la rotation des proxies levait toujours `NotImplementedError` (corrige [#215](https://github.com/D4Vinci/Scrapling/issues/215)). Merci, @yetval+- **Correction d’une fuite dans le pool de pages** avec la rotation des proxies par requête dans les sessions du navigateur. Les pages créées dans des contextes temporaires n’étaient pas retirées du pool au nettoyage, ce qui accumulait des références obsolètes au fil du temps. Par @yetval dans [#223](https://github.com/D4Vinci/Scrapling/pull/223)+- **Correction d’une vérification de type manquante** dans le fetcher statique : `curl_cffi` pouvait renvoyer `None` depuis `session.request()`, ce qui provoquait des erreurs ensuite.++### Autres changements {#v0.4.4-other}+- Mise à jour des dépendances, pour disposer des dernières empreintes et d’autres nouveautés.+- Ajout de `protego` comme nouvelle dépendance dans le groupe optionnel `fetchers` pour analyser robots.txt.++## [v0.4.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.3) - 2026-03-30 {#v0.4.3}++**Une nouvelle mise à jour avec de nombreux changements importants 🎉**++### 🚀 Nouveautés et améliorations d’utilisation {#v0.4.3-new-stuff-and-quality-of-life-changes}+- **Ajout d’un nouvel outil MCP** pour ouvrir un navigateur persistant, normal ou discret, et continuer à l’utiliser avec les autres outils, ainsi que d’un autre outil pour le fermer. ([Exemples](https://github.com/D4Vinci/Scrapling/blob/v0.4.3/docs/ai/mcp-server.md#examples))+- **Ajout d’un nouvel outil MCP** pour lister toutes les sessions du navigateur existantes, destiné à être utilisé avec les nouveaux outils.+- **Ajout d’une nouvelle option aux sessions du navigateur** pour collecter automatiquement toutes les requêtes en arrière-plan pendant une requête (résout [#159](https://github.com/D4Vinci/Scrapling/pull/159)) [[Exemples](https://github.com/D4Vinci/Scrapling/blob/v0.4.3/docs/fetching/dynamic.md#capturing-xhrfetch-requests)].+- **Ajout d’un nouveau nettoyage** pour protéger le serveur MCP contre les attaques courantes d’injection de prompts en supprimant le contenu caché ou invisible.+- **Ajout d’une nouvelle option de ligne de commande**, appelée `--ai-targeted`, aux commandes d’extraction Web pour adapter le contenu à l’IA et le protéger contre les attaques courantes d’injection de prompts, comme le serveur MCP.+- **Ajout d’une nouvelle option aux sessions du navigateur**, appelée `executable_path`, pour définir un chemin de navigateur personnalisé (résout [#202](https://github.com/D4Vinci/Scrapling/pull/202))+- **Réorganisation** du code du serveur MCP pour simplifier sa maintenance, et passage de tous les outils en mode asynchrone.+- **Réorganisation** du code des commandes CLI pour simplifier sa maintenance et le réduire de 210 lignes.++### 🐛 Corrections de bugs {#v0.4.3-bug-fixes}+- Correction d’un bug pour conserver la méthode HTTP lors des nouvelles tentatives dans la session du spider, par @karesansui-u dans [#201](https://github.com/D4Vinci/Scrapling/pull/201)+- Ajout d’un nombre maximal de tentatives pour récupérer le contenu de la page afin d’éviter une boucle infinie, par @haosenwang1018 et @D4Vinci dans [#197](https://github.com/D4Vinci/Scrapling/pull/197)+- Remplacement du `raise` sans argument par `return False` dans `_restore_from_checkpoint`, par @haosenwang1018 dans [#196](https://github.com/D4Vinci/Scrapling/pull/196)+- Remplacement de `get_all` par `getall` dans `Texthandler` pour correspondre à la classe Selector.++### Amélioration des tests et de leur couverture {#v0.4.3-coverage-tests-improvement}+- Ajout de tests des cas limites de `_normalize_credentials`, par @Bortlesboat dans [#192](https://github.com/D4Vinci/Scrapling/pull/192)+- Ajout de tests du cycle d’enregistrement et de récupération, ainsi que du stockage principal, par @haosenwang1018 dans [#193](https://github.com/D4Vinci/Scrapling/pull/193)+- Ajout d’une couverture des chemins regex de `TextHandler` et de `TextHandlers.re()`, par @haosenwang1018 dans [#194](https://github.com/D4Vinci/Scrapling/pull/194)+- Ajout de tests des cas limites de `filter`, `iterancestors` et `find_similar`, par @awanawana dans [#200](https://github.com/D4Vinci/Scrapling/pull/200)++### Amélioration de l’Agent Skill {#v0.4.3-agent-skill-improvement}+- Correction des liens Markdown cassés dans les références de la skill, par @yetval dans [#204](https://github.com/D4Vinci/Scrapling/pull/204)+- Amélioration de la structure de la skill pour mieux passer la validation de [Clawhub](https://clawhub.ai/d4vinci/scrapling-official).+- La skill impose maintenant l’option de ligne de commande `--ai-targeted` lors de l’extraction par des commandes.++### Amélioration de la documentation {#v0.4.3-docs-improvement}+- Ajout d’une traduction du README en coréen, par @greatsk55 dans [#187](https://github.com/D4Vinci/Scrapling/pull/187)+- Correction des espaces entre les caractères CJK et latins dans les README chinois et japonais.+- Correction des liens cassés de l’ancienne présentation du site.++## [v0.4.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.2) - 2026-03-08 {#v0.4.2}++**Une nouvelle mise à jour de maintenance avec des changements importants**++#### Corrections de bugs {#v0.4.2-bug-fixes}+- La fonction `get_all_text()` récupère désormais aussi les nœuds de texte qui suivent les éléments. Le serveur MCP et les commandes peuvent ainsi lire du texte qui était ignoré auparavant ([#168](https://github.com/D4Vinci/Scrapling/pull/168)). Merci @mhillebrand+- Referer renvoie désormais l’URL de base de Google au lieu d’une URL de recherche Google. La logique précédente était incorrecte et pouvait produire un indice permettant de reconnaître l’empreinte du navigateur ([#179](https://github.com/D4Vinci/Scrapling/pull/179)). Merci @Bortlesboat+- Correction d’un problème lors de l’assemblage des options de lancement supplémentaires dans tous les navigateurs. Merci @rostchri+- Correction d’un problème d’annotations de types qui provoquait un plantage avec les versions de Python antérieures à 3.12. (Résout [#163](https://github.com/D4Vinci/Scrapling/issues/163))++#### Autres changements {#v0.4.2-other}+- Ajout d’une Agent Skill pour Claude Code / OpenClaw et d’autres outils d’agents IA.+- Ajout de l’Agent Skill à Clawhub.+- Mise à jour de tous les navigateurs et de Playwright vers les dernières versions.+- Ajout d’une traduction française du fichier README principal.++## [v0.4.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.1) - 2026-02-27 {#v0.4.1}++**Une nouvelle mise à jour avec de nombreux changements importants**++### 🚀 Nouveautés et améliorations d’utilisation {#v0.4.1-new-stuff-and-quality-of-life-changes}+- **Expressions régulières plus précises** pour détecter les défis Cloudflare (Merci à @Rinz27 [#133](https://github.com/D4Vinci/Scrapling/pull/133))+- **Résolution des défis Cloudflare plus rapide et plus efficace**. Elle est désormais presque deux fois plus rapide.+- **Amélioration de la résolution des défis Cloudflare** pour les sites qui affichent parfois la page Cloudflare deux fois avant de rediriger vers le site principal.+- **Amélioration du mode furtif et de la vitesse du navigateur furtif** grâce à la suppression des fichiers JS injectés.+- **Amélioration du schéma MCP** pour qu’il soit accepté par OpenCode (Merci à @robin-ede [#137](https://github.com/D4Vinci/Scrapling/pull/137))+- **Schéma MCP encore plus conforme au protocole** pour qu’il soit accepté par VS Code Copilot et d’autres outils stricts. (Résout #150 )+- **Forte réduction de la consommation de tokens du serveur MCP** en supprimant les balises HTML inutiles quand l’option `main_content_only` est activée.+- Correction de la page PyPI et ajout des fichiers nécessaires pour inscrire le serveur MCP au registre des serveurs MCP.+- Ajout d’un exemple montrant comment installer les dépendances des navigateurs depuis le code plutôt que depuis la ligne de commande, pour faciliter l’automatisation.+- Amélioration de tous les workflows avec les dernières versions des actions (Merci à @salmanmkc [#143](https://github.com/D4Vinci/Scrapling/pull/143)/[#144](https://github.com/D4Vinci/Scrapling/pull/144))++## [v0.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4) - 2026-02-15 {#v0.4}++**La plus grande version de Scrapling à ce jour : framework de spiders, rotation de proxies et améliorations majeures du parser**++Cette version apporte un framework de spiders et d’exploration entièrement asynchrone, une gestion intelligente des proxies et des changements importants de l’API qui rendent Scrapling plus puissant et plus cohérent. Lisez attentivement la section sur les changements incompatibles avant la mise à jour.++### 🕷️ Framework de spiders {#v0.4-spider-framework}++Un nouveau framework d’exploration asynchrone basé sur `anyio` pour une extraction organisée et à grande échelle :++```python+from scrapling.spiders import Spider, Response++class MySpider(Spider):+ name = "demo"+ start_urls = ["https://example.com/"]++ async def parse(self, response: Response):+ for item in response.css('.product'):+ yield {"title": item.css('h2::text').get()}++MySpider().start()+```++- **API de spiders similaire à Scrapy** : Définissez des spiders avec `start_urls`, des callbacks `parse` asynchrones, des objets `Request`/`Response` et une file de priorité.+- **Exploration concurrente** : Limites de concurrence, contrôle du débit par domaine et délais entre les téléchargements configurables.+- **Prise en charge de plusieurs sessions** : Une interface commune pour les requêtes HTTP et les navigateurs furtifs sans interface graphique dans un même spider. Dirigez les requêtes vers différentes sessions grâce à leur ID. Le démarrage des sessions au premier besoin est pris en charge.+- **Pause et reprise** : Conservation de l’état de l’exploration grâce à des points de reprise. Appuyez sur Ctrl+C pour arrêter proprement, puis redémarrez pour reprendre là où vous en étiez.+- **Mode streaming** : Recevez les éléments dès leur extraction via `async for item in spider.stream()`, avec des statistiques en temps réel. Idéal pour les interfaces, les pipelines et les longues explorations.+- **Détection des requêtes bloquées** : Détection et nouvelles tentatives automatiques des requêtes bloquées, avec une logique personnalisable.+- **Export intégré** : Exportez les résultats avec des hooks et votre propre pipeline, ou utilisez l’export intégré JSON/JSONL avec `result.items.to_json()` / `result.items.to_jsonl()`, respectivement.+- **Hooks du cycle de vie** : `on_start()`, `on_close()`, `on_error()`, `on_scraped_item()` et d’autres hooks pour contrôler tout le cycle de vie de l’exploration.+- **Statistiques détaillées d’exploration** : Suivi des requêtes, réponses, octets, codes de statut, proxies, détails par domaine et session, nombres de messages par niveau de log, et plus encore.+- **Prise en charge d’uvloop** : Passez `use_uvloop=True` à `spider.start()` pour accélérer l’exécution asynchrone quand uvloop est disponible.++Une nouvelle section du site présente tous les détails. Cliquez [ici](spiders/architecture.md)++### 🔄 Rotation de proxies {#v0.4-proxy-rotation}++* Nouvelle classe `ProxyRotator` avec une rotation sûre entre threads. Elle fonctionne avec tous les fetchers et toutes les sessions :++ ```python+ from scrapling import ProxyRotator+ rotator = ProxyRotator(["http://proxy1:8080", "http://proxy2:8080"])+ Fetcher.get(url, proxy_rotator=rotator)+ ```++* **Stratégies de rotation personnalisées** : Créez votre propre logique de rotation de proxies+* **Changement de proxy par requête** : Passez `proxy=` à un appel individuel de `get()`/`post()`/`fetch()` pour remplacer le proxy de la session pour cette requête.++### 🌐 Améliorations des fetchers de navigateur {#v0.4-browser-fetcher-improvements}++* **Blocage de domaines** : Nouveau paramètre `blocked_domains` sur `DynamicFetcher`/`StealthyFetcher` pour bloquer les requêtes vers des domaines précis. Leurs sous-domaines sont inclus automatiquement.+* **Nouvelles tentatives automatiques** : Les fetchers de navigateur réessaient désormais en cas d’échec avec les paramètres `retries` (valeur par défaut : 3) et `retry_delay` (valeur par défaut : 1s). Cela inclut la détection des erreurs liées aux proxies.+* **Métadonnées de réponse** : Le dictionnaire `Response.meta` enregistre automatiquement le proxy utilisé et intègre les métadonnées de la requête.+* **Response.follow()** : Créez des objets `Request` pour les requêtes suivantes avec une gestion automatique du referer, conçus pour le système de spiders.+* **Aucune lecture automatique** : Les sessions de navigateur bloquent désormais le contenu en lecture automatique, qui causait des problèmes auparavant.+* **Vitesse** : Amélioration de la discrétion et de la vitesse en ajustant les options de lancement du navigateur.++### 🔧 Corrections de bugs et améliorations {#v0.4-bug-fixes-improvements}+- **Optimisation du parser** : Optimisation des opérations répétées pour améliorer les performances.+- **Pages en erreur** : Correction d’un bug qui empêchait le navigateur de se fermer quand les pages renvoyaient des erreurs.+- **Corps vide** : Prise en charge des réponses dont le corps est vide.+- **Boucle Playwright** : Correction d’un problème qui laissait la boucle Playwright ouverte quand la connexion CDP échouait+- **Sécurité des types** : Correction de toutes les erreurs mypy et ajout d’annotations de types dans les corps de fonctions qui n’en avaient pas. Ajout de mypy et pyright au workflow de CI.++### ⚠️ Changements incompatibles {#v0.4-breaking-changes}++* **Suppression de `css_first`/`xpath_first`** : Utilisez `css('.selector').first`, `css('.selector')[0]` ou `css('.selector').get()` à la place.+* **Toutes les sélections renvoient désormais `Selectors`** : `css('::text')`, `xpath('//text()')`, `css('::attr(href)')` et `xpath('//@href')` renvoient maintenant `Selectors`, qui enveloppe les nœuds de texte dans des objets `Selector` avec `tag="#text"`, au lieu de `TextHandlers`. Cela rend l’API cohérente entre toutes les méthodes de sélection et les annotations de types.+* **`Response.body` est toujours de type `bytes`** : Auparavant, il pouvait être de type `str` ou `bytes`. Il renvoie désormais toujours `bytes`.+* **Comportement de `get()`/`getall()`** : Sur `Selector`, `get()` renvoie `TextHandler` (HTML sérialisé ou valeur textuelle) et `getall()` renvoie `TextHandlers`. Alias : `extract_first = get`, `extract = getall`. L’ancien `get_all()` de `Selectors` est supprimé.+* **`Selectors.first`/`.last`** : Accès sûr qui renvoie `Selector | None` au lieu de lever `IndexError`.+* **Constantes internes renommées** : `DEFAULT_FLAGS` → `DEFAULT_ARGS`, `DEFAULT_STEALTH_FLAGS` → `STEALTH_ARGS`, `HARMFUL_DEFAULT_ARGS` → `HARMFUL_ARGS`, `DEFAULT_DISABLED_RESOURCES` → `EXTRA_RESOURCES`.++### 🔨 Autres changements {#v0.4-other-changes}++* **Changements de dépendances** : Remplacement de `tldextract` par `tld`, suppression du fichier interne `_html_utils.py` au profit de `w3lib.html.replace_entities`, et ajout de `typing_extensions` comme dépendance obligatoire.+* **Refonte de la documentation** : Migration complète de MkDocs vers Zensical, nouvelle section sur les spiders, mise à jour de toutes les pages existantes et ajout de nouvelles références d’API.++## [v0.3.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.14) - 2026-01-03 {#v0.3.14}++**Une petite mise à jour de maintenance pour corriger des problèmes apparus sur certains appareils avec la v0.3.13**++- Désactivation du mode de navigation privée dans `StealthyFetcher` et ses classes de session, car il empêchait la conservation des cookies entre les pages sur Windows. Ce problème ne se produisait pas sur MacOS ni Linux (Corrige [#123](https://github.com/D4Vinci/Scrapling/issues/123) ; merci à @frugality4121 de l’avoir signalé et à @gembleman d’avoir indiqué la solution).+- La version de browserforge est désormais fixée à la plus récente pour résoudre le problème des anciens modèles d’en-têtes chez les utilisateurs qui avaient déjà une ancienne version de browserforge.++## [v0.3.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.13) - 2026-01-01 {#v0.3.13}++**Une mise à jour majeure avec des améliorations dans de nombreux domaines, mais aussi beaucoup de changements incompatibles pour de bonnes raisons. Lisez ce qui suit avant de mettre à jour**++* Pour plusieurs raisons, nous avons décidé de ne plus utiliser Camoufox du tout à partir de maintenant. Nous pourrions y revenir si son développement se poursuit. Si vous préférez continuer à utiliser Camoufox comme avant cette version, consultez les instructions dans cette [section](https://github.com/D4Vinci/Scrapling/blob/v0.3.13/docs/fetching/stealthy.md#using-camoufox-as-an-engine).++* Nous utilisions auparavant patchright dans le mode furtif de `DynamicFetcher` et de ses classes de session. Nous avons retiré ce mode de ces classes et commencé à utiliser patchright dans `StealthyFetcher` et ses classes de session, avec BEAUCOUP d’améliorations, comme vous le verrez, qui renforcent la discrétion au-delà de ce que patchright apporte déjà.++**Cela rend `StealthyFetcher` et ses classes de session 101 % plus rapides, réduit leur utilisation de mémoire et d’espace et retire environ ~400 lignes de code. Surtout, ils sont plus stables que lorsque nous utilisions Camoufox.**++Cela réduit aussi le temps d’installation de la commande `scrapling install` et la taille de l’image Docker, améliore le déroulement des tests dans la CI de GitHub et rend scrapling moins déroutant pour les nouveaux utilisateurs.++### Changements incompatibles {#v0.3.13-breaking-changes}+1. L’argument `stealth` a été supprimé de `DynamicFetcher` et de sa classe de session, tandis que `hide_canvas` a été déplacé vers `StealthyFetcher` et ses classes de session.+2. L’argument `disable_webgl` a été déplacé de `DynamicFetcher` vers la classe `StealthyFetcher` et renommé `allow_webgl`. Cela vaut aussi pour toutes les classes de session.+3. La classe `StealthyFetcher` est désormais la nouvelle version furtive de `DynamicFetcher`. Les arguments suivants sont donc supprimés : `block_images`, `humanize`, `addons`, `os_randomize`, `disable_ads` et `geoip`. J’ai essayé de les reproduire dans Chromium, mais chacun posait un problème particulier. Cela pourrait changer dans les prochaines versions avant la v0.4.++Passons aux bonnes nouvelles : nous avons amélioré et corrigé beaucoup de choses :)++### Améliorations {#v0.3.13-improvements}+- Vous savez déjà que `StealthyFetcher` et ses classes de session sont 101 % plus rapides, mais `DynamicFetcher` et sa classe de session sont aussi 20 % plus rapides.+- L’algorithme de résolution des défis Cloudflare a été amélioré pour terminer plus vite et traiter plus de cas. Grâce à la réorganisation du code, attendez-vous aussi à une résolution des captchas deux fois plus rapide !+- Tous les fetchers utilisent désormais moins de mémoire.+- Le serveur MCP utilise moins de tokens pour vous faire économiser davantage !+- L’image Docker est désormais 60 % plus petite.+- Tout le site de documentation a été mis à jour avec les nouveautés. Les explications sont plus claires, de nombreuses sections ont été raccourcies, des exemples et des arguments manquants ont été ajoutés, la référence de l’API comprend des graphiques et de nombreuses autres améliorations ont été apportées. Le site charge désormais 130 % plus vite, utilise moins de données et est mieux adapté au référencement SEO.++### Corrections {#v0.3.13-fixes}+- Ajout des arguments manquants dans les raccourcis du shell de web scraping, et amélioration de leur précision.+- Correction d’un problème où `google_search` créait un referer Google même si l’URL pointait vers localhost ou une adresse IP.++## [v0.3.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.12) - 2025-12-18 {#v0.3.12}++### Ce qui a changé {#v0.3.12-what-s-changed}+- Ajout aux classes `DynamicSession`/`AsyncDynamicSession` d’un argument nommé `timezone_id`. Il permet de régler le fuseau horaire du navigateur pour qu’il corresponde à celui du proxy ou VPN utilisé. Les sites ne peuvent ainsi plus détecter le proxy grâce à une différence de fuseau horaire.+- Amélioration de la conversion automatique des réponses en JSON.+- La fonction interne `__create__` a été renommée `start` dans les classes de session des fetchers, pour faciliter leur utilisation hors du contexte `with`.+- Mise à jour de `curl_cffi` et d’autres dépendances vers les dernières versions.++## [v0.3.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.11) - 2025-12-03 {#v0.3.11}++### Ce qui a changé {#v0.3.11-what-s-changed}+- Amélioration de la gestion des erreurs de délai d’attente quand `network_idle` est utilisé sur un site instable, comme un site qui lit du contenu multimédia en continu.+- Correction de l’autocomplétion du raccourci `stealthy_fetch` dans le shell de web scraping++## [v0.3.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.10) - 2025-11-26 {#v0.3.10}++**Une mise à jour de maintenance avec de nombreux changements importants, dont certains peuvent être incompatibles**++- **Résolution** de tous les problèmes d’encodage grâce à une meilleure approche qui gère les pages dont l’encodage n’est pas déclaré correctement (Merci à @Kemsty2 pour ses efforts pour le signaler dans [#110](https://github.com/D4Vinci/Scrapling/issues/110) [#111](https://github.com/D4Vinci/Scrapling/pull/111) )+- **Résolution** d’un problème de logique dans le remplacement des paramètres de session par les paramètres de requête dans tous les fetchers de navigateur, présent depuis la v0.3+- **Correction** des signatures des raccourcis du shell interactif de web scraping, pour une autocomplétion complète de ces raccourcis. Ce problème existait lui aussi depuis la v0.3.+- **Mise à jour** de la version de la base de données Maxmind, ce qui améliore l’argument `geoip` de `StealthyFetcher` et de ses classes de session.+- **Mise à jour** de tous les navigateurs utilisés vers les dernières versions disponibles.+- **CHANGEMENTS INCOMPATIBLES** : Tous les fetchers ont fait l’objet d’une grande réorganisation, avec des changements intéressants qui pourraient affecter votre code :+ 1. Le code de Scrapling comporte désormais environ ~750 lignes de moins et de nombreux changements qui facilitent la maintenance future et réduisent un peu l’utilisation des ressources.+ 2. La validation de tous les fetchers et de leurs classes de session est beaucoup plus rapide, ce qui améliore leur vitesse globale.+ 3. Pour cela, les fetchers n’acceptent plus d’arguments positionnels autres que `url`. Tous les autres doivent être passés par leur nom. Votre code doit donc utiliser `Fetcher.get('https://google.com', stealthy_headers=True)` et non `Fetcher.get('https://google.com', True)`, si vous le faisiez ainsi pour une raison quelconque !+ 4. Depuis la v0.3, une différence gênante existait entre les fetchers de navigateur et leurs classes de session : l’argument qui permettait de configurer le parser par requête s’appelait `custom_config`, contre `selector_config` dans les classes de session. Cette réorganisation a permis d’unifier le nom en `selector_config` sans casser votre code. Le nom principal est donc maintenant `selector_config`, avec une compatibilité pour l’ancien argument `custom_config`. L’autocomplétion sera disponible uniquement pour `selector_config`.+ 5. Pour permettre tous ces changements, les annotations de types des fonctions des fetchers sont désormais générées dynamiquement. Si l’autocomplétion ne fonctionne pas correctement dans votre IDE, vérifiez que vous utilisez une version récente. Nous avons testé presque tous les IDE et éditeurs connus.++> Nous avons aussi mis à jour toutes les tables de performances avec les chiffres actuels, comparés aux dernières versions de toutes les bibliothèques alternatives.++## [v0.3.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.9) - 2025-11-17 {#v0.3.9}++**Une nouvelle mise à jour avec de nombreux changements importants**++### 🚀 Nouveautés et améliorations d’utilisation {#v0.3.9-new-stuff-and-quality-of-life-changes}+- L’argument `impersonate` de `Fetcher` et `FetcherSession` accepte désormais une liste de navigateurs. La bibliothèque en choisit un au hasard pour chaque requête.++```python+from scrapling.fetchers import FetcherSession++with FetcherSession(impersonate=['chrome', 'firefox', 'safari']) as s:+ s.get('https://github.com/D4Vinci/Scrapling')+```++- Un nouvel argument de la méthode `clean` de `TextHandler` permet de retirer facilement les entités HTML du texte actuel.+- Améliorations majeures de la documentation, avec des explications plus précises de nombreuses parties et des traductions automatiques du fichier `README.md` principal.++### 🐛 Corrections de bugs {#v0.3.9-bug-fixes}+- Correction d’un problème important lors de la récupération des réponses des fetchers de navigateur. Une détection intelligente du type de contenu garantit désormais que `response.body` contient le contenu rendu par le navigateur uniquement s’il s’agit de HTML. Sinon, il contient le contenu brut de la dernière requête. Cela permet de télécharger des fichiers binaires et texte sans les retrouver enveloppés dans des balises HTML, tout en pouvant récupérer le contenu rendu du site quand vous en avez besoin.++### 🔨 Autres changements {#v0.3.9-misc}+- Mise à jour du guide de contribution pour le rendre plus clair et plus simple.+- Ajout d’un workflow qui impose l’utilisation des outils de qualité du code, les mêmes que ceux utilisés comme hooks de pre-commit.++## [v0.3.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.8) - 2025-10-27 {#v0.3.8}++**Une nouvelle mise à jour avec de nombreux changements importants**++### 🚀 Nouveautés et améliorations d’utilisation {#v0.3.8-new-stuff-and-quality-of-life-changes}+- Dans tous les fetchers de navigateur, les sites dont les requêtes ne finissent jamais de charger ne font plus planter le code quand vous utilisez `network_idle`.+- Modification de la logique de collecte et de vérification du contenu des pages dans les fetchers de navigateur, pour rendre les navigateurs aussi stables sur Windows que sur Linux/MacOS. Cette différence de comportement vient de l’implémentation de Playwright sur Windows.+- Réorganisation de toute la logique de validation, ce qui accélère de 8-15 % les requêtes de tous les fetchers de navigateur+- Ajout de l’option `extra_flags` à `DynamicFetcher` et à sa session pour ajouter des options Chrome personnalisées aux options existantes au lancement du navigateur.+- Rétablissement de l’ancienne logique de routage pour capturer les réponses quand `page_action` est utilisé, après le changement de la version précédente. Cela permet de récupérer le dernier contenu de la page si `page_action` le modifie sans envoyer de requête. (Merci à @gembleman de l’avoir signalé dans [#100](https://github.com/D4Vinci/Scrapling/issues/100) et [#102](https://github.com/D4Vinci/Scrapling/pull/102) )++### 🐛 Corrections de bugs {#v0.3.8-bug-fixes}+- Correction d’une faute de frappe dans `load_dom` de la méthode async_fetch de DynamicSession+- Correction d’un problème de résolution des défis Cloudflare qui attendait indéfiniment la disparition des captchas intégrés restant visibles après leur résolution. L’attente est désormais de 30 secondes, après quoi le captcha est considéré comme un type qui ne disparaît pas (Corrige #100 )++### 🔨 Autres changements {#v0.3.8-misc}+- L’image Docker est désormais publiée automatiquement sur Dockerhub et dans le registre de conteneurs de GitHub pour faciliter son utilisation.+- Ajout d’une [nouvelle page de documentation](https://github.com/D4Vinci/Scrapling/blob/v0.3.8/docs/tutorials/external.md) expliquant comment utiliser le navigateur Scrapeless avec Scrapling.++## [v0.3.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.7) - 2025-10-12 {#v0.3.7}++**Une nouvelle mise à jour avec de nombreux changements importants**++### 🚀 Nouveautés et améliorations d’utilisation {#v0.3.7-new-stuff-and-quality-of-life-changes}+- Refonte de l’argument `solve_cloudflare` de `StealthyFetcher` pour résoudre tous les types d’implémentations personnalisées de Turnstile.+- Réorganisation de tout le code pour qu’il passe les contrôles de Pyright, ce qui améliore l’utilisation de tous les IDE et corrige de nombreux bugs.+- Réorganisation de la logique des requêtes pour la rendre plus claire et plus rapide (Résout aussi #97 )+- Ajout de l’option `user_data_dir` à toutes les classes de session de navigateur pour réutiliser les données de sessions précédentes, comme les cookies et le stockage. Si vous ne la renseignez pas, Playwright utilise un répertoire aléatoire à chaque exécution, comme auparavant.+- Ajout de l’option de personnalisation `additional_args` à `Dynamic fetcher` et à sa classe de session pour passer des arguments supplémentaires au contexte Playwright, comme c’était déjà possible avec `StealthyFetcher`.+- Amélioration de la logique de routage qui collecte la dernière réponse de navigation pour tous les navigateurs. Les réponses brutes peuvent ainsi parvenir au parser avant leur traitement par le navigateur, au lieu d’être traitées d’abord par celui-ci comme auparavant. C’est très utile pour les réponses texte et JSON.++### 🐛 Corrections de bugs {#v0.3.7-bug-fixes}+- La nouvelle logique de routage a résolu un problème de récupération du contenu de sites instables sur certains appareils Windows.+- Les réorganisations du code de cette version ont corrigé de nombreux bugs difficiles à repérer et des problèmes inhabituels d’autocomplétion dans certains IDE.+- Nombreuses corrections sur le site de documentation++## [v0.3.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.6) - 2025-10-01 {#v0.3.6}++### 🚀 Nouveautés {#v0.3.6-new-stuff}+- Amélioration de l’argument `solve_cloudflare` de `StealthyFetcher` et de ses classes de session pour résoudre tous les types de défis Turnstile et de pages intermédiaires Cloudflare 🎉+- Le serveur MCP permet désormais d’utiliser `Streamable HTTP` pour rendre le serveur facilement accessible.+- Ajout de la prise en charge de Docker. Une image contenant tous les navigateurs est créée et publiée automatiquement sur Docker Hub à chaque version++### 🐛 Corrections de bugs {#v0.3.6-bug-fixes}+- Correction d’un problème d’encodage du parser qui se produisait dans certains cas, la célèbre erreur `invalid start byte`+- Réorganisation de plusieurs parties de la bibliothèque pour corriger des fuites de mémoire. L’utilisation de la mémoire est désormais nettement plus faible selon votre configuration (Résout aussi #92 )+- Amélioration des annotations de types dans de nombreuses parties du code pour faciliter le travail dans l’IDE (Résout aussi #93 )++## [v0.3.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.5) - 2025-09-20 {#v0.3.5}++**Une version nécessaire qui corrige plusieurs problèmes**++### 🚀 Nouveautés {#v0.3.5-new-stuff}+- Tous les fetchers de navigateur (`DynamicFetcher`/`StealthyFetcher`/...) et leurs classes de session récupèrent désormais les pages 15-20 % plus vite :+ 1. La gestion des pages est beaucoup plus rapide grâce à l’amélioration de la logique par @AbdullahY36 dans #87+ 2. Optimisation de la logique de validation globale et amélioration de la création des pages pour les requêtes synchrones. Ensemble, ces changements ont apporté de nombreux gains de vitesse++- Améliorations majeures du mode furtif de `DynamicFetcher` et de ses classes de session grâce au remplacement de `rebrowser-playwright` par `PatchRight` :+ 1. Avant cette mise à jour, `rebrowser-playwright` était désactivé quand vous activiez `stealth` et `real_chrome`, car ils fonctionnaient mal ensemble. Ce problème n’existe plus avec `PatchRight`+ 2. Vous pouvez désormais interagir avec les Shadow Roots fermés, car `PatchRight` les gère automatiquement.++### 🐛 Corrections de bugs {#v0.3.5-bug-fixes}+- Correction d’un bug lors de l’utilisation de la méthode `re` de la classe `Selectors`.+- Correction d’un bug des commandes `uncurl` et `curl2fetcher` du shell de web scraping qui provoquait une mauvaise analyse de l’option `--data-raw` de curl.+- Correction d’un bug de la commande `view` du shell de web scraping qui apparaissait selon l’encodage du site.+- Correction d’un bug de conversion du contenu qui affectait le mode `mcp` et les commandes `extract`.++### Nouveaux contributeurs {#v0.3.5-new-contributors}+- @AbdullahY36 a fait sa première contribution dans #87++## [v0.3.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.4) - 2025-09-16 {#v0.3.4}++**Une version nécessaire qui corrige plusieurs problèmes**++### 🚀 Nouveautés {#v0.3.4-new-stuff}+- Ajout de toutes les classes de session des fetchers au shell interactif pour les utiliser immédiatement, sans importation.++### 🐛 Corrections de bugs {#v0.3.4-bug-fixes}+- Ajout d’une solution de contournement pour un bug de l’API Playwright sur Windows lors de la récupération du contenu pendant la résolution de défis Cloudflare.+- Correction d’un problème d’encodage de la commande `view` dans le shell interactif+- Correction d’un bug de l’argument `max_pages` dans `AsyncStealthySession` qui faisait planter le code.+- Correction d’un problème apparu avec les dernières mises à jour : les propriétés `html_content` et `prettify` de `Selector` renvoyaient des octets selon l’encodage. Elles renvoient de nouveau des chaînes de caractères.++## [v0.3.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.3) - 2025-09-15 {#v0.3.3}++- Suppression de la logique qui fermait l’onglet par défaut du navigateur dans les fetchers de navigateur, car elle provoquait un plantage. Le problème ne se produisait pas sur Mac et n’a pu être reproduit que sur Windows et Linux++## [v0.3.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.2) - 2025-09-15 {#v0.3.2}++Notes de la version v0.3.2++### 🚀 Nouveautés {#v0.3.2-new-stuff}++- **Dépendances facultatives des fetchers** : Tous les fetchers font désormais partie de groupes de dépendances facultatifs, ce qui réduit la taille du paquet de base. Le module de base `scrapling` ne contient plus que le parser. Pour utiliser les fetchers ou les options de ligne de commande, exécutez `pip install "scrapling[fetchers]"`. Consultez les instructions d’installation détaillées [ici](index.md#installation)+- **Configuration par page dans les sessions** : Les classes de session des fetchers de navigateur permettent désormais de configurer chaque page séparément. Tous les paramètres de requête sont maintenant validés comme les paramètres de session. Plus de détails sur le site de documentation [ici](fetching/stealthy.md#full-list-of-arguments)+ <br>Exemple :++ ```python+ with StealthySession(headless=True, solve_cloudflare=True) as session:+ page = session.fetch('https://nopecha.com/demo/cloudflare', google_search=False)+ ```++- **Amélioration des fetchers de navigateur**+ - Une nouvelle option permet de choisir s’il faut attendre la fin de l’exécution de JavaScript dans les pages. Elle est activée par défaut, comme auparavant++ ```python+ with DynamicSession(headless=True, disable_resources=False, network_idle=True) as session:+ page = session.fetch('https://quotes.toscrape.com/', load_dom=False)+ ```++ - Le mode furtif est désormais plus fiable dans `DynamicFetcher` et ses classes de session.+ - `DynamicFetcher` et `StealthyFetcher` utilisent moins de ressources en trouvant et en fermant automatiquement l’onglet par défaut ouvert par les contextes persistants de l’API Playwright+ - Correction d’un bug important dans la rotation des pages des fetchers de navigateur. Les anciennes pages sont désormais remplacées par des pages neuves, car les onglets réutilisés pouvaient garder des réglages de leurs utilisations précédentes+ - `StealthyFetcher` et ses classes de session sont désormais un peu plus rapides (5 %)++- **Amélioration de la propriété `.body`** : Elle renvoie désormais le contenu reçu tel quel, sans traitement. Cela permet de télécharger des fichiers et de gérer les requêtes qui ne renvoient pas du HTML. Voici un exemple de téléchargement d’image :++ ```python+ from scrapling.fetchers import Fetcher++ page = Fetcher.get('https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/poster.png')+ with open(file='poster.png', mode='wb') as f:+ f.write(page.body)+ ```++### 🐛 Corrections de bugs {#v0.3.2-bug-fixes}++- **Problèmes d’encodage résolus** : Correction de plusieurs problèmes d’encodage avec certains sites dans le parser, le mode mcp et les commandes extract (Résout aussi #80 et #81)+- **Analyse plus rapide** : Grâce à de nombreux changements dans différentes parties, la bibliothèque est désormais plus rapide, comme le montrent les tests de performances mis à jour++### 🔨 Autres changements {#v0.3.2-misc}++- **Tests de performances mis à jour** : Actualisation des mesures pour comparer les gains de vitesse actuels aux dernières versions de bibliothèques similaires+- **Réorganisation d’une grande partie du code et remplacement du code inutilisé par de meilleures implémentations** : Moins de code, plus clair et plus facile à maintenir+- **Ajout d’une vidéo YouTube** : Ajout de contenu vidéo à la documentation MCP.+- **Nouveau modèle d’issue** : Un modèle simple pour les utilisateurs qui ne peuvent pas utiliser les modèles actuels.+- **Optimisation du workflow de CI** : Le workflow de tests ignore désormais les exécutions où seuls la documentation ou d’autres fichiers sans code ont changé.+- **Dépendances mises à jour** : Mise à jour de plusieurs dépendances vers les dernières versions.+- **Améliorations du style de code** : Application de nouvelles règles ruff dans tous les fichiers.+- **Hooks de pre-commit** : Mise à jour de la configuration de pre-commit.++### 🎯 Changements incompatibles {#v0.3.2-breaking-changes}++- Suppression du paramètre `max_pages` de la version synchrone de `StealthySession` pour l’aligner sur `DynamicSession`, car il n’a pas d’utilité dans la version synchrone++## [v0.3.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.1) - 2025-09-02 {#v0.3.1}++1. Correction d’un problème d’installation de scrapling sans l’extra `shell` (#76 )+2. Ajout d’un argument à tous les fetchers de navigateur et à leurs classes de session pour passer un fichier JS à exécuter lors de la création de la page (#56) :++```python+from scrapling.fetchers import StealthyFetcher++StealthyFetcher.fetch('https://example.com', init_script="/absolute/path/to/js/script.js")+```++## [v0.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3) - 2025-09-01 {#v0.3}++🎉 **Version majeure - Refonte complète de l’architecture**++Scrapling v0.3 est la plus grande mise à jour de l’histoire du projet. Elle comprend une réécriture complète de l’architecture, d’importants gains de performances et de nouvelles fonctions puissantes, dont l’intégration avec l’IA et un shell interactif de web scraping.++Cette version comporte plusieurs changements incompatibles. Lisez attentivement les notes de version.++### 🚀 Principales nouveautés {#v0.3-major-new-features}++#### Architecture basée sur les sessions {#v0.3-session-based-architecture}+- **Nouvelles classes de session** : Réécriture complète qui ajoute la prise en charge des sessions persistantes+ - `FetcherSession` - Requêtes HTTP avec conservation de l’état, pour le code synchrone comme asynchrone+ - `DynamicSession`/`AsyncDynamicSession` - Automatisation du navigateur, qui reste ouvert jusqu’à ce que vous ayez terminé+ - `StealthySession`/`AsyncStealthySession` - Navigation discrète, avec un navigateur qui reste ouvert jusqu’à ce que vous ayez terminé+- **Gestion asynchrone des onglets du navigateur** : Nouveau groupe d’onglets via l’argument `max_pages`, qui alterne entre les onglets pour effectuer des requêtes simultanées avec le navigateur+- **Sessions simultanées** : Exécutez plusieurs sessions isolées en même temps++Consultez la section `Fetching` du site pour plus de détails.++#### De nombreuses fonctions pour masquer l’automatisation et contourner les protections antibots {#v0.3-a-lot-of-new-stealth-anti-bot-capabilities}+- **🤖 Résolution des défis Cloudflare** : [Résolution automatique des défis Cloudflare Turnstile](fetching/stealthy.md#cloudflare-and-stealth-options) dans `StealthyFetcher` et ses classes de session+- **Imitation des empreintes du navigateur** : Imitez les empreintes TLS de vrais navigateurs, utilisez des en-têtes qui correspondent à leur version, profitez de HTTP/3 et plus encore avec la toute nouvelle classe [Fetcher](fetching/static.md)+- **Mode discret amélioré** : Le mode discret de `DynamicFetcher` et de ses classes de session est désormais plus robuste et fiable (également connu sous le nom `PlayWrightFetcher`)++#### Intégration avec l’IA et serveur MCP {#v0.3-ai-integration-mcp-server}+- **Serveur MCP intégré** : Serveur Model Context Protocol pour le web scraping assisté par IA+- **6 outils puissants** : `get`, `bulk_get`, `fetch`, `bulk_fetch`, `stealthy_fetch`, `bulk_stealthy_fetch`+- **Extraction intelligente du contenu** : Convertissez des pages ou éléments web en Markdown ou HTML, ou extrayez une version propre du texte+- **Prise en charge des sélecteurs CSS** : Utilisez le moteur de Scrapling pour cibler précisément des éléments avant de transmettre le contenu à l’IA+- **Contournement des protections antibots** : Gérez Cloudflare Turnstile et d’autres protections+- **Prise en charge des proxies** : Utilisez des proxies pour préserver l’anonymat et choisir la localisation géographique+- **Imitation des navigateurs** : Imitez de vrais navigateurs avec leurs empreintes TLS, des en-têtes réels qui correspondent à leur version et plus encore+- **Traitement en parallèle** : Extrayez les données de plusieurs URL simultanément pour gagner en efficacité+- [et plus encore...](ai/mcp-server.md)++#### Nouveau shell interactif de web scraping {#v0.3-new-interactive-web-scraping-shell}+- **Nouveau shell** : Shell IPython personnalisé avec de nombreux raccourcis intelligents intégrés, comme `get`, `post`, `put`, `delete`, `fetch` et `stealthy_fetch`+- **Gestion intelligente des pages** : Nouvelles commandes `page` et `pages` pour conserver automatiquement la page actuelle et l’historique de toutes les requêtes faites depuis le shell+- **Intégration avec Curl** : Utilisez les fonctions `uncurl` et `curl2fetcher` pour convertir les commandes curl des outils de développement du navigateur en requêtes `Fetcher`+- [et plus encore...](cli/interactive-shell.md)++#### Extraire des données depuis le terminal sans programmer {#v0.3-scrape-from-the-terminal-without-programming}+- **Nouvelles commandes d’extraction** : Extrayez des données depuis le terminal sans programmer+ - `scrapling extract get/post/put/delete` - Requêtes HTTP simples+ - `scrapling extract fetch` - Extraction de contenu dynamique+ - `scrapling extract stealthy-fetch` - Contournement des protections antibots+- **Télécharge des pages web** et enregistre leur contenu dans des fichiers.+- **Convertit le HTML en formats lisibles**, comme Markdown, le conserve en HTML ou extrait uniquement le texte de la page.+- **Accepte des sélecteurs CSS personnalisés** pour extraire des parties précises de la page.+- **Gère les requêtes HTTP et la récupération de pages avec un navigateur.**+- **De nombreuses options de personnalisation**, avec des en-têtes, cookies, proxies et autres réglages. Presque toutes les options disponibles dans le code sont aussi accessibles depuis le terminal.+- [et plus encore...](cli/extract-commands.md)++### 🔧 Améliorations techniques {#v0.3-technical-improvements}++#### Améliorations des performances {#v0.3-performance-enhancements}+- **Fetcher est désormais 4 fois plus rapide** - Oui, vous avez bien lu !+- **DynamicFetcher est désormais ~60 % plus rapide** - Une version bien plus rapide selon votre configuration (surtout le mode discret)+- **StealthyFetcher est désormais 20–30 % plus rapide** - Grâce à la nouvelle structure et à l’adoption de notre propre code à la place de l’interface Python de `Camoufox`+- **Gain de vitesse cumulé de 50 %+** sur les principales méthodes de sélection (`find_by_text`, `find_similar`, `find_by_regex`, `relocate`, etc.) 🚀+- **Gain de vitesse de ~10 % pour les méthodes qui récupèrent la première correspondance CSS/XPath** - `css_first` et `xpath_first` sont désormais plus rapides que `css` et `xpath`+- **La méthode `get_all_text()` est 40 % plus rapide** pour extraire du contenu+- **Gain de vitesse de 20 %** pour retrouver les éléments de façon adaptative+- **Optimisation des propriétés de navigation** - Des propriétés comme `next`, `previous`, `below_elements` et d’autres sont désormais nettement plus rapides+- **Nettoyage du texte 5 fois plus rapide**+- **Meilleure utilisation de la mémoire** grâce à des importations optimisées et à moins de traitements supplémentaires+- **⚡ Importations très rapides** : Démarrage plus rapide grâce à un chargement optimisé des modules+- **De meilleurs résultats aux tests de performances** : Tous ces gains rendent Scrapling bien plus rapide qu’avant face aux autres bibliothèques (1775 fois plus rapide que BeautifulSoup et 5,1 fois plus rapide qu’AutoScraper ; consultez les [tests de performances](benchmarks.md))++#### Architecture, qualité du code et améliorations d’utilisation {#v0.3-architecture-code-quality-and-quality-of-life}+- **Contexte persistant** : Tous les fetchers basés sur un navigateur utilisent désormais un contexte persistant par défaut. (Résout aussi #64)+- **Utilisation de msgspec pour valider très vite la configuration de tous les fetchers basés sur un navigateur** avant d’exécuter les requêtes, ce qui facilite la recherche d’erreurs.+- **Tous les cookies** renvoyés par les fetchers ont désormais le format accepté par le même fetcher. Vous pouvez donc récupérer des cookies et les transmettre à nouveau à tous les fetchers et à leurs classes de session.+- **Vérification et mise en forme du code plus rapides** après la migration vers `ruff`+- **Système de build moderne** : Migration de setup.py vers pyproject.toml 📦+- **Amélioration des actions et workflows GitHub** pour faciliter le développement et les tests+- **🎨 Meilleures annotations de types** : Couverture complète des types selon les normes modernes de Python pour améliorer la prise en charge par les IDE et la fiabilité+- **Code plus propre** : Suppression du code inutilisé et optimisation des fonctions principales 🧹+- **🚀 Compatibilité avec les versions précédentes** : Ajout de raccourcis pour préserver la compatibilité avec l’ancien code++### Changements incompatibles {#v0.3-breaking-changes}++#### Version minimale de Python {#v0.3-minimum-python-version}+- **Python 3.10+ requis** : Fin de la prise en charge de Python 3.9 et des versions précédentes++#### Noms des classes et des méthodes {#v0.3-class-and-method-naming}+Ces changements de noms visent à apporter plus de clarté et de cohérence, surtout pour les nouveaux utilisateurs.++- **`Adaptor` → `Selector`** : La classe principale d’analyse a été renommée (vous pouvez toujours l’importer sous le nom `Adaptor` pour préserver la compatibilité)+- **`Adaptors` → `Selectors`** : La classe de collection a été renommée (vous pouvez toujours l’importer sous le nom `Adaptors` pour préserver la compatibilité)+- **`auto_match` → `adaptive`** : Le paramètre a été renommé dans toutes les méthodes+- **`adaptor_arguments` → `selector_config`** : Le paramètre de configuration a été renommé+- **`automatch_domain` → `adaptive_domain`** : Le paramètre de domaine a été renommé+- **`additional_arguments` → `additional_args`** : Le nom du paramètre a été raccourci+- **⚠️ `text/body` → `content`** : Le paramètre du constructeur de Selector accepte désormais `str` et `bytes`+- **`PlayWrightFetcher` → `DynamicFetcher`** : La classe d’automatisation du navigateur a été renommée (vous pouvez toujours l’importer sous le nom `PlayWrightFetcher` pour préserver la compatibilité)+- **DynamicFetcher ne contient plus la logique ni les arguments de NSTBrowser**, car il n’y a plus de raison de les conserver.+- **L’argument headless de StealthyFetcher n’accepte plus 'virtual'** car nous utilisons désormais la bibliothèque Camoufox uniquement pour obtenir le chemin d’installation du navigateur et les autres options de lancement++### 🐛 Corrections de bugs {#v0.3-bug-fixes}++- Correction du comptage des enfants imbriqués dans les balises ignorées par `get_all_text` (#61)+- Correction du problème d’installation causé par les espaces dans le chemin de l’exécutable Python (#57)+- Résolution des problèmes de threads dans le stockage, avec gestion de la récursion lorsque la fonction adaptative est activée+- Correction des problèmes de priorité des arguments avec le modèle Sentinel dans `FetcherSession`+- Correction de la gestion des types de proxies dans `StealthyFetcher`+- Correction des conflits entre les arguments `referer` et `google_search`+- Correction des problèmes d’injection asynchrone des scripts du mode discret++## [v0.2.99](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.99) - 2025-04-08 {#v0.2.99}++**Cette mise à jour est importante pour profiter pleinement de Scrapling tel qu’il a été conçu.**++### Ce qui a changé {#v0.2.99-what-s-changed}+#### Nouveau site avec toute la documentation {#v0.2.99-new-full-documentation-website}+- Oui, enfin 😄 Découvrez-le [ici](index.md)+#### Importation unifiée des fetchers {#v0.2.99-unified-import-logic-for-fetchers}+- Vous pouvez désormais importer tous les fetchers avec `from scrapling.fetchers import Fetcher, AsyncFetcher, StealthyFetcher, PlayWrightFetcher`, puis les utiliser directement, comme dans `page = Fetcher.get(...)`, sans créer d’instance.<br/> Cela remplace l’ancienne importation `from scrapling.defaults import Fetcher, AsyncFetcher, StealthyFetcher, PlayWrightFetcher`.+#### Changement incompatible : automatch est désormais désactivé par défaut {#v0.2.99-breaking-change-automatch-is-now-turned-off-by-default}+- Une nouvelle logique permet d’activer automatch depuis les fetchers ou les autres options d’analyse. Consultez la [documentation](fetching/choosing.md#parser-configuration-in-all-fetchers) pour plus de détails.+> Les anciennes importations et l’ancienne logique restent utilisables, avec un avertissement, pour préserver la compatibilité.+#### Nouvelles options pour les fetchers {#v0.2.99-new-options-added-to-fetchers}+- `StealthyFetcher` et `PlayWrightFetcher` ont désormais un nouvel argument appelé `wait` pour récupérer des pages. Il fait attendre le fetcher pendant une durée définie en millisecondes avant de fermer la page et de vous renvoyer la réponse.+- Les méthodes de `StealthyFetcher` nommées `fetch` et `async_fetch` acceptent désormais l’argument `additional_arguments` pour transmettre des réglages supplémentaires à Camoufox. Ils ont priorité sur les réglages de Scrapling (#54 )+#### Corrections de bugs {#v0.2.99-bugs-squashed}+- Correction d’un bug de détection des redirections dans `async_fetch` des classes `StealthyFetcher` et `PlayWrightFetcher`.++**_Merci pour votre soutien et vos dons !_**++## [v0.2.98](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.98) - 2025-03-17 {#v0.2.98}++**Cette mise à jour est importante pour profiter pleinement de Scrapling tel qu’il a été conçu**++### Ce qui a changé {#v0.2.98-what-s-changed}+#### Améliorations de la consommation de mémoire et de la vitesse {#v0.2.98-various-memory-usage-and-speed-optimizations}+- Les méthodes de sélection utilisent désormais ~40 % de la mémoire utilisée auparavant, avec un léger gain de vitesse.+- Le chargement à la demande s’applique à tous les sous-modules de la bibliothèque : seuls les modules utilisés sont chargés. Par exemple :+Avant la mise à jour, l’importation `from scrapling import Adaptor` utilisait `30-40mb` de RAM car elle chargeait aussi tous les fetchers et d’autres composants. Elle utilise désormais `~1.2mb`.+- La dernière mise à jour réduisait la consommation de la bibliothèque à ~32 % de la mémoire utilisée auparavant avec un grand groupe de requêtes. Nous avons encore ajusté le cache pour utiliser moins de mémoire.+- Léger gain de vitesse global du parser, de 2-5 %++**_Merci pour votre soutien et vos dons !_**++## [v0.2.97](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.97) - 2025-03-15 {#v0.2.97}++**Cette mise à jour est importante pour profiter pleinement de Scrapling tel qu’il a été conçu**++### Ce qui a changé {#v0.2.97-what-s-changed}+#### Moins de mémoire utilisée et un léger gain de vitesse pour tous les fetchers {#v0.2.97-lower-memory-usage-and-small-speed-increase-across-all-fetchers}+- Les nouvelles limites de taille du cache dans toute la bibliothèque réduisent nettement la consommation de mémoire lors de nombreuses requêtes ou opérations.+- Réorganisation de grandes parties des fetchers pour faciliter leur maintenance et augmenter légèrement leur vitesse.++#### Corrections de bugs {#v0.2.97-bugs-fixed}+- Correction d’un bug de `TextHandler` qui transformait une valeur non textuelle en chaîne vide lorsque cette classe était importée seule. Toute valeur transmise à `TextHandler` est désormais convertie en chaîne, puis en `TextHandler`. Cela s’applique à toutes les valeurs : après tout, `TextHandler`, comme son nom l’indique, est conçu uniquement pour le texte ! (#45 )+- Correction d’un bug qui faisait ignorer l’argument `retries` par la plupart des méthodes d’AsyncFetcher.++#### Autres changements {#v0.2.97-miscellaneous}+- Mise à jour des annotations de types de la plupart des arguments dans tous les fetchers pour les rendre plus claires et précises.++**_Merci pour votre soutien et vos dons !_**++## [v0.2.96](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.96) - 2025-03-05 {#v0.2.96}++**Cette mise à jour est importante pour profiter pleinement de Scrapling tel qu’il a été conçu**++### Ce qui a changé {#v0.2.96-what-s-changed}+1. Ajout de l’option `-f` à `scrapling install` pour forcer la réinstallation des dépendances du navigateur. Je vous recommande d’exécuter `scrapling install -f` maintenant pour profiter du grand gain de vitesse de `StealthyFetcher` avec la nouvelle version du navigateur Camoufox :)+2. Correction d’un bug de `TextHandler` qui renvoyait `TextHandlers` au lieu de `TextHandler` lors de l’extraction d’une portion du texte, et correction de l’annotation de type correspondante (#41 )+3. Correction d’un problème qui pouvait faire ouvrir un shell Python par `scrapling install` dans certains cas !++## [v0.2.95](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.95) - 2025-02-25 {#v0.2.95}++**Cette mise à jour est importante pour profiter pleinement de Scrapling tel qu’il a été conçu**++### Ce qui a changé {#v0.2.95-what-s-changed}+1. Correction d’un bug de `Fetcher` : les en-têtes générés avec l’argument `stealthy_headers` écrasaient certains en-têtes fournis par l’utilisateur, comme `Accept` (#39 )+2. Légère amélioration de la logique de génération des en-têtes, qui devrait apporter un petit gain de vitesse.++## [v0.2.94](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.94) - 2025-02-22 {#v0.2.94}++**Cette mise à jour est importante pour profiter pleinement de Scrapling tel qu’il a été conçu**++### Ce qui a changé {#v0.2.94-what-s-changed}+1. Ajout de la propriété `history` à tous les fetchers pour afficher les redirections (#32 )+2. Correction de la logique de l’argument `case_sensitive` dans toutes les méthodes `re`/`re_first`. Si vous l’utilisiez, les résultats de votre code peuvent changer (mais vous l’avez peut-être mérité en voyant que cela ne fonctionnait pas comme prévu sans ouvrir d’issue, haha)+3. Mise à jour des dépendances et réactivation de `coop` dans le moteur Camoufox (StealthyFetcher).++## [v0.2.93](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.93) - 2025-01-31 {#v0.2.93}++**Cette mise à jour est importante pour profiter pleinement de Scrapling tel qu’il a été conçu**++### Ce qui a changé {#v0.2.93-what-s-changed}+1. Le type de retour est désormais cohérent dans tout le moteur d’analyse. Vous recevrez toujours un de ces types : `Adaptor`, `Adaptors`, `TextHandler`, `TextHandlers`, `None`, ou une liste si les résultats sont mixtes, comme avec un sélecteur CSS combiné. Cela facilite la programmation avec moins de vérifications manuelles des types, rend la bibliothèque plus stable et permet de toujours enchaîner les méthodes.+2. Réorganisation de la majeure partie du moteur d’analyse, surtout de la classe `Adaptor`, pour le rendre plus propre et surtout plus rapide. Presque toutes les méthodes et propriétés, notamment celles de recherche, gagnent 5-40 % de vitesse. Certaines gagnent davantage, comme `find_by_regex`, avec ~60 % de gain ! La fonction automatch gagne environ ~5 %.+3. Correction de bugs dans la logique de `find_all`/`find` qui appliquait les filtres avec OR dans certains cas et avec AND dans d’autres. Tous les éléments renvoyés doivent désormais satisfaire tous les filtres transmis.+4. Toutes les méthodes liées aux expressions régulières renvoient désormais `TextHandler`/`TextHandlers` pour faciliter l’enchaînement des méthodes.+5. **Ajout d’une nouvelle** propriété `below_elements`, qui renvoie un objet `Adaptors` contenant tous les éléments sous l’élément actuel dans l’arbre DOM.+6. Toutes les méthodes et propriétés qui renvoyaient du code HTML sous forme de chaîne le renvoient désormais comme `TextHandler`, pour faciliter l’utilisation des expressions régulières et d’autres opérations...+7. StealthyFetcher est désormais un peu plus rapide et discret. Vous pouvez aussi cliquer sur les CAPTCHA dans des iframes, comme **Cloudflare Turnstile**.+8. L’autocomplétion et les annotations de types sont nettement améliorées dans près de la moitié de la bibliothèque, surtout dans `Adaptor`, `TextHandler` et `TextHandlers`.+9. Extraire une portion de `TextHandler`, accéder à un caractère par son indice ou utiliser la méthode `split` renvoie désormais un autre `TextHandler` au lieu d’une chaîne Python standard. Presque toutes les opérations et méthodes standard de chaînes renvoient un autre `Texthandler` pour toujours permettre l’enchaînement des méthodes et fonctions.+10. Correction de petits bugs et de fautes de frappe. Par exemple, async_put de Fetcher envoyait une requête post au lieu d’une requête put 😶🌫️+11. Petite amélioration du README en attendant que je termine le site de documentation.++Cela devait être une petite mise à jour avant la version 0.3, mais j’ai décidé de l’améliorer davantage.++## [v0.2.92](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.92) - 2024-12-26 {#v0.2.92}++### Ce qui a changé {#v0.2.92-what-s-changed}+- Les réponses des fetchers basés sur un navigateur utilisent désormais des sources de données plus fiables lorsque la page chargée contient beaucoup d’iframes.+- **Installer `Scrapling` est encore plus simple : installez-le avec pip, exécutez `scrapling install` dans le terminal, et c’est prêt !**+- Correction d’une annotation de type imprécise dans le parser.++## [v0.2.91](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.91) - 2024-12-19 {#v0.2.91}++### Ce qui a changé {#v0.2.91-what-s-changed}+- Correction d’un bug qui faisait apparaître le message de journal de récupération de page uniquement lors de la première requête.+- Par défaut, l’API de Playwright renvoie la première réponse qui satisfait l’état de chargement transmis à la méthode `goto` : `["load", "domcontentloaded", "networkidle"]`. Si un site affiche une page d’attente, comme celle de Cloudflare, qui redirige ensuite vers le vrai site, Playwright renvoie le premier code de statut, par exemple 403. Cette mise à jour résout ce problème dans `PlaywrightFetcher` et `StealthyFetcher`, qui utilisent tous deux l’API de Playwright. Le résultat ne dépend plus de ce comportement par défaut.+- Ajout de la prise en charge des proxies SOCKS dans la classe `Fetcher`.+- Correction de l’annotation de type de l’argument `wait_selector_state` pour que l’autocomplétion affiche les valeurs correctes à utiliser.++## [v0.2.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.9) - 2024-12-16 {#v0.2.9}++### Ce qui a changé {#v0.2.9-what-s-changed}+##### Nouvelles fonctionnalités {#v0.2.9-new-features}+1. Voici le support asynchrone **tant attendu** dans Scrapling ! Vous disposez désormais de `AsyncFetcher`, la version asynchrone de `Fetcher`, et `StealthyFetcher` comme `PlayWrightFetcher` proposent une nouvelle méthode `async_fetch` avec les mêmes options.++```python+>> from scrapling import StealthyFetcher+>> page = await StealthyFetcher().async_fetch('https://www.browserscan.net/bot-detection') # the async version of fetch+>> page.status == 200+True+```++2. La classe `StealthyFetcher` possède désormais l’argument `geoip` dans ses méthodes de récupération. Lorsqu’il est activé, elle utilise automatiquement la longitude, la latitude, le fuseau horaire, le pays et les paramètres régionaux de l’IP, puis modifie l’adresse IP exposée par WebRTC. Elle détermine et simule aussi la langue du navigateur selon la répartition des locuteurs dans la région ciblée.+3. Ajout de l’argument `retries` aux classes `Fetcher`/`AsyncFetcher` pour définir le nombre de nouvelles tentatives de chaque requête effectuée par `httpx`.+4. Ajout de la méthode `url_join` à `Adaptor` et aux fetchers. Elle combine une URL relative avec l’URL actuelle pour créer une URL absolue complète !+5. Ajout de la méthode `keep_cdata` à `Adaptor` et aux fetchers pour empêcher le parser de supprimer cdata lorsque vous souhaitez le conserver.+6. Dans `Adaptor`/`Response`, la méthode `body` renvoie désormais la réponse HTML brute quand c’est possible, sans traitement dans la bibliothèque.+7. Ajout de la journalisation à la classe `Response`. Quand vous utilisez les fetchers, vous recevez désormais un journal avec des informations sur la réponse.+Exemple :++ ```python+ >> from scrapling.defaults import Fetcher+ >> Fetcher.get('https://books.toscrape.com/index.html')+ [2024-12-16 13:33:36] INFO: Fetched (200) <GET https://books.toscrape.com/index.html> (referer: https://www.google.com/search?q=toscrape)+ >>+ ```++8. Utiliser des méthodes standard de chaînes sur un `TextHandler`, comme `.replace()`, renvoie désormais un autre `TextHandler`. Elles renvoyaient auparavant une chaîne standard.+9. Gains de vitesse importants dans toute la bibliothèque et amélioration de la discrétion des classes de fetchers en général.+10. Ajout de fonctions de compatibilité comme `extract_first`\`extract`, qui renvoient le même résultat que l’objet d’origine. Elles servent uniquement à faciliter la copie de code de Scrapy/Parsel vers Scrapling si nécessaire, car ces fonctions y sont utilisées !+11. Les requêtes par lots sont désormais beaucoup plus rapides grâce à la réorganisation d’une grande partie du code et à l’utilisation du cache aux bons endroits.++##### Changements incompatibles {#v0.2.9-breaking-changes}+- Fin de la prise en charge de Python 3.8. (Surtout parce que Playwright ne le prend plus en charge, mais cette version posait déjà des problèmes)+- L’argument `debug` a été retiré de toute la bibliothèque. Pour activer le débogage, faites ceci après l’avoir importée :++ ```python+ >>> import logging+ >>> logging.getLogger("scrapling").setLevel(logging.DEBUG)+ ```++##### Corrections de bugs {#v0.2.9-bugs-squashed}+1. WebGL est désormais activé par défaut, car de nombreuses protections vérifient s’il est actif.+2. Correction de quelques erreurs et fautes de frappe dans la documentation et le README.++##### Améliorations d’utilisation {#v0.2.9-quality-of-life-changes}+1. Tous les journaux utilisent désormais le logger nommé `scrapling` pour simplifier leur contrôle. Nous utilisions auparavant le logger racine.+2. Réorganisation du dossier des tests pour le rendre plus clair et ajout de tests pour les nouvelles fonctions. Tous les tests ont été réécrits plus proprement, et de nouveaux tests augmentent la couverture.+3. Réorganisation d’une grande partie du code pour le rendre plus propre et plus facile à maintenir.++> Tous ces changements étaient prévus pour la version 0.3, mais j’ai décidé de les inclure ici car la prochaine version prendra encore du temps. La prochaine étape est de terminer le site de documentation détaillée, puis de travailler sur la version 0.3++## [v0.2.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.8) - 2024-11-30 {#v0.2.8}++### Ce qui a changé {#v0.2.8-what-s-changed}+- Petite mise à jour avec des améliorations d’utilisation nécessaires dans le code et la correction d’une faute de frappe dans le README principal (#20)++## [v0.2.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.7) - 2024-11-26 {#v0.2.7}++### Ce qui a changé {#v0.2.7-what-s-changed}+##### Nouvelles fonctionnalités {#v0.2.7-new-features}+- Si vous utilisez l’argument `wait_selector` avec les classes `StealthyFetcher` et `PlayWrightFetcher`, Scrapling attend de nouveau le chargement et l’exécution complets du JS, comme d’habitude. Si vous utilisez `network_idle`, il attend aussi de nouveau cet état après tout cela. Bien sûr, si tous les états sont déjà satisfaits, il n’attend pas.+- Vous pouvez désormais activer ou désactiver les publicités dans `StealthyFetcher` avec l’argument `disable_ads`. Le blocage est activé par défaut et installe l’extension `ublock origin`.+- Vous pouvez désormais définir les paramètres régionaux de `PlayWrightFetcher` avec l’argument `locale`. La valeur par défaut reste `en-US`.+- Les requêtes simples effectuées par `Fetcher` acceptent désormais des proxies au format `http://username:password@localhost:8030`.+- Légère amélioration du mode discret de `PlayWrightFetcher`.++##### Corrections de bugs et améliorations {#v0.2.7-bugs-squashed-improvements}+1. L’activation des proxies dans la classe `PlayWrightFetcher` ne dépend plus de l’activation ou non du mode `stealth` (merci à [@AbdullahY36](https://github.com/AbdullahY36) pour le signalement)+2. `ResponseEncoding` vérifie désormais si l’encodage indiqué dans la réponse peut être utilisé avec la page. Si cet encodage provoque une erreur, Scrapling utilise `utf-8` par défaut++## [v0.2.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.6) - 2024-11-24 {#v0.2.6}++### Ce qui a changé {#v0.2.6-what-s-changed}+##### Nouvelles fonctionnalités {#v0.2.6-new-features}+- `PlayWrightFetcher` peut désormais utiliser directement le vrai navigateur en passant `real_chrome` à la fonction `PlayWrightFetcher.fetch`, à condition que Chrome soit installé. Scrapling ouvre une instance de votre navigateur Chrome, et vous pouvez utiliser la plupart des options comme d’habitude. (Auparavant, seul l’argument `cdp_url` permettait de le faire)+- Mise à jour de la version indiquée dans les en-têtes générés pour les vrais navigateurs.++##### Corrections de bugs {#v0.2.6-bugs-squashed}+1. Le format des en-têtes de navigateur générés par `BrowserForge` était dépassé, ce qui permettait à certaines protections de détecter Scrapling. `BrowserForge` sert désormais uniquement à générer un useragent réel.+2. L’argument `hide_canvas` est désormais désactivé par défaut car ReCaptcha de Google le détecte.++## [v0.2.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.5) - 2024-11-23 {#v0.2.5}++### Ce qui a changé {#v0.2.5-what-s-changed}++##### Corrections de bugs {#v0.2.5-bugs-squashed}+- Gestion d’une erreur de l’argument 'wait_selector' lorsqu’il correspond à plus de 1 élément. Cela concerne les classes `StealthyFetcher` et `PlayWrightFetcher`.+- Correction du type d’encodage lorsque la valeur de l’en-tête `content_type` contient des paramètres comme `charset` (merci à @andyfcx pour [#12](https://github.com/D4Vinci/Scrapling/issues/12) )++##### Améliorations d’utilisation {#v0.2.5-quality-of-life}+- Ajout de tests pour couvrir de nouvelles parties du code et exécution des tests dans des threads.+- Mise à jour des docstrings pour qu’ils s’affichent correctement dans apidoc de Sphinx et les outils similaires.++##### Nouveaux contributeurs {#v0.2.5-new-contributors}+- @andyfcx a fait sa première contribution dans [#13 ](https://github.com/D4Vinci/Scrapling/pull/13)++## [v0.2.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.4) - 2024-11-20 {#v0.2.4}++### Ce qui a changé {#v0.2.4-what-s-changed}++##### Corrections de bugs {#v0.2.4-bugs-squashed}+- Correction d’un bug lors de la récupération des octets de la réponse après l’utilisation de `network_idle` dans les classes `StealthyFetcher` et `PlayWrightFetcher`. <br/> Cela provoquait le message d’erreur suivant :++ ```+ Response.body: Protocol error (Network.getResponseBody): No resource with given identifier found+ ```++- L’API de PlayWright renvoie parfois des réponses avec un texte de statut vide. `Scrapling` le détermine désormais lui-même dans ce cas. Cela concerne les classes `StealthyFetcher` et `PlayWrightFetcher`.++## [v0.2.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.3) - 2024-11-19 {#v0.2.3}++### Ce qui a changé {#v0.2.3-what-s-changed}++##### Corrections de bugs {#v0.2.3-bugs-squashed}+- Correction d’un bug d’installation avec pip qui empêchait complètement le mode discret de PlayWright Fetcher de fonctionner.++## [v0.2.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.2) - 2024-11-16 {#v0.2.2}++### Ce qui a changé {#v0.2.2-what-s-changed}+##### Nouvelles fonctionnalités {#v0.2.2-new-features}+- Si vous ne souhaitez pas transmettre d’arguments à l’objet `Adaptor` créé et préférez les valeurs par défaut, vous pouvez utiliser cette importation pour simplifier le code++ ```python+ >> from scrapling.default import Fetcher, StealthyFetcher, PlayWrightFetcher+ >> page = Fetcher.get('https://example.com', stealthy_headers=True)+ ```++ Sinon++ ```python+ >> from scrapling import Fetcher, StealthyFetcher, PlayWrightFetcher+ >> page = Fetcher(auto_match=False).get('https://example.com', stealthy_headers=True)+ ```++##### Corrections de bugs {#v0.2.2-bugs-squashed}+1. Correction d’un bug de l’objet `Response`, apparu avec le correctif v0.2.1 d’hier, dans certains cas de sélection ou d’analyse imbriquées.++## [v0.2.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.1) - 2024-11-15 {#v0.2.1}++### Ce qui a changé {#v0.2.1-what-s-changed}+##### Nouvelles fonctionnalités {#v0.2.1-new-features}+1. L’objet `Response` renvoyé par tous les fetchers est désormais identique à l’objet `Adaptor`, avec les attributs supplémentaires suivants : `status`, `reason`, `cookies`, `headers` et `request_headers`. Les attributs `cookies`, `headers` et `request_headers` sont toujours de type `dictionary`. <br/>Votre code peut donc devenir :++ ```python+ >> from scrapling import Fetcher+ >> page = Fetcher().get('https://example.com', stealthy_headers=True)+ >> print(page.status)+ 200+ >> products = page.css('.product')+ ```++ Au lieu du code précédent++ ```python+ >> from scrapling import Fetcher+ >> fetcher = Fetcher().get('https://example.com', stealthy_headers=True)+ >> print(fetcher.status)+ 200+ >> page = fetcher.adaptor+ >> products = page.css('.product')+ ```++ J’ai conservé la propriété `.adaptor` pour préserver la compatibilité avec les versions précédentes.++2. Les classes `StealthyFetcher` et `PlayWrightFetcher` acceptent désormais un argument `proxy` dans la méthode de récupération, sous forme de chaîne ou de dictionnaire.+3. La classe `StealthyFetcher` possède désormais l’argument `os_randomize` dans la méthode `fetch`. S’il est activé, Scrapling choisit au hasard les empreintes du système d’exploitation. Par défaut, les empreintes correspondent au système d’exploitation actuel.++##### Corrections de bugs {#v0.2.1-bugs-squashed}+1. Correction d’un bug lors de la transmission d’en-têtes à la classe `Fetcher`.+2. Correction d’un bug lors de l’analyse de réponses JSON transmises par les classes de fetchers.++##### Améliorations d’utilisation {#v0.2.1-quality-of-life-changes}+1. Les fonctions de texte essayaient de supprimer les commentaires HTML avant de renvoyer le texte, mais cela causait des erreurs dans certains cas et compliquait inutilement le code. Elles reviennent désormais au comportement par défaut de lxml : **vous remarquerez un léger gain de vitesse dans toutes les opérations qui dépendent du texte des éléments, comme les sélecteurs**. Si vous souhaitez que Scrapling retire les commentaires HTML avant de renvoyer le texte pour éviter l’étrange découpage du texte dans lxml/parsel/scrapy, laissez l’argument `keep_comments` à True, sa valeur par défaut.++## [v0.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2) - 2024-11-11 {#v0.2}++### Ce qui a changé {#v0.2-what-s-changed}+##### Nouvelles fonctionnalités {#v0.2-new-features}+1. Voici la fonction `Fetchers`, avec 3 nouveaux types principaux pour que Scrapling récupère des pages à votre place avec BEAUCOUP d’options !+ - La classe `Fetcher`, pour les requêtes HTTP simples+ - La classe `StealthyFetcher`, un fetcher entièrement discret qui utilise une [version modifiée de Firefox pour masquer l’automatisation](https://github.com/daijro/camoufox).+ - La classe `PlayWrightFetcher`, pour effectuer des requêtes avec un navigateur via PlayWright sans modification, PlayWright avec un mode discret créé par moi, de vrais navigateurs via CDP, et [NSTBrowser](https://app.nstbrowser.io/r/1vO5e5) avec son [docker browserless](https://hub.docker.com/r/nstbrowser/browserless) !+2. Ajout des toutes nouvelles méthodes `find_all`/`find` pour trouver facilement des éléments sur la page avec un peu de magie noire !+3. Ajout des méthodes `filter` et `search` à la classe `Adaptors` pour faciliter les opérations par lots sur des groupes d’objets `Adaptor`.+4. Ajout des méthodes `css_first` et `xpath_first` pour simplifier l’utilisation.+5. Ajout de la nouvelle classe `TextHandlers`, utilisée pour les opérations par lots sur des objets `TextHandler`, comme la classe `Adaptors`.+6. Ajout des méthodes `generate_full_css_selector` et `generate_full_xpath_selector`.++##### Corrections de bugs {#v0.2-bugs-squashed}+1. Dans la classe `Adaptors`, `re_first` renvoie désormais la première correspondance trouvée parmi tous les objets `Adaptor` qu’elle contient, au lieu de renvoyer par erreur les résultats de `re_first` de tous les objets `Adaptor`.+2. Si vous sélectionnez le contenu textuel d’éléments (comme avec la fonction CSS `::text`) via une méthode comme `.css` ou `.xpath`, l’objet `Adaptor` renvoie désormais la classe `TextHandlers` au lieu d’une liste de chaînes. Vous pouvez donc utiliser `page.css('something::text').re_first(r'regex_pattern').json()` au lieu de `page.css('something::text')[0].re_first(r'regex_pattern').json()`+3. Les arguments re/re_first de `Adaptor`/`Adaptors` sont désormais cohérents avec ceux de `TextHandler`. Vous disposez donc des arguments `clean_match` et `case_sensitive`.+4. L’argument `auto_match` est activé par défaut lors de la création de `Adaptor`, mais vous devez toujours l’activer lors de la sélection des éléments si vous souhaitez l’utiliser. (Ce n’est pas un bug, mais un choix de conception)+5. Correction de nombreuses annotations de types pour améliorer l’autocomplétion quand vous programmez avec Scrapling.++##### Améliorations d’utilisation {#v0.2-quality-of-life-changes}+1. Les méthodes `css_selector` et `xpath_selector` ont été renommées `generate_css_selector` et `generate_xpath_selector` pour plus de clarté et pour ne pas perturber l’autocomplétion pendant la programmation.+2. Réorganisation de la majeure partie de l’ancien code dans un sous-paquet `core`, avec d’autres choix de conception pour faciliter la maintenance future.+3. Réorganisation du dossier des tests et ajout de tests pour les nouvelles fonctions. Les environnements tox sont désormais conservés en cache sur GitHub pour accélérer les tests automatiques à chaque commit.++## [v0.1.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.2) - 2024-10-16 {#v0.1.2}++**Historique des changements** :++- Correction d’un bug qui empêchait l’argument `keep_comments` de fonctionner comme prévu.+- Ajustement de la fonction de texte pour supprimer automatiquement les commentaires HTML des éléments avant d’en extraire le texte et éviter le comportement différent de Lxml. Par exemple :++ ```python+ >>> page = Adaptor('<span>CONDITION: <!-- -->Excellent</span>', keep_comments=True)+ >>> page.css('span::text')+ ['CONDITION: ', 'Excellent']+ ```++ Ce résultat était dû au comportement par défaut de Lxml, mais la fonction renvoie désormais le texte complet 'CONDITION: Excellent'+ Ce comportement est aussi connu dans parsel\scrapy, j’ai donc voulu le traiter ici.++- Correction d’un bug qui empêchait de supprimer le fichier de base de données SQLite créé par la bibliothèque lors de l’exécution de `pip uninstall scrapling` ou d’une commande similaire.++## [v0.1.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.1) - 2024-10-14 {#v0.1.1}++Petites corrections++## [v0.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1) - 2024-10-13 {#v0.1}++**Historique complet des changements** : <https://github.com/D4Vinci/Scrapling/commits/v0.1>diff --git a/docs/locales/ja/changelog.md b/docs/locales/ja/changelog.mdnew file mode 100644index 0000000..9232085--- /dev/null+++ b/docs/locales/ja/changelog.md@@ -0,0 +1,1279 @@+---+title: "Scrapling の変更履歴"+description: "Scrapling のリリースノートです。新機能、修正、互換性に影響する変更をまとめています。"+---++# 変更履歴 {#changelog}++Scrapling の主な変更を、[GitHub のリリース](https://github.com/D4Vinci/Scrapling/releases)からまとめています。++## [v0.4.15](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.15) - 2026-08-23 {#v0.4.15}++**今年最大規模のリリースの 1 つです。MCP サーバーを作り直し、1 行で RAG 用の Markdown を生成できるようにしました。Cloudflare チャレンジの解決を改善し、自動操作のためにブラウザタブを開いたままにします 🚀**++!!! warning "警告"++ **このリリースには、MCP サーバーの互換性に影響する変更があります。更新前に[互換性に影響する変更](https://github.com/D4Vinci/Scrapling/blob/v0.4.15/docs/ai/mcp-server.md#breaking-changes)を確認してください。**++### 🚀 新機能と使いやすさの改善 {#v0.4.15-new-stuff-and-quality-of-life-changes}++- **ブラウザタブを開いたままにして、次のリクエストでも再利用するようになりました**([ドキュメント](fetching/stealthy.md#session-management)を参照):+ - すべてのブラウザセッションで、リクエスト後もタブを保持します。次のリクエストでは新しいタブを開かず、空いているタブを再利用します。+ - 各リクエストは、割り当てられたタブに自身の設定(タイムアウト、ヘッダー、リソースのブロック)を適用し直します。そのため、別のリクエストの設定が残ることはありません。+ - エラーが発生したタブは閉じて、新しいタブに置き換えます。新しい `close_pages()` メソッドでは、開いているタブをすべて閉じられます。+ - 取得したページは読み込まれたままなので、次のリクエストの `page_setup` 関数は、別のページに移動する前にそのページ上で動作します。これを使って、複数のリクエストにまたがる自動操作をつなげられます。++- **`Response.markdown()` で、どのページも不要な内容を除いた、LLM で使いやすい Markdown に変換できます**([ドキュメント](ai/building-rag-systems.md)を参照):++ ```python+ from scrapling.fetchers import Fetcher++ markdown = Fetcher.get("https://example.com").markdown(main_content_only=True)+ ```++ - MCP サーバーと同じ処理で、スクリプト、スタイル、プロンプトインジェクションに使われる隠れた内容を必ず先に取り除きます。+ - 必要な要素だけを変換するには、`css_selector` を渡します。+ - 新しい `rag` オプション依存関係(`pip install "scrapling[rag]"`)で利用できます。`ai`/`shell`/`all` のオプション依存関係にも含まれます。++- **Web サイト全体をクロールし、RAG パイプライン用の Markdown の文書集合を作る `SiteToMarkdownSpider` テンプレートを追加しました**([ドキュメント](ai/building-rag-systems.md)を参照):++ ```python+ from scrapling.spiders import SiteToMarkdownSpider++ class DocsSpider(SiteToMarkdownSpider):+ name = "docs"+ start_urls = ["https://example.com/docs/"]+ allowed_domains = {"example.com"}+ output_dir = "docs_markdown"++ result = DocsSpider().start()+ result.items.to_jsonl("docs.jsonl")+ ```++ - ページごとに `url`/`title`/`markdown` を持つアイテムを 1 つ返します。省略可能な `output_dir` を指定すると、ページごとに Markdown ファイルを 1 つ書き出します。+ - `max_pages` でクロールするページ数を制限できます。`CrawlSpider` を継承しているため、`rules()` を上書きすれば、どのリンクをたどるかを自由に制御できます。++- **MCP サーバーを作り直しました(互換性に影響します)**([互換性に影響する変更](https://github.com/D4Vinci/Scrapling/blob/v0.4.15/docs/ai/mcp-server.md#breaking-changes)と[ドキュメント](ai/mcp-server.md)を参照):+ - 13 個のツールを 2 つのモードに分けました。単発ツール(`fetch`、`bulk_fetch`、`stealthy_fetch`、`bulk_stealthy_fetch`)は毎回専用のブラウザを起動し、実際の既定値を表示します。セッションツールは、一度開いたセッションを使って動作します。+ - 新しい `session_fetch` ツールは、ブラウザセッションを通じてページを取得します。`open_session` はブラウザ単位の設定だけを持ち、セッションに実際に適用された設定を AI エージェントに返すようになりました。+ - `get` ツールを `make_request` に改名し、すべての HTTP メソッドに対応しました。+ - 新しい `open_request_session` と `session_make_request` ツールにより、AI が永続 HTTP セッションを使えます。リクエスト間で Cookie とブラウザのフィンガープリントを保持します。+ - これにより、取得処理でセッションの設定がリセットされる問題も解消しました。この問題は、最初に @Yigtwxx が [#418](https://github.com/D4Vinci/Scrapling/pull/418) で修正しました。++- **MCP サーバーの HTTP トランスポートは、既定で認証を必須にし、localhost にバインドするようになりました(互換性に影響します)**。@yamantaka-singh による [#414](https://github.com/D4Vinci/Scrapling/pull/414) の変更です([#413](https://github.com/D4Vinci/Scrapling/issues/413) を修正。[ドキュメント](ai/mcp-server.md#authentication)を参照):+ - Bearer トークンを必須にするには、`--auth-token`(または環境変数 `SCRAPLING_MCP_AUTH_TOKEN`)を渡します。意図的に認証なしで公開するには、`--no-auth` を渡します。+ - ネットワークからの接続を受け付けるには、`--host 0.0.0.0` を渡します。++### 🐛 バグ修正 {#v0.4.15-bug-fixes}++- **ブラウザのロケールにかかわらず Cloudflare Turnstile/Interstitial を解決できるようになり、ヘッドレスモードで対話型チャレンジが無限ループすることもなくなりました**。ステルスページが解決中にクラッシュする問題も修正しました。@subediparas5 による [#412](https://github.com/D4Vinci/Scrapling/pull/412) の貢献を含みます([#411](https://github.com/D4Vinci/Scrapling/issues/411) と [#422](https://github.com/D4Vinci/Scrapling/issues/422) を修正)。+- **`find`/`find_all` で `class_` を使うと、複数のクラスを持つ要素を通知なく見落とす問題を修正しました**。@yetval による [#410](https://github.com/D4Vinci/Scrapling/pull/410) の変更です。**空の `class_` 値と、エスケープされていない CSS 文字列の値の問題も修正しました**。@yamantaka-singh による [#417](https://github.com/D4Vinci/Scrapling/pull/417) の変更です。+- **`development_mode` のキャッシュ済みレスポンスを再利用すると、リクエストのメタデータが失われる問題を修正しました**。@Yigtwxx による [#419](https://github.com/D4Vinci/Scrapling/pull/419) の変更です。+- **`retries` が 1 未満の HTTP リクエストが、送信されないまま失敗する問題を修正しました**。@Yigtwxx による [#420](https://github.com/D4Vinci/Scrapling/pull/420) の変更です。++### ドキュメント {#v0.4.15-docs}++- **Web サイトのセクションを整理しました**。新しい「AI と使う」セクションに、MCP サーバー、新しい [Agent Skill](ai/agent-skill.md) ページ、[RAG システムの構築](ai/building-rag-systems.md)ガイドをまとめました。BeautifulSoup からの移行ガイドは「連携と移行」に移し、Scrapy 連携の隣に置きました。+- **[変更履歴](changelog.md)をリポジトリに追加しました**。これまでのすべてのリリースノートを含みます。++## [v0.4.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.14) - 2026-08-10 {#v0.4.14}++**`uv` でのインストールを修正するための、小さなメンテナンスリリースです 🔧**++### 🐛 バグ修正 {#v0.4.14-bug-fixes}++- **`uv` が既定で v0.4.13 のインストールを拒否し、通知なく古いバージョンに戻る問題を修正しました**。前のリリースは `curl_cffi` のプレリリース版を必要としていましたが、`uv` は明示的に有効にしない限り、プレリリース版を許可しません。+すべての依存関係で、安定版を使えるようになりました([#407](https://github.com/D4Vinci/Scrapling/issues/407) を修正)。++## [v0.4.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.13) - 2026-08-09 {#v0.4.13}++**フィード用 Spider と、より使いやすい MCP サーバーを追加する更新です 🎉**++### 🚀 新機能と使いやすさの改善 {#v0.4.13-new-stuff-and-quality-of-life-changes}++- **フィード用 Spider テンプレートを追加しました**。`XMLFeedSpider` は XML フィード(RSS、Atom、商品フィードなど)のノードを順に処理し、`CSVFeedSpider` は CSV の行を辞書として順に処理します。どちらも gzip 圧縮されたフィードを自動で展開します([ドキュメント](spiders/generic-templates.md)を参照)。++ ```python+ from scrapling.spiders import XMLFeedSpider++ class RSSSpider(XMLFeedSpider):+ name = "rss"+ start_urls = ["https://example.com/feed.xml"]++ async def parse_node(self, response, node):+ yield {"title": node.findtext("title"), "link": node.findtext("link")}++ result = RSSSpider().start()+ ```++- **MCP サーバーを MCP SDK v2 に更新し、使い方を改善しました**。AI エージェントにツールの効率的な使い方を教える指示を含めました。各ツールがアノテーションを宣言するため、Claude Code などのクライアントは読み取り専用のツールを自動で承認できます。トークンを節約するため、ツールの説明も短くしました。また、サーバーのバージョンとロゴを MCP クライアントに伝えます([ドキュメント](ai/mcp-server.md)を参照)。+- **`scrapling-mcp` コマンドを追加しました**。`scrapling mcp` に直接対応するため、単一のコマンドを必要とする MCP クライアントやレジストリに、1 行で Scrapling を登録できます。+- **Playwright/Patchright とブラウザのバージョン固定を外しました**。生成するブラウザの User-Agent は、インストール済みの Playwright/Patchright が実際に操作する Chromium のバージョンと常に一致します。そのため、Scrapling 側でバージョンを固定する必要がなくなり、自由に更新できます。更新後は `scrapling install --force` を実行して、ブラウザを更新してください。++### 🐛 バグ修正 {#v0.4.13-bug-fixes}++- **フィンガープリントのデータパッケージがブラウザのバージョンより古いときに、Scrapling のインポートが `browserforge` の ValueError でクラッシュする問題を修正しました**([#394](https://github.com/D4Vinci/Scrapling/issues/394)、[#396](https://github.com/D4Vinci/Scrapling/issues/396)、[#400](https://github.com/D4Vinci/Scrapling/issues/400) を修正)。+- **MCP の一括ブラウザツールで、ページプールのサイズが正しく設定されない問題を修正しました**。この問題により、`bulk_fetch` は 50 個を超える URL を一括取得すると失敗し、`bulk_stealthy_fetch` はすべての URL を 1 つのタブで取得していました。@Yigtwxx による [#393](https://github.com/D4Vinci/Scrapling/pull/393) の変更です。++### プロジェクト {#v0.4.13-project}++- **[AI による貢献の方針](https://github.com/D4Vinci/Scrapling/blob/main/AI_POLICY.md)を追加しました**。AI を使った貢献は歓迎しますが、PR または Issue でその使用を明記する必要があります。AI の使用を明記せずに生成内容を提出したと判断されるものには、ラベルを付けてクローズします。++## [v0.4.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.12) - 2026-07-26 {#v0.4.12}++**Spider がクロール先の Web サイトに合わせて、より適切に動作できるようにするリリースです**++### 🚀 新機能と使いやすさの改善 {#v0.4.12-new-stuff-and-quality-of-life-changes}++- **Spider が AutoThrottle で速度を自動調整できるようになりました。** 遅すぎたり、アクセスを拒否されたりする `download_delay` を推測する必要はありません。Spider が各 Web サイトの応答速度を測り、ドメインごとに待機時間を調整します。Web サイトがアクセスを拒否したり、リクエスト数を制限したりすると、待機時間を 2 倍にするか、`Retry-After` ヘッダーで指定された時間だけ待ちます。制限がなくなったら、再び速度を上げます。設定した `download_delay` と robots.txt の `Crawl-delay` は、引き続き待機時間の下限として守られます([ドキュメント](spiders/advanced.md#autothrottle)を参照)。++ ```python+ class MySpider(Spider):+ name = "adaptive"+ start_urls = ["https://example.com"]+ autothrottle_enabled = True+ autothrottle_start_delay = 2.0+ autothrottle_max_delay = 30.0+ autothrottle_block_backoff = True+ ```++- **結果を CSV と XML に書き出せるようになりました**。従来の JSON/JSONL への書き出しも使えます。アイテムごとにキーが異なっていても、内容を失わずに書き出します。入れ子の値は JSON として書き込みます([ドキュメント](spiders/getting-started.md)を参照)。++ ```python+ result = MySpider().start()+ result.items.to_csv("products.csv")+ result.items.to_xml("products.xml")+ ```++- **MCP サーバーで認証を必須にできるようになりました**。自分の端末だけで使うのではなく、安全に外部に公開できます。トークンのないリクエストは拒否します。サーバーが応答するホスト名も制限できます([ドキュメント](ai/mcp-server.md)を参照)。++ ```bash+ scrapling mcp --http --auth-token "$(openssl rand -hex 32)"+ ```++- **ブラウザで HTTP 形式の CDP URL を使えるようになりました**。WebSocket 形式だけに限りません。ブラウザサービスが提供する `wss://` エンドポイントに加え、`--remote-debugging-port=9222` で自分で起動した Chrome にも、ブラウザ Fetcher や MCP セッションを接続できます。++- **公開する Docker イメージに、リリースのバージョンタグを付けるようになりました**。`latest` だけでなく、使いたいバージョンを正確に指定できます。@JanRK による [#384](https://github.com/D4Vinci/Scrapling/pull/384) の変更です。++### 🐛 バグ修正 {#v0.4.12-bug-fixes}++- **ブラウザエンジンのレスポンスをキャッシュすると、すべての Cookie が失われる問題を修正しました**。Spider の開発モードでは、Cookie に依存するセッションや認証の処理が通知なく動かなくなる原因になっていました。@amitvijapur による [#379](https://github.com/D4Vinci/Scrapling/pull/379) の変更です([#376](https://github.com/D4Vinci/Scrapling/issues/376) を修正)。++- **`StealthyFetcher` が、システム設定に従わずにすべてのブラウザに `en-US` ロケールを強制する問題を修正しました**。ロケールと IP アドレスの不一致により、Web サイトから疑わしいアクセスと見なされ、Google が 429 を返すなどの問題がありました([#381](https://github.com/D4Vinci/Scrapling/issues/381) を修正)。++- **ストレージシステムの誤解を招くエラーメッセージを修正しました**。挿入後に残っていた不要な呼び出しも削除しました。@fix2015 による [#377](https://github.com/D4Vinci/Scrapling/pull/377) の変更です。++### パフォーマンス {#v0.4.12-performance}++- **`get_all_text()` の処理時間が、ノード数に比例する O(nodes) になりました**。各テキストノードの祖先を毎回たどらなくなったため、深く入れ子になったページでは約 5-6 倍の速度になります。@yetval による [#378](https://github.com/D4Vinci/Scrapling/pull/378) の変更です。++## [v0.4.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.11) - 2026-07-12 {#v0.4.11}++**初のプラットフォーム別 Spider テンプレート、より速いパーサー、重要な修正を含む更新です 🎉**++### 🚀 新機能と使いやすさの改善 {#v0.4.11-new-stuff-and-quality-of-life-changes}++- **初のプラットフォーム別 Spider テンプレート、`ShopifySpider` を追加しました!** Shopify ストアの JSON API から、すべての商品を抽出できます。Web サイトの HTML を扱う必要はありません。このクラスを継承し、ストアのドメインを設定するだけで使えます([ドキュメント](spiders/platform-templates.md)を参照)。++ ```python+ from scrapling.spiders import ShopifySpider++ class MyStore(ShopifySpider):+ target_website = "example.com"++ result = MyStore().start()+ ```++- **CLI のブラウザコマンドに `--executable-path` を追加しました**。`scrapling extract fetch` と `scrapling extract stealthy-fetch` の両方で、任意の Chromium 互換ブラウザの実行ファイルを指定できます。このオプションがない場合は、環境変数 `SCRAPLING_EXECUTABLE_PATH` を使います。これにより、MCP サーバーと同じ機能を使えます([#371](https://github.com/D4Vinci/Scrapling/issues/371) を解決)。++ ```bash+ scrapling extract fetch "https://example.com" page.html --executable-path "/path/to/chromium"+ ```++### 🤖 使いやすさの改善 {#v0.4.11-quality-of-life-changes}+- **`find_by_text` と `find_by_regex` の速度が最大で約 2 倍になりました**。`first_match` が有効な場合(既定)、必要になった要素だけをオブジェクトに変換することで、最初の一致が見つかった時点で検索を終了します。@yetval による [#370](https://github.com/D4Vinci/Scrapling/pull/370) の変更です。+- **すべてのライブラリの最新版と比較した、新しいベンチマーク結果に更新しました。**+- **貢献ルールを更新しました。**++### 🐛 バグ修正 {#v0.4.11-bug-fixes}++- **制御文字を含むページで、MCP サーバーの取得ツールがクラッシュする問題を修正しました**。`All strings must be XML compatible` エラーが発生していました。@yetval による [#368](https://github.com/D4Vinci/Scrapling/pull/368) の変更です([#366](https://github.com/D4Vinci/Scrapling/issues/366) を修正)。++## [v0.4.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.10) - 2026-07-04 {#v0.4.10}++**新しい Scrapy 連携と、コミュニティから寄せられた修正を含む更新です 🎉**++### 🚀 新機能と使いやすさの改善 {#v0.4.10-new-stuff-and-quality-of-life-changes}++- **Scrapy 連携を追加しました**。既存の Scrapy プロジェクトを書き直さずに、Scrapling の解析 API を使えます。Spider のコールバックに `scrapling_response` デコレーターを付けると、受け取るレスポンスが Scrapling の `Response` になります。クロールは引き続き Scrapy が担当します([ドキュメント](integrations/scrapy.md)を参照):++ ```python+ import scrapy+ from scrapling.integrations.scrapy import scrapling_response++ class QuotesSpider(scrapy.Spider):+ name = "quotes"+ start_urls = ["https://quotes.toscrape.com"]++ @scrapling_response+ def parse(self, response): # `response` is now a Scrapling Response+ first_quote = response.find_by_text("The world as we have created it", partial=True)+ for quote in [first_quote, *first_quote.find_similar()]:+ yield {"text": quote.get_all_text(strip=True)}+ ```++- **MCP サーバーのすべてのブラウザツールで、任意の Chromium 互換ブラウザを使えるようになりました**。`scrapling mcp --executable-path "/path/to/chromium"` または環境変数 `SCRAPLING_EXECUTABLE_PATH` で共通の設定を行えます。`executable_path` 引数でリクエストごとに指定することもできます。@samrusani による [#360](https://github.com/D4Vinci/Scrapling/pull/360) の変更です([#347](https://github.com/D4Vinci/Scrapling/issues/347) を解決)。+- **すべてのブラウザとフィンガープリントを更新しました**。更新後に `scrapling install --force` を実行して、反映してください。++### 🐛 バグ修正 {#v0.4.10-bug-fixes}++- **UTF-8 以外の Web サイトで、ブラウザ Fetcher が文字化けしたテキストを返す問題を修正しました**。@yehudalevy-collab による [#365](https://github.com/D4Vinci/Scrapling/pull/365) の変更です([#364](https://github.com/D4Vinci/Scrapling/issues/364) を修正)。+- **`LinkExtractor` が `.tar.gz` などの複合拡張子を除外できない問題を修正しました**。@renbkna による [#359](https://github.com/D4Vinci/Scrapling/pull/359) の変更です([#349](https://github.com/D4Vinci/Scrapling/issues/349) を修正)。+- **クロールを一時停止すると、実行中のリクエストがチェックポイントから失われる問題を修正しました。再開後にそれらのリクエストが飛ばされることはなくなりました**。@yetval による [#358](https://github.com/D4Vinci/Scrapling/pull/358) の変更です。+- **Spider が robots.txt の `Request-rate` 指示から誤った待機時間を計算する問題を、Protego の更新により修正しました**。@Disaster-Terminator が [#355](https://github.com/D4Vinci/Scrapling/pull/355) でテストを合わせて修正しました。++### ドキュメント {#v0.4.10-docs}++- **ステルスモードで `init_script` が Patchright の分離された実行環境とどう関わるかを明確にしました**。@mturac による [#353](https://github.com/D4Vinci/Scrapling/pull/353) の変更です([#350](https://github.com/D4Vinci/Scrapling/issues/350) を解決)。+- **Agent Skill を [skills.sh](https://skills.sh/D4Vinci/Scrapling) からインストールする方法を追加しました**。@ob-aion による [#363](https://github.com/D4Vinci/Scrapling/pull/363) の変更です。++## [v0.4.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.9) - 2026-06-07 {#v0.4.9}++**コミュニティから報告された多くの問題を修正するメンテナンス更新です 🛠️**++### 🚀 新機能と使いやすさの改善 {#v0.4.9-new-stuff-and-quality-of-life-changes}++- **すべてのブラウザとフィンガープリントを更新しました**。更新後に `scrapling install --force` を実行して、反映してください。+- **CLI に `--version` フラグを追加しました**。@ETM-Code による [#303](https://github.com/D4Vinci/Scrapling/pull/303) の変更です([#299](https://github.com/D4Vinci/Scrapling/issues/299) を解決)。++### 🐛 バグ修正 {#v0.4.9-bug-fixes}++- **HTTP セッションで、セッション単位の `proxy` 引数が通知なく無視される問題を修正しました**。この問題は実際の IP アドレスを漏らす可能性がありました([#295](https://github.com/D4Vinci/Scrapling/issues/295) を解決)。セッション単位の `proxy` とリクエスト単位の `proxies`(またはその逆)を混在させると、一方を通知なく無視する代わりにエラーを出すようになりました。+- **`init_script` と `user_data_dir` を併用すると、ブラウザのページ移動が失敗する問題を修正しました**([#294](https://github.com/D4Vinci/Scrapling/issues/294) を解決)。+- **Web サイトが `Content-Type` ヘッダーの charset 値を引用符で囲むと、文字コードを正しく検出できない問題を修正しました**。@Bortlesboat による [#323](https://github.com/D4Vinci/Scrapling/pull/323) の変更です。+- **適応型の要素再検索で `IndexError` が発生する問題を修正しました。`auto_save` が有効なときに発生していました**。@Mubashirrrr による [#340](https://github.com/D4Vinci/Scrapling/pull/340) の変更です。+- **Windows で Spider のチェックポイントとキャッシュの保存がクラッシュする問題を修正しました**。@MrStarkEG による [#344](https://github.com/D4Vinci/Scrapling/pull/344) の変更です。+- **属性の数が異なる要素に対し、`find_similar` が誤った類似度を計算する問題を修正しました**([#322](https://github.com/D4Vinci/Scrapling/issues/322) を解決)。++### ドキュメント {#v0.4.9-docs}++- **既定のインストールにはパーサーエンジンだけが含まれることを明確にしました**。Fetcher と Spider にはオプション依存関係が必要です([#343](https://github.com/D4Vinci/Scrapling/issues/343) を解決)。+- **残っていた例の Docker イメージ名を修正しました**。@evanclan による [#315](https://github.com/D4Vinci/Scrapling/pull/315) の変更です。+- **貢献ガイドのリンク切れを修正しました**。@Bortlesboat による [#320](https://github.com/D4Vinci/Scrapling/pull/320) の変更です。++## [v0.4.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.8) - 2026-05-11 {#v0.4.8}++**クロールフレームワークをさらに使いやすくする、Spider の大きな更新です 🕷️**++### 🚀 新機能と使いやすさの改善 {#v0.4.8-new-stuff-and-quality-of-life-changes}++- **`LinkExtractor` ユーティリティを追加しました**。`scrapling.spiders.LinkExtractor` から使い、`Response` から URL を抽出できます。多くの制御オプションがあります([ドキュメント](spiders/generic-templates.md)を参照)。++ ```python+ from scrapling.spiders import LinkExtractor++ extractor = LinkExtractor(allow=r"/posts/", deny_domains=["ads.example.com"])+ ```++- **汎用 Spider テンプレートの `CrawlSpider` と `CrawlRule` を追加しました**。「このパターンに一致するリンクをたどる」といった定型コードを毎回書く必要がなくなります。`rules()` を上書きして `CrawlRule` オブジェクトのリストを返し、それぞれに `LinkExtractor` を組み合わせます([ドキュメント](spiders/generic-templates.md)を参照)。++ ```python+ from scrapling.spiders import CrawlSpider, CrawlRule, LinkExtractor++ class QuotesSpider(CrawlSpider):+ name = "blog"+ start_urls = ["https://quotes.toscrape.com/"]++ def rules(self):+ return [+ CrawlRule(LinkExtractor(allow=r"/author/"), callback=self.parse_author),+ CrawlRule(LinkExtractor(allow=r"/page/\d+/")), # pagination, no callback+ ]++ async def parse_author(self, response):+ yield {+ "name": response.css(".author-title::text").get(),+ "birthday": response.css(".author-born-date::text").get(),+ "url": response.url,+ }+ ```++- **`SitemapSpider` テンプレートを追加しました**。サイトマップや `robots.txt` の URL から直接クロールを開始できます。gzip 圧縮のサイトマップに対応し、多くの制御オプションを備えています。上の **CrawlSpider** の例と同じように、クロールルールで URL の処理先を決めます([ドキュメント](spiders/generic-templates.md)を参照)。++ ```python+ from scrapling.spiders import SitemapSpider, CrawlRule, LinkExtractor++ class NewsSitemap(SitemapSpider):+ name = "news"+ sitemap_urls = ["https://example.com/robots.txt"]++ def rules(self):+ return [+ CrawlRule(LinkExtractor(allow=r"/articles/"), callback=self.parse_article),+ ]++ async def parse_article(self, response):+ yield {"url": response.url, "title": response.css("h1::text").get()}+ ```++- **適応型の要素再検索で、すべてのメソッドの類似度のしきい値を既定で 40% にしました**。以前の既定値は `0` でした。これにより、適応型機能がより適切に動作します。しきい値を超える要素がない場合は、見つかった最高スコアを警告で伝えるため、必要に応じて `percentage` を意図的に下げられます。++- **すべてのブラウザとフィンガープリントを更新しました**。更新後に `scrapling install --force` を再実行して、ブラウザとフィンガープリントを更新してください。++### 🐛 バグ修正 {#v0.4.8-bug-fixes}++- **`Fetcher.configure(...)` が個別のリクエスト呼び出しに適用されない問題を修正しました**。`AsyncFetcher` にも同じ修正を適用しました。+- **リクエストのフィンガープリントの計算ミスにより、Spider が重複したリクエストを送る問題を修正しました**。@yetval による [#255](https://github.com/D4Vinci/Scrapling/pull/255) の変更です。+- **適応型スクレイピングエンジンが、類似度の低い一致を通知しない問題を修正しました。** 上のしきい値変更と合わせて、要素の再検索が失敗した場合は、誤解を招く「最も近そうな」要素を返す代わりに警告を出します。++### ドキュメント {#v0.4.8-docs}++- **ドキュメント全体の古いコード例を更新しました**。現在のバージョンに合わせています。+- **ドキュメントサイトでコードをコピーして貼り付けやすくしました**。Agent Skill も整理し、呼び出すたびに使うトークンを減らしました。++## [v0.4.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.7) - 2026-04-17 {#v0.4.7}++**AI エージェントがページを見られるようにする更新です 📸**++### 🚀 新機能と使いやすさの改善 {#v0.4.7-new-stuff-and-quality-of-life-changes}++- **MCP ツール `screenshot` を追加しました**。ページを撮影し、MCP の実際の `ImageContent` ブロックとして返すため、モデルが画像を直接見られます。ブラウザセッションを開いておく必要があります。先に `open_session` を呼び出し(`dynamic` または `stealthy`)、その `session_id` をここに渡してください。PNG と JPEG、ページ全体の撮影、JPEG の品質指定、通常の待機オプション(`wait`、`wait_selector`、`network_idle`、`timeout`)に対応しています([#244](https://github.com/D4Vinci/Scrapling/issues/244) を実装)。+- **任意の名前を指定する `session_id` パラメーターを `open_session` に追加しました**。既定のランダムな 12 桁の 16 進文字列の代わりに、意味のある名前(`"search"`、`"checkout"`)を付けられます。@hauntedhost による [#243](https://github.com/D4Vinci/Scrapling/pull/243) の変更です。++### 🐛 バグ修正 {#v0.4.7-bug-fixes}++- **`FetcherSession` の状態が壊れる問題と、遅延初期化するセッションを閉じるとクラッシュする問題を修正しました**。@yetval による [#245](https://github.com/D4Vinci/Scrapling/pull/245) の変更です。+- **`TypeError: Session.request() got an unexpected keyword argument 'block_ads'` を修正しました**。CLI の `--ai-targeted` フラグを HTTP コマンドで使うと発生していました。@voidborne-d による [#249](https://github.com/D4Vinci/Scrapling/pull/249) の変更です([#247](https://github.com/D4Vinci/Scrapling/issues/247) を修正)。++### 翻訳 {#v0.4.7-translations}++- **ブラジルポルトガル語の README 翻訳を追加しました**。@rgomids による [#250](https://github.com/D4Vinci/Scrapling/pull/250) の貢献です。++## [v0.4.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.6) - 2026-04-13 {#v0.4.6}++**ブラウザのステルス機能、プライバシー、開発のしやすさを改善する更新です 🔒**++### 🚀 新機能と使いやすさの改善 {#v0.4.6-new-stuff-and-quality-of-life-changes}++- **ブラウザ Fetcher に広告ブロックを組み込みました**。`block_ads=True` を渡すと、約 3,500 個の既知の広告・トラッキングドメインへのリクエストをルートのインターセプト段階で止めます。DNS 問い合わせも TCP 接続も行わず、すぐに中止します。`blocked_domains` と組み合わせて、独自のリストも使えます。MCP サーバーと CLI の `--ai-targeted` モードでは自動で有効になり、トークンを節約し、ページの読み込みを速くします。++ ```python+ page = StealthyFetcher.fetch('https://example.com', block_ads=True)+ ```++- **DNS-over-HTTPS に対応しました**。プロキシ使用時の DNS 漏えいを防ぎます。`dns_over_https=True` を渡すと、Cloudflare の DoH を使って DNS 問い合わせを送ります。HTTP 通信がプロキシを通っていても、DNS の名前解決から実際の場所が漏れる問題を防げます。++ ```python+ page = StealthyFetcher.fetch('https://example.com', proxy='http://proxy:8080', dns_over_https=True)+ ```++- **ブラウザ Fetcher に `page_setup` コールバックを追加しました**。`page.goto()` の前に実行する関数です。ページ移動前に必要なイベントリスナー、ルート、スクリプトを登録できます。ページ移動後に動作する `page_action` と組み合わせて使えます([#237](https://github.com/D4Vinci/Scrapling/issues/237) を解決)。++ ```python+ def capture_websockets(page):+ page.on("websocket", lambda ws: print(f"WS: {ws.url}"))++ page = DynamicFetcher.fetch('https://example.com', page_setup=capture_websockets)+ ```++- **CLI オプション `--block-ads` と `--dns-over-https` を追加しました**。`fetch` と `stealthy-fetch` の両方のコマンドで使えます。++### 🐛 バグ修正 {#v0.4.6-bug-fixes}++- **`Seconds` 型エイリアスが浮動小数点数を受け付けない問題を修正しました**。ブラウザ Fetcher に `wait=1.5` や `timeout=500.0` を渡すと、型エラーになっていました。型エイリアスが `float` を型ではなくメタデータとして扱っていたことが原因です。@kuishou68 による [#240](https://github.com/D4Vinci/Scrapling/pull/240) の変更です。+- **フルパスのセレクター生成で ID 部分が重複する問題を修正しました**。CSS/XPath のフルパスを生成するとき、`id` 属性を持つ要素のセレクターが 2 回追加され、`body > #main > #main > #target > #target` のようになっていました。XPath のフルパスで、`[@id='x']` だけの条件式(無効な XPath)が出力される問題も修正し、`*[@id='x']` を出力するようにしました。@sjhddh による [#241](https://github.com/D4Vinci/Scrapling/pull/241) の変更です。+- **シェルの関数シグネチャに不足していたパラメーターを追加しました**。対話型シェルの関数シグネチャには、`blocked_domains`、`block_ads`、`retries`、`retry_delay`、`capture_xhr`、`executable_path`、`dns_over_https` が含まれていませんでした。++## [v0.4.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.5) - 2026-04-07 {#v0.4.5}++**Spider 開発者に便利な大きな新機能と、いくつかの重要な修正を含む更新です 🎉**++### 🚀 新機能と使いやすさの改善 {#v0.4.5-new-stuff-and-quality-of-life-changes}++- **Spider の開発モード**:以前は Spider の `parse()` 処理を調整するたびに、対象サーバーに再アクセスする必要がありました。遅いうえに不要な通信が増え、セレクターを調整している間にリクエスト数を制限されることもありました。新しい開発モードでは、最初の実行時にすべてのレスポンスをディスクにキャッシュし、以降はディスクから再利用します。コールバックを何度調整して実行しても、ネットワークリクエストは発生しません。クラス属性を 1 つ設定するだけで有効にできます:++ ```python+ class MySpider(Spider):+ name = "my_spider"+ start_urls = ["https://example.com"]+ development_mode = True++ async def parse(self, response):+ yield {"title": response.css("title::text").get("")}+ ```++ キャッシュの既定の保存先は `.scrapling_cache/{spider.name}/` です。`development_cache_dir` で別の場所に変更できます。新しい統計カウンター `cache_hits` と `cache_misses` で、キャッシュの利用状況を確認できます。キャッシュの再利用では、`download_delay`、リクエスト数の制限、ブロックされたリクエストの再試行を省くため、ディスクの速度で繰り返し試せます。`development_mode = True` のまま Spider を本番で使わないでください。これは開発用の機能で、本番用のキャッシュではありません。詳しくは[ドキュメント](spiders/advanced.md#development-mode)を参照してください。++- **リダイレクトの既定の動作をより安全にしました**。すべての HTTP Fetcher、MCP サーバー、シェルで、`follow_redirects` の既定値は `"safe"` になりました。リダイレクトは引き続きたどりますが、内部・プライベート IP(ループバック、プライベートネットワーク、リンクローカル)への移動は拒否します。これにより、ユーザーが指定した URL をスクレイピングするときに SSRF を防げます。以前の動作に戻すには `follow_redirects="all"` を渡します。リダイレクトを完全に無効にするには `False` を渡します。++### 🐛 バグ修正 {#v0.4.5-bug-fixes}++- **強制停止でチェックポイントが失われることはなくなりました**。`crawldir` を有効にした Spider で Ctrl+C を 2 回押す(強制停止する)と、チェックポイントの書き込みと競合することがありました。pickle の書き込みが終わる前にキャンセルスコープがタスクを終了し、`paused=False` のままになるため、前のチェックポイントを*削除する*後片付けの処理が動いていました。その結果、長いクロールを強制停止すると、保存したかった進捗をすべて失う可能性がありました。現在のエンジンは、**チェックポイントを書き込んでから** `cancel_scope.cancel()` を呼び出すため、強制停止しても最新の未処理の状態を必ず保持します。@voidborne-d による [#230](https://github.com/D4Vinci/Scrapling/pull/230) の変更です。++## [v0.4.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.4) - 2026-04-05 {#v0.4.4}++**Spider の重要な改善とバグ修正を含む更新です 🎉**++### 🚀 新機能と使いやすさの改善 {#v0.4.4-new-stuff-and-quality-of-life-changes}+- **Spider フレームワークで robots.txt のルールに従えるようにしました**。新しい `robots_txt_obey` オプションで有効にします。Spider はクロール前に robots.txt を自動で取得し、`Disallow`、`Crawl-delay`、`Request-rate` などの指示を守ります。robots.txt は並行して取得し、クロールが終わるまでドメインごとにキャッシュします。@AbdullahY36 による [#226](https://github.com/D4Vinci/Scrapling/pull/226) の変更です。+- **robots.txt のキャッシュを事前に準備する機能を追加しました**。クロールループが始まる前に、start_urls のすべてのドメインの robots.txt を取得して解析します。各ドメインへの最初のリクエストで待つ必要がなくなります。+- **統計値 `robots_disallowed_count` を追加しました**。`CrawlStats` で、クロール中に robots.txt のルールでブロックされたリクエスト数を記録します。++Web サイトの説明は[こちら](spiders/getting-started.md#robotstxt-compliance)を参照してください。++### 🐛 バグ修正 {#v0.4.4-bug-fixes}+- **`ProxyRotator` の重大な MRO の問題を修正しました**。仮のメソッド `_build_context_with_proxy` が子クラスの実装を隠していたため、プロキシのローテーションで必ず `NotImplementedError` が発生していました([#215](https://github.com/D4Vinci/Scrapling/issues/215) を修正)。@yetval に感謝します。+- **ブラウザセッションでリクエストごとにプロキシを切り替えると、ページプールに不要な参照が残る問題を修正しました**。一時的なコンテキスト内で作成したページが後片付けでプールから削除されず、無効な参照が蓄積していました。@yetval による [#223](https://github.com/D4Vinci/Scrapling/pull/223) の変更です。+- **静的 Fetcher で不足していた型のアサーションを追加しました**。`curl_cffi` が `None` を `session.request()` から返す場合があり、後続の処理でエラーになっていました。++### その他 {#v0.4.4-other}+- 依存関係を更新しました。最新のフィンガープリントなどを利用できます。+- robots.txt の解析用に、`protego` をオプション依存関係グループ `fetchers` に追加しました。++## [v0.4.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.3) - 2026-03-30 {#v0.4.3}++**多くの重要な変更を含む更新です 🎉**++### 🚀 新機能と使いやすさの改善 {#v0.4.3-new-stuff-and-quality-of-life-changes}+- **新しい MCP ツールを追加しました**。通常モードまたはステルスモードのブラウザを開いたままにして、ほかのツールから引き続き使えます。ブラウザを閉じるツールも追加しました([例](https://github.com/D4Vinci/Scrapling/blob/v0.4.3/docs/ai/mcp-server.md#examples))。+- **新しい MCP ツールを追加しました**。既存のブラウザセッションをすべて一覧表示します。新しいツール群と組み合わせて使います。+- **ブラウザセッションに新しいオプションを追加しました**。リクエスト中に発生したすべてのバックグラウンドリクエストを自動で収集します([#159](https://github.com/D4Vinci/Scrapling/pull/159) を解決)[[例](https://github.com/D4Vinci/Scrapling/blob/v0.4.3/docs/fetching/dynamic.md#capturing-xhrfetch-requests)]。+- **新しいサニタイザーを追加しました**。隠れた内容や見えない内容を取り除き、一般的なプロンプトインジェクション攻撃から MCP サーバーを守ります。+- **Web スクレイピングコマンドに新しいコマンドラインオプションを追加しました**。`--ai-targeted` を使うと、MCP サーバーと同様に、AI 向けの内容に整え、一般的なプロンプトインジェクション攻撃を防げます。+- **ブラウザセッションに新しいオプションを追加しました**。`executable_path` で、任意のブラウザのパスを指定できます([#202](https://github.com/D4Vinci/Scrapling/pull/202) を解決)。+- MCP サーバーのコードを**整理し直しました**。保守しやすくし、すべてのツールを非同期に統一しました。+- CLI コマンドのコードを**整理し直しました**。保守しやすくし、210 行削減しました。++### 🐛 バグ修正 {#v0.4.3-bug-fixes}+- Spider のセッションで再試行するときも HTTP メソッドを保持するように修正しました。@karesansui-u による [#201](https://github.com/D4Vinci/Scrapling/pull/201) の変更です。+- ページ内容の取得に再試行回数の上限を設け、無限ループを防ぎました。@haosenwang1018 と @D4Vinci による [#197](https://github.com/D4Vinci/Scrapling/pull/197) の変更です。+- 引数のない `raise` を `return False` に置き換えました。対象は `_restore_from_checkpoint` です。@haosenwang1018 による [#196](https://github.com/D4Vinci/Scrapling/pull/196) の変更です。+- `get_all` を `getall` に置き換え、`Texthandler` を Selector クラスに合わせました。++### カバレッジとテストの改善 {#v0.4.3-coverage-tests-improvement}+- `_normalize_credentials` の境界条件を確認するテストを追加しました。@Bortlesboat による [#192](https://github.com/D4Vinci/Scrapling/pull/192) の変更です。+- 保存したデータを同じ内容で取得できることを確認するテストと、コアストレージのカバレッジを増やすテストを追加しました。@haosenwang1018 による [#193](https://github.com/D4Vinci/Scrapling/pull/193) の変更です。+- `TextHandler` の正規表現を使う処理と `TextHandlers.re()` を確認するテストを追加しました。@haosenwang1018 による [#194](https://github.com/D4Vinci/Scrapling/pull/194) の変更です。+- `filter`、`iterancestors`、`find_similar` の境界条件を確認するテストを追加しました。@awanawana による [#200](https://github.com/D4Vinci/Scrapling/pull/200) の変更です。++### Agent Skill の改善 {#v0.4.3-agent-skill-improvement}+- Skill のリファレンス内の Markdown リンク切れを修正しました。@yetval による [#204](https://github.com/D4Vinci/Scrapling/pull/204) の変更です。+- [Clawhub](https://clawhub.ai/d4vinci/scrapling-official) の検証に通りやすいよう、Skill の構成を改善しました。+- Skill がコマンドラインでスクレイピングするときは、`--ai-targeted` オプションを必ず使うようにしました。++### ドキュメントの改善 {#v0.4.3-docs-improvement}+- 韓国語の README 翻訳を追加しました。@greatsk55 による [#187](https://github.com/D4Vinci/Scrapling/pull/187) の貢献です。+- 中国語と日本語の README で、CJK 文字とラテン文字の間の空白を修正しました。+- 以前の Web サイトのデザインから残っていたリンク切れを修正しました。++## [v0.4.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.2) - 2026-03-08 {#v0.4.2}++**重要な変更を含むメンテナンス更新です**++#### バグ修正 {#v0.4.2-bug-fixes}+- `get_all_text()` 関数が、要素の終了タグの後にあるテキストノードも取得するようになりました。これにより、MCP サーバーやコマンドで、以前は見落としていたテキストを読めます([#168](https://github.com/D4Vinci/Scrapling/pull/168))。@mhillebrand に感謝します。+- Referer に使う URL を、Google の検索 URL から Google のトップページの URL に変更しました。以前の処理は正しくなく、フィンガープリントによる識別の手がかりになっていた可能性があります([#179](https://github.com/D4Vinci/Scrapling/pull/179))。@Bortlesboat に感謝します。+- すべてのブラウザで、追加の起動フラグを結合する処理の問題を修正しました。@rostchri に感謝します。+- 3.12 より前の Python でクラッシュを起こしていた型ヒントの問題を修正しました([#163](https://github.com/D4Vinci/Scrapling/issues/163) を解決)。++#### その他 {#v0.4.2-other}+- Claude Code / OpenClaw などの AI エージェントツール向けに Agent Skill を追加しました。+- Agent Skill を Clawhub に追加しました。+- すべてのブラウザと Playwright を最新バージョンに更新しました。+- メインの README ファイルにフランス語の翻訳を追加しました。++## [v0.4.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.1) - 2026-02-27 {#v0.4.1}++**多くの重要な変更を含む更新です**++### 🚀 新機能と使いやすさの改善 {#v0.4.1-new-stuff-and-quality-of-life-changes}+- Cloudflare のチャレンジ検出に使う**正規表現の精度を改善しました**(@Rinz27 に感謝します。[#133](https://github.com/D4Vinci/Scrapling/pull/133))。+- Cloudflare のチャレンジ処理の**速度と効率を改善しました**。速度はほぼ以前の倍になりました。+- サイト本体に移動する前に Cloudflare のページを二度表示するサイトにも対応するよう、**Cloudflare のチャレンジ処理を改善しました**。+- 注入していた JS ファイルを削除し、**ステルスブラウザのステルス性と速度を改善しました**。+- OpenCode で使えるように **MCP スキーマを改善しました**(@robin-ede に感謝します。[#137](https://github.com/D4Vinci/Scrapling/pull/137))。+- VS Code Copilot などの厳密なツールでも使えるよう、**MCP スキーマの互換性をさらに改善しました**(#150 を解決)。+- `main_content_only` が有効なときに不要な HTML タグを削除することで、**MCP サーバーのトークン使用量を大幅に減らしました**。+- PyPI ページを修正し、MCP サーバーレジストリへの登録に必要なファイルを追加しました。+- コマンドラインの代わりにコードからブラウザの依存関係をインストールする例を追加し、自動化しやすくしました。+- すべてのワークフローで actions を最新バージョンに更新しました(@salmanmkc に感謝します。[#143](https://github.com/D4Vinci/Scrapling/pull/143)/[#144](https://github.com/D4Vinci/Scrapling/pull/144))。++## [v0.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4) - 2026-02-15 {#v0.4}++**Scrapling でこれまで最大のリリースです。Spider フレームワーク、プロキシの切り替え、パーサーの大幅な改善を導入しました**++このリリースでは、完全に非同期のクローリングフレームワーク、賢いプロキシ管理、重要な API の変更を導入しました。Scrapling の機能と一貫性が向上しています。更新前に、互換性に影響する変更の節をよく確認してください。++### 🕷️ Spider フレームワーク {#v0.4-spider-framework}++`anyio` を基にした新しい非同期クローリングフレームワークです。大規模なスクレイピングを整理して実行できます。++```python+from scrapling.spiders import Spider, Response++class MySpider(Spider):+ name = "demo"+ start_urls = ["https://example.com/"]++ async def parse(self, response: Response):+ for item in response.css('.product'):+ yield {"title": item.css('h2::text').get()}++MySpider().start()+```++- **Scrapy に似た Spider API**:`start_urls`、非同期の `parse` コールバック、`Request`/`Response` オブジェクト、優先度付きキューを使って Spider を定義できます。+- **並行クローリング**:同時実行数の上限、ドメインごとの速度制限、ダウンロード間隔を設定できます。+- **複数セッションへの対応**:同じ Spider で、HTTP リクエストとステルス対応のヘッドレスブラウザを共通のインターフェースから使えます。ID でリクエストを各セッションに振り分け、必要になった時点でセッションを初期化することもできます。+- **一時停止と再開**:チェックポイントにクロールの進み具合を保存します。Ctrl+C で安全に終了し、次の起動時に続きから再開できます。+- **ストリーミングモード**:`async for item in spider.stream()` で、取得したデータをその都度受け取れます。リアルタイムの統計もあり、UI、データ処理パイプライン、長時間のクロールに適しています。+- **ブロックされたリクエストの検出**:ブロックされたリクエストを自動で検出し、再試行します。処理はカスタマイズできます。+- **組み込みのエクスポート**:フックと独自のパイプラインで結果を出力できます。組み込みの JSON/JSONL 出力には、それぞれ `result.items.to_json()` / `result.items.to_jsonl()` を使えます。+- **ライフサイクルフック**:`on_start()`、`on_close()`、`on_error()`、`on_scraped_item()` などのフックで、クロールの開始から終了まで制御できます。+- **詳しいクロール統計**:リクエスト、レスポンス、バイト数、ステータスコード、プロキシ、ドメインやセッションごとの内訳、ログレベルごとの件数などを記録します。+- **uvloop 対応**:`use_uvloop=True` を `spider.start()` に渡すと、uvloop が利用可能な場合に非同期処理が速くなります。++Web サイトに詳しい説明の節を追加しました。[こちら](spiders/architecture.md)を参照してください。++### 🔄 プロキシの切り替え {#v0.4-proxy-rotation}++* スレッドセーフなプロキシ切り替えを行う `ProxyRotator` クラスを追加しました。すべての Fetcher とセッションで使えます。++ ```python+ from scrapling import ProxyRotator+ rotator = ProxyRotator(["http://proxy1:8080", "http://proxy2:8080"])+ Fetcher.get(url, proxy_rotator=rotator)+ ```++* **独自の切り替え方法**:プロキシを切り替える処理を自分で定義できます。+* **リクエストごとのプロキシ指定**:`proxy=` を個別の `get()`/`post()`/`fetch()` 呼び出しに渡すと、そのリクエストだけセッションのプロキシ設定を上書きできます。++### 🌐 ブラウザ用 Fetcher の改善 {#v0.4-browser-fetcher-improvements}++* **ドメインのブロック**:新しい `blocked_domains` 引数を `DynamicFetcher`/`StealthyFetcher` に追加しました。指定したドメインへのリクエストをブロックします(サブドメインも自動で対象になります)。+* **自動再試行**:ブラウザ用 Fetcher は、失敗時に再試行するようになりました。`retries`(既定値:3)と `retry_delay`(既定値:1s)で設定でき、プロキシ関連のエラーも検出します。+* **レスポンスのメタデータ**:`Response.meta` 辞書に使用したプロキシを自動で保存し、リクエストのメタデータもまとめます。+* **Response.follow()**:Referer を自動で引き継ぐ次の `Request` オブジェクトを作成します。Spider システム向けの機能です。+* **自動再生の停止**:ブラウザセッションでコンテンツの自動再生をブロックし、以前発生していた問題を防ぎます。+* **速度**:ブラウザの起動フラグを調整し、ステルス性と速度を改善しました。++### 🔧 バグ修正と改善 {#v0.4-bug-fixes-improvements}+- **パーサーの最適化**:繰り返し行う操作を最適化し、性能を改善しました。+- **ページのエラー**:ページでエラーが発生したときにブラウザが閉じない問題を修正しました。+- **空の本文**:本文が空のレスポンスに対応しました。+- **Playwright のイベントループ**:CDP 接続に失敗したときに Playwright のイベントループが閉じない問題を解決しました。+- **型の安全性**:mypy のエラーをすべて修正し、型が付いていなかった関数本体に型ヒントを追加しました。CI ワークフローに mypy と pyright を追加しました。++### ⚠️ 互換性に影響する変更 {#v0.4-breaking-changes}++* **`css_first`/`xpath_first` の削除**:代わりに `css('.selector').first`、`css('.selector')[0]`、または `css('.selector').get()` を使ってください。+* **すべての選択操作が `Selectors` を返します**:`css('::text')`、`xpath('//text()')`、`css('::attr(href)')`、`xpath('//@href')` は、`Selectors` を返すようになりました。テキストノードは `Selector` オブジェクトに包まれ、`tag="#text"` を持ちます。以前の `TextHandlers` は返しません。これにより、選択メソッド全体で API と型ヒントが一貫します。+* **`Response.body` は常に `bytes` です**:以前は `str` または `bytes` でしたが、今後は常に `bytes` を返します。+* **`get()`/`getall()` の動作**:`Selector` では、`get()` が `TextHandler`(シリアライズした HTML またはテキスト値)を返し、`getall()` が `TextHandlers` を返します。別名は `extract_first = get`、`extract = getall` です。古い `get_all()` は `Selectors` から削除しました。+* **`Selectors.first`/`.last`**:安全に要素へアクセスでき、`Selector | None` を返します。`IndexError` は発生しません。+* **内部定数の名前変更**:`DEFAULT_FLAGS` → `DEFAULT_ARGS`、`DEFAULT_STEALTH_FLAGS` → `STEALTH_ARGS`、`HARMFUL_DEFAULT_ARGS` → `HARMFUL_ARGS`、`DEFAULT_DISABLED_RESOURCES` → `EXTRA_RESOURCES`。++### 🔨 その他の変更 {#v0.4-other-changes}++* **依存関係の変更**:`tldextract` を `tld` に置き換えました。内部の `_html_utils.py` を削除して `w3lib.html.replace_entities` を使うようにし、`typing_extensions` を必須の依存関係に追加しました。+* **ドキュメントの全面更新**:MkDocs から Zensical に完全移行し、Spider のドキュメントを追加しました。既存の全ページを更新し、新しい API リファレンスも追加しました。++## [v0.3.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.14) - 2026-01-03 {#v0.3.14}++**v0.3.13 で一部のデバイスに発生した問題を修正する、小さなメンテナンス更新です**++- `StealthyFetcher` とそのセッションクラスでシークレットモードを無効にしました。このモードにより、Windows ではページ間で Cookie が保持されなくなっていました。MacOS と Linux では発生していません([#123](https://github.com/D4Vinci/Scrapling/issues/123) を修正。報告した @frugality4121 と解決方法を示した @gembleman に感謝します)。+- browserforge を最新バージョンに固定しました。すでに古い browserforge が入っている環境で、古いヘッダーモデルが使われる問題を解決します。++## [v0.3.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.13) - 2026-01-01 {#v0.3.13}++**多くの部分を改善した大きな更新です。必要な対応として、互換性に影響する変更も多く含まれています。更新前に以下を読んでください**++* さまざまな理由から、今後は Camoufox を一切使わないことにしました。Camoufox の開発が続けば、将来また使う可能性はあります。このリリース以前のように Camoufox を使い続けたい場合は、[こちらの節](https://github.com/D4Vinci/Scrapling/blob/v0.3.13/docs/fetching/stealthy.md#using-camoufox-as-an-engine)に手順があります。++* 以前は `DynamicFetcher` とそのセッションクラスのステルスモードで patchright を使っていました。今回はそれらのステルスモードを削除し、`StealthyFetcher` とそのセッションクラスで patchright を使うようにしました。以下で説明するとおり、多くの改善を加え、patchright を基に全体のステルス性も高めています。++**これにより、`StealthyFetcher` とそのセッションクラスは以前より 101% 速くなり、メモリとディスク容量の使用量が減り、コードも約 400 行短くなりました。何より、Camoufox を使っていたときより安定しています。**++この変更で、`scrapling install` コマンドのインストール時間が短くなり、Docker イメージも小さくなります。GitHub CI のテストも円滑になり、新しいユーザーにも Scrapling が分かりやすくなります。++### 互換性に影響する変更 {#v0.3.13-breaking-changes}+1. `stealth` 引数を `DynamicFetcher` とそのセッションクラスから削除し、`hide_canvas` 引数を `StealthyFetcher` とそのセッションクラスへ移しました。+2. `disable_webgl` 引数を `DynamicFetcher` から `StealthyFetcher` クラスへ移し、`allow_webgl` に名前を変えました。すべてのセッションクラスでも同じ変更を行っています。+3. `StealthyFetcher` は基本的に `DynamicFetcher` の新しいステルス版になりました。そのため、`block_images`、`humanize`、`addons`、`os_randomize`、`disable_ads`、`geoip` を削除しました。Chromium でこれらを再現しようとしましたが、それぞれに問題がありました。v0.4 までの今後のリリースで変わる可能性があります。++続いて良い知らせです。多くの改善と修正を行いました :)++### 改善 {#v0.3.13-improvements}+- すでに説明したように、`StealthyFetcher` とそのセッションクラスは以前より 101% 速くなりました。さらに、`DynamicFetcher` とそのセッションクラスも 20% 速くなりました。+- Cloudflare のチャレンジを処理するアルゴリズムを改善し、より多くの状況に、より速く対応できるようにしました。今回のリファクタリングで、CAPTCHA の処理も以前の倍の速度になります。+- すべての Fetcher のメモリ使用量を減らしました。+- MCP サーバーのトークン使用量が減り、費用を節約できます!+- Docker イメージが 60% 小さくなりました。+- ドキュメントサイト全体を新しい機能に合わせて更新しました。説明を明確にし、多くの節を短くして、例を追加しました。足りなかった引数の説明や API リファレンスの図なども追加し、ほかにも多くの改善を行っています。サイトの読み込みは 130% 速くなり、通信量も減り、SEO も改善しました。++### バグ修正 {#v0.3.13-fixes}+- Web スクレイピングシェルのショートカットに、以前足りなかった引数を追加し、より正確にしました。+- URL が localhost や IP アドレスでも `google_search` が Google の Referer を作っていた問題を修正しました。++## [v0.3.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.12) - 2025-12-18 {#v0.3.12}++### 変更内容 {#v0.3.12-what-s-changed}+- `DynamicSession`/`AsyncDynamicSession` に `timezone_id` 引数を追加しました。使用するプロキシや VPN に合わせてブラウザのタイムゾーンを設定できます。これにより、タイムゾーンの違いからプロキシの使用を検出されるのを防げます。+- レスポンスを JSON に自動変換する処理を改善しました。+- Fetcher のセッションクラスにある内部関数 `__create__` を `start` に変更しました。`with` の外でもセッションを使いやすくなります。+- `curl_cffi` などの依存関係を最新バージョンに更新しました。++## [v0.3.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.11) - 2025-12-03 {#v0.3.11}++### 変更内容 {#v0.3.11-what-s-changed}+- メディアを再生しているサイトなど、安定しないサイトで `network_idle` を使う場合のタイムアウト処理を改善しました。+- Web スクレイピングシェルの `stealthy_fetch` ショートカットの自動補完を修正しました。++## [v0.3.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.10) - 2025-11-26 {#v0.3.10}++**多くの重要な変更と、互換性に影響する可能性がある変更を含むメンテナンス更新です**++- **すべての文字コードの問題を解決しました**。文字コードが正しく宣言されていないページも扱える、より良い方法を使っています(@Kemsty2 が [#110](https://github.com/D4Vinci/Scrapling/issues/110) [#111](https://github.com/D4Vinci/Scrapling/pull/111) で問題を指摘してくれました。感謝します)。+- すべてのブラウザ用 Fetcher で、リクエスト単位の設定がセッション単位の設定を上書きする処理の問題を**解決しました**。v0.3 から存在していた問題です。+- Web スクレイピング用の対話型シェルで、ショートカットの関数シグネチャを**修正しました**。シェルで正確に自動補完されるようになりました。この問題も v0.3 から存在していました。+- Maxmind データベースを**更新しました**。`geoip` 引数の動作が `StealthyFetcher` とそのセッションクラスで改善します。+- 使用するすべてのブラウザを最新バージョンに**更新しました**。+- **互換性に影響する変更**:すべての Fetcher を大きくリファクタリングしました。以下の変更により、既存のコードが動かなくなる可能性があります。+ 1. Scrapling のコードを約 750 行減らし、多くの部分を変更しました。今後の保守がしやすくなり、リソースの使用量も少し減ります。+ 2. すべての Fetcher とそのセッションクラスで引数の検証が大幅に速くなり、全体の速度も向上します。+ 3. この改善のため、すべての Fetcher で位置引数として渡せるのは `url` だけになりました。残りはキーワード引数にしてください。たとえば `Fetcher.get('https://google.com', stealthy_headers=True)` と書く必要があり、`Fetcher.get('https://google.com', True)` という書き方は使えません。+ 4. v0.3 から、ブラウザ用 Fetcher とそのセッションクラスには不便な違いがありました。リクエストごとのパーサー設定を渡す引数が、Fetcher では `custom_config`、セッションクラスでは `selector_config` でした。今回のリファクタリングで、既存のコードを壊さずに `selector_config` に統一しました。今後は `selector_config` が主な引数になり、`custom_config` も互換性のために使えます。自動補完は `selector_config` のみ対応します。+ 5. これらの変更のため、Fetcher の関数の型ヒントを動的に生成するようにしました。IDE で正しく自動補完されない場合は、新しいバージョンを使っているか確認してください。ほぼすべての有名な IDE とエディターでテストしました。++> すべてのベンチマーク表も更新し、同種のライブラリの最新バージョンと現在の結果を比較しています。++## [v0.3.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.9) - 2025-11-17 {#v0.3.9}++**多くの重要な変更を含む更新です**++### 🚀 新機能と使いやすさの改善 {#v0.3.9-new-stuff-and-quality-of-life-changes}+- `impersonate` 引数にブラウザのリストを渡せるようになりました。`Fetcher` と `FetcherSession` は、リクエストごとにリストからブラウザをランダムに選びます。++```python+from scrapling.fetchers import FetcherSession++with FetcherSession(impersonate=['chrome', 'firefox', 'safari']) as s:+ s.get('https://github.com/D4Vinci/Scrapling')+```++- `clean` メソッドに引数を追加しました。このメソッドは `TextHandler` にあり、現在のテキストから HTML エンティティを簡単に削除できます。+- ドキュメントを大幅に改善し、多くの部分をより正確に説明しました。メインの `README.md` の自動翻訳も追加しました。++### 🐛 バグ修正 {#v0.3.9-bug-fixes}+- ブラウザ用 Fetcher からレスポンスを取得する処理の大きな問題を修正しました。内容の種類を判定し、HTML の場合に限り、`response.body` にブラウザで描画した内容を入れます。それ以外は、最後のリクエストの元の内容を返します。これにより、バイナリファイルやテキストファイルを HTML タグに包まれずにダウンロードでき、Web サイトの取得では必要な描画済みの内容も得られます。++### 🔨 その他 {#v0.3.9-misc}+- 貢献ガイドを更新し、分かりやすくしました。+- コード品質ツールの実行を必須にする新しいワークフローを追加しました(pre-commit フックと同じツールです)。++## [v0.3.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.8) - 2025-10-27 {#v0.3.8}++**多くの重要な変更を含む更新です**++### 🚀 新機能と使いやすさの改善 {#v0.3.8-new-stuff-and-quality-of-life-changes}+- すべてのブラウザ用 Fetcher で、リクエストの読み込みが終わらないサイトに `network_idle` を使っても、コードがクラッシュしなくなりました。+- ブラウザ用 Fetcher でページ内容を取得・確認する処理を変え、Windows でも Linux/MacOS と同じように安定するようにしました(この動作の違いは、Windows での Playwright の実装が異なるためです)。+- 検証処理全体をリファクタリングし、すべてのブラウザ用 Fetcher のリクエストが 8-15% 速くなりました。+- 新しい `extra_flags` を `DynamicFetcher` とそのセッションに追加しました。ブラウザの起動時に、既存の Chrome フラグに独自のフラグを追加できます。+- `page_action` を使う場合は、前のバージョンで変更したレスポンス取得用のルーティング処理を元に戻しました。`page_action` がリクエストを送らずにページを変更しても、最新の内容を取得するためです([#100](https://github.com/D4Vinci/Scrapling/issues/100) と [#102](https://github.com/D4Vinci/Scrapling/pull/102) で指摘した @gembleman に感謝します)。++### 🐛 バグ修正 {#v0.3.8-bug-fixes}+- `load_dom` のスペルミスを DynamicSession の async_fetch 内で修正しました。+- Cloudflare のチャレンジ処理で、解決後も消えない埋め込み CAPTCHA を待ち続ける問題を修正しました。今後は消えるまで 30 秒待ち、その後は消えない種類と判断します(#100 を修正)。++### 🔨 その他 {#v0.3.8-misc}+- Docker イメージを Dockerhub と GitHub のコンテナレジストリに自動で公開するようにし、利用しやすくしました。+- Scrapling で Scrapeless ブラウザを使う方法を説明する[新しいドキュメントページ](https://github.com/D4Vinci/Scrapling/blob/v0.3.8/docs/tutorials/external.md)を追加しました。++## [v0.3.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.7) - 2025-10-12 {#v0.3.7}++**多くの重要な変更を含む更新です**++### 🚀 新機能と使いやすさの改善 {#v0.3.7-new-stuff-and-quality-of-life-changes}+- `solve_cloudflare` の処理を `StealthyFetcher` で作り直し、あらゆる独自実装の Turnstile を解決できるようにしました。+- コード全体をリファクタリングし、Pyright のチェックを通るようにしました。すべての IDE で使い勝手が良くなり、多くのバグも修正されています。+- リクエストの処理を整理し、速くしました(#97 も解決)。+- すべてのブラウザ用セッションクラスに `user_data_dir` を追加しました。以前のセッションのブラウザデータ(Cookie、ストレージなど)を再利用できます。未指定の場合は、以前と同じく、Playwright が実行ごとにランダムなディレクトリを使います。+- 新しい設定項目 `additional_args` を `Dynamic fetcher` とそのセッションクラスに追加しました。Playwright のコンテキストに追加引数を渡せます。以前から `StealthyFetcher` で使えた機能と同じです。+- すべてのブラウザで、最後のナビゲーションレスポンスを取得するルーティング処理を改善しました。以前はブラウザで処理してから渡していましたが、今後はブラウザで処理する前のレスポンスを、そのままパーサーへ渡せます。テキストや JSON のレスポンスで特に役立ちます。++### 🐛 バグ修正 {#v0.3.7-bug-fixes}+- ルーティング処理の変更により、一部の Windows デバイスで不安定なサイトの内容を取得できない問題を解決しました。+- このバージョンのリファクタリングにより、以前は見つけにくかった多くのバグや、一部の IDE の不自然な自動補完も修正しました。+- ドキュメントサイトの多くの問題を修正しました。++## [v0.3.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.6) - 2025-10-01 {#v0.3.6}++### 🚀 新機能 {#v0.3.6-new-stuff}+- `solve_cloudflare` を `StealthyFetcher` とそのセッションクラスで改善し、あらゆる種類の Cloudflare Turnstile/Interstitial チャレンジを解決できるようにしました 🎉+- MCP サーバーで `Streamable HTTP` を使えるようになり、サーバーを簡単に外部へ公開できます。+- Docker 対応を追加しました。リリースごとにイメージを自動でビルドし、Docker Hub に公開します(すべてのブラウザを含みます)。++### 🐛 バグ修正 {#v0.3.6-bug-fixes}+- 一部の状況でパーサーに発生していた文字コードの問題を修正しました(よく見られた `invalid start byte` エラーです)。+- ライブラリの複数の部分を整理し、メモリリークを修正しました。設定によりますが、メモリ使用量が明らかに少なくなります(#92 も解決)。+- コードの多くの部分で型注釈を改善し、IDE を使いやすくしました(#93 も解決)。++## [v0.3.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.5) - 2025-09-20 {#v0.3.5}++**複数の問題を修正する重要なリリースです**++### 🚀 新機能 {#v0.3.5-new-stuff}+- すべてのブラウザ用 Fetcher(`DynamicFetcher`/`StealthyFetcher`/...)とそのセッションクラスで、サイトの取得が 15-20% 速くなりました。+ 1. @AbdullahY36 が #87 で処理を改善したことで、ページ管理が大幅に速くなりました。+ 2. 全体の検証処理を最適化し、同期取得でのページ作成も改善しました。これらにより速度が大きく向上しています。++- `DynamicFetcher` とそのセッションクラスでは、`rebrowser-playwright` を `PatchRight` に置き換え、ステルスモードを大幅に改善しました。+ 1. 以前は `rebrowser-playwright` が、`stealth` と `real_chrome` の両方を有効にすると無効になっていました。組み合わせるとうまく動かなかったためですが、`PatchRight` ではこの問題はありません。+ 2. クローズドな Shadow Root も操作できるようになりました。`PatchRight` が自動で対応します。++### 🐛 バグ修正 {#v0.3.5-bug-fixes}+- `re` メソッドを `Selectors` クラスで使ったときのバグを修正しました。+- Web スクレイピングシェルの `uncurl` と `curl2fetcher` が、curl の `--data-raw` フラグを正しく解析しない問題を修正しました。+- Web スクレイピングシェルの `view` コマンドで、サイトの文字コードによって発生するバグを修正しました。+- `mcp` モードと `extract` コマンドに影響する内容変換のバグを修正しました。++### 新しい貢献者 {#v0.3.5-new-contributors}+- @AbdullahY36 が #87 で初めて貢献しました。++## [v0.3.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.4) - 2025-09-16 {#v0.3.4}++**複数の問題を修正する重要なリリースです**++### 🚀 新機能 {#v0.3.4-new-stuff}+- すべての Fetcher のセッションクラスを対話型シェルに追加しました。インポートせずにすぐ使えます。++### 🐛 バグ修正 {#v0.3.4-bug-fixes}+- Windows の Playwright API で、Cloudflare のチャレンジ処理中にページ内容を取得すると起きるバグへの回避策を追加しました。+- 対話型シェルの `view` コマンドの文字コードの問題を修正しました。+- `max_pages` 引数が `AsyncStealthySession` でクラッシュを起こすバグを修正しました。+- 最近の更新により、`html_content` と `prettify` が `Selector` クラスで文字コードによって bytes を返すようになっていた問題を修正しました。どちらも以前と同じく文字列を返します。++## [v0.3.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.3) - 2025-09-15 {#v0.3.3}++- ブラウザ用 Fetcher で既定のタブを閉じる処理を削除しました。この処理がクラッシュを起こしていたためです(Mac では発生せず、Windows と Linux でのみ再現しました)。++## [v0.3.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.2) - 2025-09-15 {#v0.3.2}++v0.3.2 のリリースノート++### 🚀 新機能 {#v0.3.2-new-stuff}++- **Fetcher の依存関係をオプションに変更**:すべての Fetcher をオプション依存関係のグループに移し、基本パッケージを小さくしました。基本の `scrapling` モジュールにはパーサーだけが含まれます。Fetcher やコマンドライン機能を使う場合は、`pip install "scrapling[fetchers]"` を実行してください。詳しいインストール手順は[こちら](index.md#installation)にあります。+- **セッション内のページごとの設定**:ブラウザ用 Fetcher のセッションクラスで、ページごとに設定を変えられるようになりました。取得時の引数も、セッションの引数と同じように検証します。詳細はドキュメントサイトの[こちら](fetching/stealthy.md#full-list-of-arguments)を参照してください。+ <br>例:++ ```python+ with StealthySession(headless=True, solve_cloudflare=True) as session:+ page = session.fetch('https://nopecha.com/demo/cloudflare', google_search=False)+ ```++- **ブラウザ用 Fetcher の改善**+ - ページの JavaScript の実行完了を待つかどうかを選ぶ設定を追加しました(以前と同じく、既定で有効です)。++ ```python+ with DynamicSession(headless=True, disable_resources=False, network_idle=True) as session:+ page = session.fetch('https://quotes.toscrape.com/', load_dom=False)+ ```++ - `DynamicFetcher` とそのセッションクラスのステルスモードの信頼性が向上しました。+ - `DynamicFetcher` と `StealthyFetcher` のリソース使用量を減らしました(Playwright API の永続コンテキストが開く既定のタブを自動で見つけて閉じます)。+ - ブラウザ用 Fetcher でページを切り替える処理の重要なバグを修正しました。古いページは新しいページに置き換えます(タブを再利用すると、以前の設定が残っている場合があります)。+ - `StealthyFetcher` とそのセッションクラスが少し速くなりました(5%)。++- **`.body` プロパティの改善**:渡された内容を処理せず、そのまま返すようにしました。ファイルのダウンロードや、HTML 以外のリクエストを扱えます。以下は画像をダウンロードする例です。++ ```python+ from scrapling.fetchers import Fetcher++ page = Fetcher.get('https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/poster.png')+ with open(file='poster.png', mode='wb') as f:+ f.write(page.body)+ ```++### 🐛 バグ修正 {#v0.3.2-bug-fixes}++- **文字コードの問題を解決**:一部のサイトでパーサー、mcp モード、extract コマンドに発生していた複数の文字コードの問題を修正しました(#80 と #81 も解決)。+- **解析速度の向上**:さまざまな変更によりライブラリが速くなり、更新したベンチマークにも結果が表れています。++### 🔨 その他 {#v0.3.2-misc}++- **ベンチマークの更新**:速度の改善を同種のライブラリの最新バージョンと比較するため、性能ベンチマークを更新しました。+- **多くのコードをリファクタリングし、不要なコードをより良い実装に置き換えました**:コードが少なく、明確になり、保守しやすくなりました。+- **YouTube 動画の追加**:MCP のドキュメントに動画を追加しました。+- **新しい Issue テンプレート**:既存のテンプレートを使えないユーザー向けに、簡単なテンプレートを追加しました。+- **CI ワークフローの最適化**:ドキュメントやコード以外のファイルだけが変わった場合は、テストワークフローを実行しません。+- **依存関係の更新**:さまざまな依存関係を最新バージョンに更新しました。+- **コードスタイルの改善**:すべてのファイルに新しい ruff ルールを適用しました。+- **Pre-commit フック**:pre-commit の設定を更新しました。++### 🎯 互換性に影響する変更 {#v0.3.2-breaking-changes}++- `max_pages` 引数を同期版の `StealthySession` から削除し、`DynamicSession` とそろえました(同期版では意味のない設定です)。++## [v0.3.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.1) - 2025-09-02 {#v0.3.1}++1. オプション依存関係の `shell` を入れずに Scrapling をインストールしたときの問題を修正しました(#76)。+2. すべてのブラウザ用 Fetcher とそのセッションクラスに、ページ作成時に実行する JS ファイルを指定する引数を追加しました(#56)。++```python+from scrapling.fetchers import StealthyFetcher++StealthyFetcher.fetch('https://example.com', init_script="/absolute/path/to/js/script.js")+```++## [v0.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3) - 2025-09-01 {#v0.3}++🎉 **大型リリース:アーキテクチャを全面的に刷新**++Scrapling v0.3 は、プロジェクト史上最大の更新です。アーキテクチャを全面的に書き直し、パフォーマンスを大きく改善しました。AI 連携や Web スクレイピング用の対話型シェルなど、強力な新機能も追加しています。++このリリースには互換性に影響する変更が複数あります。リリースノートをよく確認してください。++### 🚀 主な新機能 {#v0.3-major-new-features}++#### セッションを使うアーキテクチャ {#v0.3-session-based-architecture}+- **新しいセッションクラス**:全面的な書き直しにより、状態を保持するセッションに対応しました。+ - `FetcherSession`:HTTP リクエスト間で状態を保持します。同期コードと非同期コードの両方で使えます。+ - `DynamicSession`/`AsyncDynamicSession`:処理が終わるまでブラウザを開いたまま、自動操作できます。+ - `StealthySession`/`AsyncStealthySession`:処理が終わるまでブラウザを開いたまま、ステルス機能を使えます。+- **非同期のブラウザタブ管理**:新しい `max_pages` 引数でタブのプールを使えます。タブを順に利用して、ブラウザから同時にページを取得します。+- **セッションの同時実行**:互いに独立した複数のセッションを同時に実行できます。++詳しくは、Web サイトの `Fetching` セクションを参照してください。++#### ステルス機能とボット対策への対応を多数追加 {#v0.3-a-lot-of-new-stealth-anti-bot-capabilities}+- **🤖 Cloudflare チャレンジの解決**:`StealthyFetcher` とそのセッションクラスで、[Cloudflare Turnstile チャレンジを自動で解決](fetching/stealthy.md#cloudflare-and-stealth-options)できます。+- **ブラウザのフィンガープリントを再現**:新しくなった [Fetcher](fetching/static.md) クラスで、実際のブラウザの TLS フィンガープリントやバージョンに合ったヘッダーを再現できます。HTTP/3 などにも対応しています。+- **ステルスモードの改善**:`DynamicFetcher` とそのセッションクラスのステルスモードが、より安定して動作するようになりました(別名 `PlayWrightFetcher`)。++#### AI 連携と MCP サーバー {#v0.3-ai-integration-mcp-server}+- **MCP サーバーを内蔵**:Model Context Protocol サーバーを使って、AI による Web スクレイピングを行えます。+- **6 つの強力なツール**:`get`、`bulk_get`、`fetch`、`bulk_fetch`、`stealthy_fetch`、`bulk_stealthy_fetch`+- **内容を効率よく抽出**:Web ページや要素を Markdown や HTML に変換したり、不要な部分を除いたテキストを抽出したりできます。+- **CSS セレクターに対応**:AI に内容を渡す前に、Scrapling のエンジンで必要な要素を正確に選べます。+- **ボット対策の回避**:Cloudflare Turnstile などの保護機能に対応できます。+- **プロキシに対応**:プロキシで匿名性を確保したり、特定の地域からアクセスしたりできます。+- **ブラウザを再現**:TLS フィンガープリントや、ブラウザのバージョンに合った実際のヘッダーなどを再現できます。+- **並行処理**:複数の URL を同時にスクレイピングして、効率を上げられます。+- [そのほかの機能...](ai/mcp-server.md)++#### Web スクレイピング用の新しい対話型シェル {#v0.3-new-interactive-web-scraping-shell}+- **新しいシェル**:`get`、`post`、`put`、`delete`、`fetch`、`stealthy_fetch` など、多くの便利なショートカットを内蔵した独自の IPython シェルです。+- **ページを自動管理**:新しい `page` と `pages` コマンドで、現在のページと、シェルから行ったすべてのリクエストの履歴を自動で保存します。+- **Curl 連携**:`uncurl` と `curl2fetcher` 関数で、ブラウザの DevTools の curl コマンドを `Fetcher` のリクエストに変換できます。+- [そのほかの機能...](cli/interactive-shell.md)++#### プログラミングせずにターミナルからスクレイピング {#v0.3-scrape-from-the-terminal-without-programming}+- **新しい抽出コマンド**:プログラミングせずに、ターミナルでスクレイピングできます。+ - `scrapling extract get/post/put/delete`:基本的な HTTP リクエストを送信します。+ - `scrapling extract fetch`:動的な内容をスクレイピングします。+ - `scrapling extract stealthy-fetch`:ボット対策を回避します。+- **Web ページをダウンロード**し、その内容をファイルに保存します。+- **HTML を読みやすい形式に変換**できます。Markdown に変換する、HTML のまま保存する、ページのテキストだけを抽出する、といった使い方ができます。+- **独自の CSS セレクターに対応**し、ページの特定の部分を抽出できます。+- **HTTP リクエストとブラウザによる取得に対応しています。**+- **細かく設定できます**。独自のヘッダー、Cookie、プロキシなどを指定できます。コードで使えるほぼすべてのオプションを、ターミナルからも使えます。+- [そのほかの機能...](cli/extract-commands.md)++### 🔧 技術的な改善 {#v0.3-technical-improvements}++#### パフォーマンスの改善 {#v0.3-performance-enhancements}+- **Fetcher の速度が 4 倍になりました**。読み間違いではありません!+- **DynamicFetcher が約 60% 高速になりました**。設定、特にステルスモードによって、大きく高速化します。+- **StealthyFetcher が 20–30% 高速になりました**。新しい構造を使い、`Camoufox` の Python インターフェースの代わりに独自の実装を使い始めたためです。+- **主な選択メソッド全体で 50% 以上の高速化**を実現しました(`find_by_text`、`find_similar`、`find_by_regex`、`relocate` など)。🚀+- **CSS/XPath の first メソッドが約 10% 高速になりました**。`css_first` と `xpath_first` は、`css` と `xpath` より速くなりました。+- **内容抽出用の `get_all_text()` メソッドが 40% 高速になりました**。+- **適応型機能で要素を再び見つける処理が 20% 高速になりました**。+- **要素間の移動に使うプロパティを最適化しました**。`next`、`previous`、`below_elements` などが、目に見えて速くなりました。+- **テキストの整形処理が 5 倍高速になりました**。+- **メモリ効率を改善しました**。インポートを最適化し、余分な処理を減らしました。+- **⚡ インポートを高速化しました**。モジュールの読み込みを最適化し、起動時間を短くしました。+- **ベンチマークの改善**:これらの高速化により、ほかのライブラリと比べてもさらに速くなりました。BeautifulSoup の 1775 倍、AutoScraper の 5.1 倍の速度です。[ベンチマーク](benchmarks.md)を参照してください。++#### アーキテクチャ、コード品質、使いやすさ {#v0.3-architecture-code-quality-and-quality-of-life}+- **永続コンテキスト**:すべてのブラウザ Fetcher が、既定で永続コンテキストを使うようになりました。(#64 も解決します)+- **msgspec でブラウザ Fetcher をすばやく検証します**。リクエストの実行前に検証するので、エラーの原因を見つけやすくなりました。+- **Fetcher が返すすべての Cookie** が、その Fetcher で受け付ける形式になりました。取得した Cookie を、すべての Fetcher とセッションクラスに再び渡せます。+- **コードチェックと整形を高速化しました**。`ruff` に移行しています。+- **新しいビルドシステム**:setup.py から pyproject.toml に移行しました。📦+- **GitHub Actions とワークフローを改善し**、開発とテストを進めやすくしました。+- **🎨 型ヒントを改善しました**。現在の Python の標準に沿って全体に型を付け、IDE のサポートと信頼性を高めました。+- **コードを整理しました**。使われないコードを削除し、主要な関数を最適化しました。🧹+- **🚀 後方互換性**:古いコードを引き続き使えるように、ショートカットを追加しました。++### 互換性に影響する変更 {#v0.3-breaking-changes}++#### 必要な Python のバージョン {#v0.3-minimum-python-version}+- **Python 3.10+ が必要です**。Python 3.9 以前のサポートを終了しました。++#### クラスとメソッドの名前 {#v0.3-class-and-method-naming}+名前をより分かりやすく統一し、特に初めて使う人が理解しやすいように変更しました。++- **`Adaptor` → `Selector`**:主要な解析クラスの名前を変更しました(後方互換性のため、引き続き `Adaptor` としてインポートできます)。+- **`Adaptors` → `Selectors`**:コレクションクラスの名前を変更しました(後方互換性のため、引き続き `Adaptors` としてインポートできます)。+- **`auto_match` → `adaptive`**:すべてのメソッドで引数名を変更しました。+- **`adaptor_arguments` → `selector_config`**:設定用の引数名を変更しました。+- **`automatch_domain` → `adaptive_domain`**:ドメイン用の引数名を変更しました。+- **`additional_arguments` → `additional_args`**:引数名を短くしました。+- **⚠️ `text/body` → `content`**:Selector のコンストラクターの引数が、`str` と `bytes` の両方を受け付けるようになりました。+- **`PlayWrightFetcher` → `DynamicFetcher`**:ブラウザを自動操作するクラスの名前を変更しました(後方互換性のため、引き続き `PlayWrightFetcher` としてインポートできます)。+- **DynamicFetcher から NSTBrowser の処理と引数を削除しました**。これらの処理を残す必要がなくなったためです。+- **StealthyFetcher の headless 引数は 'virtual' を受け付けなくなりました**。Camoufox のライブラリは、ブラウザのインストール先とその他の起動オプションを取得するためだけに使っています。++### 🐛 バグ修正 {#v0.3-bug-fixes}++- `get_all_text` が無視するタグ内で、入れ子の子要素を数える処理を修正しました(#61)。+- Python の実行ファイルのパスに空白がある場合のインストールの問題を修正しました(#57)。+- 適応型機能を有効にしたとき、ストレージで再帰処理に伴って起こるスレッドの問題を修正しました。+- `FetcherSession` で Sentinel パターンを使い、引数の優先順位の問題を修正しました。+- `StealthyFetcher` でプロキシの型を扱う処理を修正しました。+- `referer` と `google_search` の引数が競合する問題を修正しました。+- ステルス用スクリプトを非同期で挿入するときの問題を修正しました。++## [v0.2.99](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.99) - 2025-04-08 {#v0.2.99}++**Scrapling の機能を十分に使うために、すべてのユーザーにとって重要な更新です。**++### 変更内容 {#v0.2.99-what-s-changed}+#### 完全なドキュメントを掲載する新しい Web サイト {#v0.2.99-new-full-documentation-website}+- ついにできました 😄 [こちら](index.md)からご覧ください。+#### Fetcher のインポート方法を統一 {#v0.2.99-unified-import-logic-for-fetchers}+- `from scrapling.fetchers import Fetcher, AsyncFetcher, StealthyFetcher, PlayWrightFetcher` ですべての Fetcher をインポートし、初期化せずに `page = Fetcher.get(...)` のように直接使えるようになりました。<br/>従来の `from scrapling.defaults import Fetcher, AsyncFetcher, StealthyFetcher, PlayWrightFetcher` に代わる方法です。+#### 互換性に影響する変更:automatch は既定で無効 {#v0.2.99-breaking-change-automatch-is-now-turned-off-by-default}+- Fetcher で automatch を有効にしたり、ほかの解析オプションを設定したりする新しい方法を導入しました。詳しくは[ドキュメント](fetching/choosing.md#parser-configuration-in-all-fetchers)を参照してください。+> 後方互換性のため、以前のインポート方法と処理も使えますが、警告が表示されます。+#### Fetcher に新しいオプションを追加 {#v0.2.99-new-options-added-to-fetchers}+- `StealthyFetcher` と `PlayWrightFetcher` の両方に、取得時の引数 `wait` を追加しました。ページを閉じてレスポンスを返す前に、指定した時間(ミリ秒)だけ待機します。+- `StealthyFetcher` の `fetch` と `async_fetch` メソッドに、`additional_arguments` 引数を追加しました。Camoufox に追加の設定を渡せます。この設定は Scrapling の設定より優先されます(#54)。+#### バグ修正 {#v0.2.99-bugs-squashed}+- `async_fetch` でリダイレクトを取得する際のバグを修正しました。`StealthyFetcher` と `PlayWrightFetcher` の両方が対象です。++**_ご支援とご寄付に感謝します!_**++## [v0.2.98](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.98) - 2025-03-17 {#v0.2.98}++**Scrapling の機能を十分に使うために、すべてのユーザーにとって重要な更新です**++### 変更内容 {#v0.2.98-what-s-changed}+#### メモリ使用量と速度のさまざまな改善 {#v0.2.98-various-memory-usage-and-speed-optimizations}+- すべての選択メソッドのメモリ使用量が以前の約 40% になり、速度も少し上がりました。+- ライブラリのすべてのサブモジュールを必要なときに読み込むようにしました。使うものだけが読み込まれます。たとえば、次のように変わります。+更新前は、`from scrapling import Adaptor` で Fetcher などもすべて読み込むため、RAM を `30-40mb` 使用していました。現在は `~1.2mb` です。+- 前回の更新では、大きなリクエストプールを使う場合のメモリ使用量が以前の約 32% になりました。今回はキャッシュをさらに調整し、使用量をそれよりも減らしました。+- パーサー全体が 2-5% 高速になりました。++**_ご支援とご寄付に感謝します!_**++## [v0.2.97](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.97) - 2025-03-15 {#v0.2.97}++**Scrapling の機能を十分に使うために、すべてのユーザーにとって重要な更新です**++### 変更内容 {#v0.2.97-what-s-changed}+#### すべての Fetcher でメモリ使用量を削減し、少し高速化 {#v0.2.97-lower-memory-usage-and-small-speed-increase-across-all-fetchers}+- ライブラリ全体でキャッシュサイズに新しい制限を設けました。大量のリクエストや操作を行うとき、メモリ使用量が以前より大きく減ります。+- Fetcher の多くの部分を書き直し、保守しやすくするとともに、少し高速化しました。++#### バグ修正 {#v0.2.97-bugs-fixed}+- `TextHandler` だけをインポートして文字列以外の値を渡すと、空の文字列になるバグを修正しました。現在は `TextHandler` に渡した値を必ず文字列に変換してから、`TextHandler` に変換します。どの値にもこの処理を適用します。名前のとおり、`TextHandler` は文字列を扱うためのものです!(#45)+- AsyncFetcher のほとんどのメソッドで、`retries` 引数が考慮されないバグを修正しました。++#### その他 {#v0.2.97-miscellaneous}+- すべての Fetcher のほとんどの引数について、型ヒントをより明確で正確にしました。++**_ご支援とご寄付に感謝します!_**++## [v0.2.96](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.96) - 2025-03-05 {#v0.2.96}++**Scrapling の機能を十分に使うために、すべてのユーザーにとって重要な更新です**++### 変更内容 {#v0.2.96-what-s-changed}+1. `-f` オプションを `scrapling install` に追加し、ブラウザの依存関係を強制的に再インストールできるようにしました。`scrapling install -f` を実行することをお勧めします。新しい Camoufox のブラウザバージョンで、`StealthyFetcher` が大きく高速化します :)+2. `TextHandler` のスライスが `TextHandlers` を返すバグを修正し、正しく `TextHandler` を返すようにしました。その型ヒントも修正しました(#41)。+3. `scrapling install` の実行中に、場合によっては Python シェルが開いてしまう問題を修正しました!++## [v0.2.95](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.95) - 2025-02-25 {#v0.2.95}++**Scrapling の機能を十分に使うために、すべてのユーザーにとって重要な更新です**++### 変更内容 {#v0.2.95-what-s-changed}+1. `Fetcher` で、`stealthy_headers` 引数が生成したヘッダーが、ユーザーの指定した `Accept` などのヘッダーを上書きするバグを修正しました(#39)。+2. ヘッダーの生成処理を少し改善したので、速度がわずかに上がるはずです。++## [v0.2.94](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.94) - 2025-02-22 {#v0.2.94}++**Scrapling の機能を十分に使うために、すべてのユーザーにとって重要な更新です**++### 変更内容 {#v0.2.94-what-s-changed}+1. すべての Fetcher に `history` プロパティを追加し、リダイレクトを確認できるようにしました(#32)。+2. `case_sensitive` 引数の処理を、すべての `re`/`re_first` で修正しました。使っていた場合は、コードが返す結果が変わることがあります(期待どおりに動かないと気づいていながら issue を報告しなかったのなら、自業自得かもしれませんね、笑)。+3. 依存関係を更新し、Camoufox エンジン(StealthyFetcher)で `coop` を再び有効にしました。++## [v0.2.93](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.93) - 2025-01-31 {#v0.2.93}++**Scrapling の機能を十分に使うために、すべてのユーザーにとって重要な更新です**++### 変更内容 {#v0.2.93-what-s-changed}+1. パーサー全体で戻り値の型を統一しました。必ず `Adaptor`、`Adaptors`、`TextHandler`、`TextHandlers`、`None` のいずれかを返します。CSS セレクターの組み合わせなどで結果が混在する場合は、リストを返します。手動の型チェックが減ってコードを書きやすくなり、ライブラリが安定し、いつでもメソッドをつなげて呼び出せます。+2. パーサーの多くの部分、特に `Adaptor` クラスを書き直し、より分かりやすく高速にしました。検索メソッドをはじめ、ほとんどのメソッドとプロパティが 5-40% 高速になりました。中にはさらに大きく改善したものもあり、`find_by_regex` は約 60% 高速になりました!automatch 機能も約 5% 高速になりました。+3. `find_all`/`find` メソッドで、渡したフィルターが OR として扱われる場合と AND として扱われる場合があるバグを修正しました。現在は、返されるすべての要素が、渡したすべてのフィルターを満たす必要があります。+4. 正規表現に関するすべてのメソッドが `TextHandler`/`TextHandlers` を返すようになり、メソッドをつなげて呼び出しやすくなりました。+5. **新しい** `below_elements` プロパティを追加しました。DOM ツリー内で現在の要素より下にあるすべての要素を、`Adaptors` オブジェクトとして返します。+6. HTML ソースを文字列として返していたすべてのメソッドとプロパティが、`TextHandler` を返すようになりました。これにより、正規表現などを簡単に使えます。+7. StealthyFetcher が少し高速になり、ステルス性能も向上しました。**Cloudflare Turnstile** など、iframe 内の CAPTCHA もクリックできるようになりました。+8. ライブラリのほぼ半分で、自動補完と型ヒントを大きく改善しました。特に `Adaptor`、`TextHandler`、`TextHandlers` が対象です。+9. `TextHandler` をスライスしたり、インデックスで参照したり、`split` メソッドを使ったりすると、通常の Python 文字列ではなく、別の `TextHandler` を返すようになりました。ほぼすべての標準的な文字列操作とメソッドが `Texthandler` を返すので、いつでもメソッドや関数をつなげて呼び出せます。+10. 小さなバグや誤記を修正しました。たとえば、Fetcher の async_put が PUT ではなく POST リクエストを送っていました 😶🌫️+11. ドキュメントの Web サイトが完成するまでの間に、README を少し改善しました。++バージョン 0.3 までの小さな更新にする予定でしたが、もう少し良くしようと思いました。++## [v0.2.92](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.92) - 2024-12-26 {#v0.2.92}++### 変更内容 {#v0.2.92-what-s-changed}+- 読み込むページに iframe が多い場合、ブラウザ Fetcher のレスポンスが、より信頼できるデータ元を使うようになりました。+- **`Scrapling` のインストールがさらに簡単になりました。pip でインストールし、ターミナルで `scrapling install` を実行すれば準備完了です!**+- パーサーの不正確な型ヒントを修正しました。++## [v0.2.91](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.91) - 2024-12-19 {#v0.2.91}++### 変更内容 {#v0.2.91-what-s-changed}+- 取得を知らせるログが最初のリクエストだけで表示されるバグを修正しました。+- Playwright API はページを開くとき、`goto` に指定した読み込み状態 `["load", "domcontentloaded", "networkidle"]` を満たす最初のレスポンスを返します。そのため、Cloudflare のような待機ページの後で実際のサイトに移動する場合、403 など、最初のステータスコードが返されていました。この更新で、Playwright API を使う `PlaywrightFetcher` と `StealthyFetcher` の両方を修正しました。結果はもう Playwright のこの既定の動作に左右されません。+- `Fetcher` クラスで SOCKS プロキシに対応しました。+- `wait_selector_state` 引数の型ヒントを修正し、自動補完で正しい値が表示されるようにしました。++## [v0.2.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.9) - 2024-12-16 {#v0.2.9}++### 変更内容 {#v0.2.9-what-s-changed}+##### 新機能 {#v0.2.9-new-features}+1. Scrapling に**待望の**非同期サポートを追加しました!`AsyncFetcher` が `Fetcher` の非同期版として加わりました。`StealthyFetcher` と `PlayWrightFetcher` にも、同じオプションを使える新しいメソッド `async_fetch` を追加しました。++```python+>> from scrapling import StealthyFetcher+>> page = await StealthyFetcher().async_fetch('https://www.browserscan.net/bot-detection') # the async version of fetch+>> page.status == 200+True+```++2. `StealthyFetcher` クラスの取得メソッドに、`geoip` 引数を追加しました。有効にすると、IP アドレスに対応する経度、緯度、タイムゾーン、国、ロケールを自動で使い、WebRTC の IP アドレスを偽装します。対象地域での言語の使用割合に基づいて、ブラウザの言語も選んで偽装します。+3. `retries` 引数を `Fetcher`/`AsyncFetcher` クラスに追加しました。`httpx` で行う各リクエストの再試行回数を設定できます。+4. `url_join` メソッドを `Adaptor` と Fetcher に追加しました。相対 URL を現在の URL と結合し、完全な絶対 URL を生成します!+5. `keep_cdata` メソッドを `Adaptor` と Fetcher に追加しました。必要に応じて、パーサーが CDATA を削除しないようにできます。+6. `Adaptor`/`Response` の `body` メソッドが、可能な場合は生の HTML レスポンスを返すようになりました。ライブラリ内では加工しません。+7. `Response` クラスにログ出力を追加しました。Fetcher を使うと、受け取ったレスポンスの情報がログに表示されます。+例:++ ```python+ >> from scrapling.defaults import Fetcher+ >> Fetcher.get('https://books.toscrape.com/index.html')+ [2024-12-16 13:33:36] INFO: Fetched (200) <GET https://books.toscrape.com/index.html> (referer: https://www.google.com/search?q=toscrape)+ >>+ ```++8. `TextHandler` で `.replace()` などの標準的な文字列メソッドを使うと、別の `TextHandler` を返すようになりました。以前は通常の文字列を返していました。+9. ライブラリ全体を大きく高速化し、Fetcher クラス全体のステルス性能も改善しました。+10. `extract_first`\`extract` など、元のオブジェクトと同じ結果を返す単純な関数を追加しました。Scrapy/Parsel ではこれらの関数を使うため、必要に応じてコードを Scrapling に簡単にコピーできるようにするためだけに追加したものです!+11. 多くのコードを書き直し、適切な場所にキャッシュを使うことで、大量のリクエストをまとめて行う場合の速度が大きく上がりました。++##### 互換性に影響する変更 {#v0.2.9-breaking-changes}+- Python 3.8 のサポートを終了しました。(主な理由は Playwright がサポートを終了したためですが、もともと問題の多いバージョンでした。)+- ライブラリ全体から `debug` 引数を削除しました。デバッグを有効にするには、ライブラリをインポートした後で次を実行してください。++ ```python+ >>> import logging+ >>> logging.getLogger("scrapling").setLevel(logging.DEBUG)+ ```++##### バグ修正 {#v0.2.9-bugs-squashed}+1. WebGL を既定で有効にしました。多くの保護機能が、WebGL が有効かどうかを確認するようになったためです。+2. ドキュメントと README の誤りや誤記を修正しました。++##### 使いやすさの改善 {#v0.2.9-quality-of-life-changes}+1. すべてのログを `scrapling` という名前のロガーに統一し、簡単に管理できるようにしました。以前はルートロガーを使っていました。+2. テストフォルダーの構成を整理し、新機能のテストを追加しました。すべてのテストを分かりやすく書き直し、カバレッジを上げるためにテストを増やしました。+3. コードの大部分を書き直し、分かりやすく保守しやすくしました。++> これらはすべて 0.3 で追加する予定でしたが、次のバージョンまで時間がかかるため、先に追加することにしました。次は詳細なドキュメントの Web サイトを完成させ、その後でバージョン 0.3 に取り組みます。++## [v0.2.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.8) - 2024-11-30 {#v0.2.8}++### 変更内容 {#v0.2.8-what-s-changed}+- 小さな更新です。コードを使いやすくするために必要な変更を加え、メインの README の誤記を修正しました(#20)。++## [v0.2.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.7) - 2024-11-26 {#v0.2.7}++### 変更内容 {#v0.2.7-what-s-changed}+##### 新機能 {#v0.2.7-new-features}+- `wait_selector` 引数を `StealthyFetcher` と `PlayWrightFetcher` で使う場合、その後に JavaScript が完全に読み込まれて実行されるまで、通常と同じように再び待つようになりました。`network_idle` も使っていれば、それらを待った後で、ネットワークがアイドル状態になるまで再び待ちます。すべての状態をすでに満たしている場合は、もちろん待ちません。+- `StealthyFetcher` で `disable_ads` 引数を使い、広告を許可するかブロックするかを選べるようになりました。既定では有効で、`ublock origin` アドオンをインストールします。+- `PlayWrightFetcher` のロケールを `locale` 引数で設定できるようになりました。既定値は引き続き `en-US` です。+- `Fetcher` の基本的なリクエストで、`http://username:password@localhost:8030` 形式のプロキシを使えるようになりました。+- `PlayWrightFetcher` のステルスモードを少し改善しました。++##### バグ修正と改善 {#v0.2.7-bugs-squashed-improvements}+1. `PlayWrightFetcher` クラスでプロキシを有効にできるかどうかが、`stealth` モードの有効・無効に左右されなくなりました(ご指摘いただいた [@AbdullahY36](https://github.com/AbdullahY36) に感謝します)。+2. `ResponseEncoding` が、レスポンスの文字コードをページに使えるかどうか確認するようになりました。エラーが起きる場合は、Scrapling が `utf-8` を使います。++## [v0.2.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.6) - 2024-11-24 {#v0.2.6}++### 変更内容 {#v0.2.6-what-s-changed}+##### 新機能 {#v0.2.6-new-features}+- `PlayWrightFetcher` が実際のブラウザを直接使えるようになりました。`real_chrome` 引数を `PlayWrightFetcher.fetch` に渡してください。Chrome がインストールされている必要があります。Scrapling がその Chrome を起動し、ほとんどのオプションを通常どおり使えます。(以前は `cdp_url` 引数でしかできませんでした。)+- 実際のブラウザ向けに生成するヘッダーのバージョンを上げました。++##### バグ修正 {#v0.2.6-bugs-squashed}+1. `BrowserForge` が生成するブラウザヘッダーの形式が古く、一部の保護機能で Scrapling が検出されることが分かりました。そのため、`BrowserForge` は実際の User-Agent の生成にだけ使うようにしました。+2. `hide_canvas` 引数を既定で無効にしました。Google の ReCaptcha に検出されるためです。++## [v0.2.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.5) - 2024-11-23 {#v0.2.5}++### 変更内容 {#v0.2.5-what-s-changed}++##### バグ修正 {#v0.2.5-bugs-squashed}+- 'wait_selector' 引数が 1 個を超える要素に一致した場合に起きるエラーを処理するようにしました。`StealthyFetcher` と `PlayWrightFetcher` が対象です。+- `content_type` ヘッダーの値に `charset` などのパラメーターが含まれる場合の文字コードを修正しました([#12](https://github.com/D4Vinci/Scrapling/issues/12) を報告してくださった @andyfcx に感謝します)。++##### 使いやすさの改善 {#v0.2.5-quality-of-life}+- コードの新しい部分を確認するテストを追加し、テストをスレッドで実行するようにしました。+- Sphinx の apidoc などのツールで正しく表示されるよう、docstring を更新しました。++##### 新しい貢献者 {#v0.2.5-new-contributors}+- @andyfcx が [#13 ](https://github.com/D4Vinci/Scrapling/pull/13) で初めて貢献しました。++## [v0.2.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.4) - 2024-11-20 {#v0.2.4}++### 変更内容 {#v0.2.4-what-s-changed}++##### バグ修正 {#v0.2.4-bugs-squashed}+- `network_idle` 引数を使った後でレスポンスのバイト列を取得する際のバグを修正しました。`StealthyFetcher` と `PlayWrightFetcher` の両方が対象です。<br/>このバグで、次のエラーメッセージが出ていました。++ ```+ Response.body: Protocol error (Network.getResponseBody): No resource with given identifier found+ ```++- PlayWright API は、レスポンスのステータステキストを空で返すことがあります。その場合、`Scrapling` が内部でステータステキストを求めるようにしました。`StealthyFetcher` と `PlayWrightFetcher` の両方が対象です。++## [v0.2.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.3) - 2024-11-19 {#v0.2.3}++### 変更内容 {#v0.2.3-what-s-changed}++##### バグ修正 {#v0.2.3-bugs-squashed}+- pip でのインストールに関するバグを修正しました。このバグで、PlayWright Fetcher のステルスモードがまったく動作しなくなっていました。++## [v0.2.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.2) - 2024-11-16 {#v0.2.2}++### 変更内容 {#v0.2.2-what-s-changed}+##### 新機能 {#v0.2.2-new-features}+- 作成する `Adaptor` オブジェクトに引数を渡さず、既定値を使いたい場合は、代わりに次のインポートでコードを簡潔にできます。++ ```python+ >> from scrapling.default import Fetcher, StealthyFetcher, PlayWrightFetcher+ >> page = Fetcher.get('https://example.com', stealthy_headers=True)+ ```++ それ以外の場合++ ```python+ >> from scrapling import Fetcher, StealthyFetcher, PlayWrightFetcher+ >> page = Fetcher(auto_match=False).get('https://example.com', stealthy_headers=True)+ ```++##### バグ修正 {#v0.2.2-bugs-squashed}+1. `Response` オブジェクトのバグを修正しました。昨日のパッチ v0.2.1 で入り、一部の入れ子の選択や解析で起きていた問題です。++## [v0.2.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.1) - 2024-11-15 {#v0.2.1}++### 変更内容 {#v0.2.1-what-s-changed}+##### 新機能 {#v0.2.1-new-features}+1. すべての Fetcher が返す `Response` オブジェクトが、`Adaptor` オブジェクトと同じように使えるようになりました。ただし、`status`、`reason`、`cookies`、`headers`、`request_headers` 属性が追加されています。`cookies`、`headers`、`request_headers` は常に `dictionary` 型です。<br/>そのため、次のように書けます。++ ```python+ >> from scrapling import Fetcher+ >> page = Fetcher().get('https://example.com', stealthy_headers=True)+ >> print(page.status)+ 200+ >> products = page.css('.product')+ ```++ 以前の書き方はこちらです。++ ```python+ >> from scrapling import Fetcher+ >> fetcher = Fetcher().get('https://example.com', stealthy_headers=True)+ >> print(fetcher.status)+ 200+ >> page = fetcher.adaptor+ >> products = page.css('.product')+ ```++ ただし、後方互換性のために `.adaptor` プロパティは引き続き使えます。++2. `StealthyFetcher` と `PlayWrightFetcher` の両方で、取得メソッドに `proxy` 引数を渡せるようになりました。文字列か辞書を受け付けます。+3. `StealthyFetcher` クラスに `os_randomize` 引数を追加し、`fetch` メソッドで使えるようにしました。有効にすると、Scrapling が OS のフィンガープリントをランダムに選びます。既定では現在の OS に合わせます。++##### バグ修正 {#v0.2.1-bugs-squashed}+1. `Fetcher` クラスでヘッダーを渡す際に起きるバグを修正しました。+2. Fetcher クラスが渡す JSON レスポンスを解析する際のバグを修正しました。++##### 使いやすさの改善 {#v0.2.1-quality-of-life-changes}+1. テキストを返す前に HTML コメントを削除しようとしていましたが、一部のケースでエラーが起き、コードも必要以上に複雑になっていました。そのため、lxml の既定の動作に戻しました。**セレクターなど、要素のテキストを使う処理が少し速くなります**。lxml/parsel/scrapy 特有の分かりにくいテキスト分割を避けるため、テキストを返す前に HTML コメントを削除したい場合は、`keep_comments` 引数を既定の True のままにしてください。++## [v0.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2) - 2024-11-11 {#v0.2}++### 変更内容 {#v0.2-what-s-changed}+##### 新機能 {#v0.2-new-features}+1. `Fetchers` 機能を追加しました。3 種類の主なクラスで、豊富なオプションを使って Scrapling にページを取得させられます!+ - `Fetcher` クラスは、基本的な HTTP リクエストを行います。+ - `StealthyFetcher` クラスは、[ステルス用に修正した Firefox](https://github.com/daijro/camoufox) を使う、完全なステルス機能付きの Fetcher です。+ - `PlayWrightFetcher` クラスは、通常の PlayWright、私が作ったステルスモード付きの PlayWright、CDP 経由の実際のブラウザ、[NSTBrowser](https://app.nstbrowser.io/r/1vO5e5) の [docker browserless](https://hub.docker.com/r/nstbrowser/browserless) で、ブラウザによるリクエストを行えます!+2. 新しい `find_all`/`find` メソッドを追加しました。魔法のように、ページの要素を簡単に探せます!+3. `filter` と `search` メソッドを `Adaptors` クラスに追加しました。複数の `Adaptor` オブジェクトをまとめて操作しやすくなります。+4. 使いやすくするために、`css_first` と `xpath_first` メソッドを追加しました。+5. 新しい `TextHandlers` クラスを追加しました。`TextHandler` オブジェクトをまとめて操作するためのもので、`Adaptors` クラスと同様に使えます。+6. `generate_full_css_selector` と `generate_full_xpath_selector` メソッドを追加しました。++##### バグ修正 {#v0.2-bugs-squashed}+1. `Adaptors` クラスの `re_first` が、内部のすべての `Adaptor` オブジェクトから最初に一致した結果を返すようになりました。以前は誤って、`re_first` の結果をすべての `Adaptor` オブジェクトから返していました。+2. 選択した要素からテキストを返す場合(CSS の `::text` 関数など)、`.css` や `.xpath` などのメソッドで `Adaptor` オブジェクトが返すのは、文字列のリストではなく `TextHandlers` になりました。そのため、`page.css('something::text').re_first(r'regex_pattern').json()` と書けます。以前の `page.css('something::text')[0].re_first(r'regex_pattern').json()` は不要です。+3. `Adaptor`/`Adaptors` の re/re_first の引数を、`TextHandler` と統一しました。`clean_match` と `case_sensitive` 引数を使えます。+4. `auto_match` 引数は `Adaptor` の初期化時に既定で有効になりました。ただし、実際に使うには、要素を選ぶときにも有効にする必要があります。(バグ修正ではなく、設計上の判断です。)+5. 多くの場所で型注釈を修正し、Scrapling でコードを書くときの自動補完を改善しました。++##### 使いやすさの改善 {#v0.2-quality-of-life-changes}+1. `css_selector` と `xpath_selector` を `generate_css_selector` と `generate_xpath_selector` に改名しました。名前を分かりやすくし、コード入力中の自動補完を妨げないようにするためです。+2. 既存コードの多くを `core` サブパッケージに整理し、ほかの設計も見直しました。コードを分かりやすくし、今後の保守を簡単にするためです。+3. テストフォルダーを分かりやすい構成に整理し、新機能のテストを追加しました。GitHub 上で tox 環境をキャッシュするようにして、各コミットの自動テストも高速化しました。++## [v0.1.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.2) - 2024-10-16 {#v0.1.2}++**変更履歴**:++- `keep_comments` 引数が想定どおりに動作しないバグを修正しました。+- テキストを抽出する前に要素から HTML コメントを自動で削除し、Lxml の異なる動作を避けるようにしました。たとえば、次の例です。++ ```python+ >>> page = Adaptor('<span>CONDITION: <!-- -->Excellent</span>', keep_comments=True)+ >>> page.css('span::text')+ ['CONDITION: ', 'Excellent']+ ```++ 以前は Lxml の既定の動作によって上の結果になっていましたが、現在は完全なテキスト 'CONDITION: Excellent' を返します。+ parsel\scrapy にも同じ動作があるため、ここで対処したいと考えました。++- `pip uninstall scrapling` などを実行しても、ライブラリが作成した SQLite データベースのファイルが削除されないバグを修正しました。++## [v0.1.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.1) - 2024-10-14 {#v0.1.1}++小さな修正++## [v0.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1) - 2024-10-13 {#v0.1}++**すべての変更履歴**:<https://github.com/D4Vinci/Scrapling/commits/v0.1>diff --git a/docs/locales/ko/changelog.md b/docs/locales/ko/changelog.mdnew file mode 100644index 0000000..ba30b83--- /dev/null+++ b/docs/locales/ko/changelog.md@@ -0,0 +1,1279 @@+---+title: "Scrapling 변경 기록"+description: "새 기능, 수정 사항, 호환성에 영향을 주는 변경 사항을 담은 Scrapling 릴리스 노트입니다."+---++# 변경 기록 {#changelog}++[GitHub 릴리스](https://github.com/D4Vinci/Scrapling/releases)에서 가져온 Scrapling의 주요 변경 사항을 모두 모았습니다.++## [v0.4.15](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.15) - 2026-08-23 {#v0.4.15}++**올해 가장 큰 릴리스 중 하나입니다. MCP 서버를 새롭게 구성하고, 한 줄로 RAG용 Markdown을 만들 수 있게 했습니다. Cloudflare 검사 처리도 개선했으며, 자동화를 위해 브라우저 탭을 열린 상태로 유지합니다 🚀**++!!! warning "주의"++ **이 릴리스에는 MCP 서버의 호환성에 영향을 주는 변경 사항이 있습니다. 업데이트 전에 [호환성에 영향을 주는 변경 사항](https://github.com/D4Vinci/Scrapling/blob/v0.4.15/docs/ai/mcp-server.md#breaking-changes)을 확인하세요.**++### 🚀 새 기능과 사용 편의 개선 {#v0.4.15-new-stuff-and-quality-of-life-changes}++- **브라우저 탭을 열린 상태로 유지하고 다음 요청에서도 재사용합니다**([문서](fetching/stealthy.md#session-management) 참고):+ - 모든 브라우저 세션이 요청 후에도 탭을 유지합니다. 다음 요청은 새 탭을 여는 대신 사용 중이 아닌 탭을 재사용합니다.+ - 각 요청은 할당받은 탭에 제한 시간, 헤더, 리소스 차단 등 자신의 설정을 다시 적용합니다. 따라서 다른 요청의 설정이 남지 않습니다.+ - 오류가 난 탭은 닫고 새 탭으로 교체합니다. 새 `close_pages()` 메서드로 열린 탭을 모두 닫을 수 있습니다.+ - 가져온 페이지는 로드된 상태로 유지됩니다. 따라서 다음 요청의 `page_setup` 함수는 다른 페이지로 이동하기 전에 그 페이지에서 실행됩니다. 이를 바탕으로 여러 요청에 걸친 자동화 작업을 연결할 수 있습니다.++- **`Response.markdown()`으로 어떤 페이지든 LLM에서 바로 쓸 수 있는 깔끔한 Markdown으로 바꿀 수 있습니다**([문서](ai/building-rag-systems.md) 참고):++ ```python+ from scrapling.fetchers import Fetcher++ markdown = Fetcher.get("https://example.com").markdown(main_content_only=True)+ ```++ - MCP 서버와 같은 정리 과정을 거쳐, 스크립트와 스타일, 숨겨진 프롬프트 인젝션 내용을 항상 먼저 제거합니다.+ - 필요한 요소만 변환하려면 `css_selector`를 전달하세요.+ - 새 선택 의존성 그룹 `rag`(`pip install "scrapling[rag]"`)로 사용할 수 있습니다. `ai`/`shell`/`all` 그룹에도 포함됩니다.++- **웹사이트 전체를 크롤링해 RAG 파이프라인용 Markdown 문서 모음을 만드는 `SiteToMarkdownSpider` 템플릿을 추가했습니다**([문서](ai/building-rag-systems.md) 참고):++ ```python+ from scrapling.spiders import SiteToMarkdownSpider++ class DocsSpider(SiteToMarkdownSpider):+ name = "docs"+ start_urls = ["https://example.com/docs/"]+ allowed_domains = {"example.com"}+ output_dir = "docs_markdown"++ result = DocsSpider().start()+ result.items.to_jsonl("docs.jsonl")+ ```++ - 페이지마다 `url`/`title`/`markdown`을 가진 항목 하나를 반환합니다. 선택 사항인 `output_dir`을 지정하면 페이지마다 Markdown 파일 하나를 저장합니다.+ - `max_pages`로 크롤링할 페이지 수를 제한합니다. `CrawlSpider`를 기반으로 하므로 `rules()`를 재정의해 어떤 링크를 따라갈지 자유롭게 정할 수 있습니다.++- **MCP 서버를 새롭게 구성했습니다(호환성에 영향을 줍니다)**([호환성에 영향을 주는 변경 사항](https://github.com/D4Vinci/Scrapling/blob/v0.4.15/docs/ai/mcp-server.md#breaking-changes)과 [문서](ai/mcp-server.md) 참고):+ - 도구 13개를 두 모드로 나눴습니다. 일회성 도구(`fetch`, `bulk_fetch`, `stealthy_fetch`, `bulk_stealthy_fetch`)는 항상 자체 브라우저를 실행하고 실제 기본값을 표시합니다. 세션 도구는 한 번 열어 둔 세션을 사용합니다.+ - 새 `session_fetch` 도구는 브라우저 세션으로 페이지를 가져옵니다. `open_session`은 이제 브라우저 수준의 설정만 관리하며, 세션에 실제로 적용된 설정을 AI 에이전트에 반환합니다.+ - `get` 도구의 이름을 `make_request`로 바꿨으며, 모든 HTTP 메서드를 지원합니다.+ - 새 `open_request_session`과 `session_make_request` 도구로 AI가 지속적인 HTTP 세션을 사용할 수 있습니다. 요청 사이에 쿠키와 브라우저 지문을 유지합니다.+ - 이 변경으로 페이지를 가져올 때 세션 설정이 초기화되는 문제도 해결했습니다. 이 문제는 @Yigtwxx가 [#418](https://github.com/D4Vinci/Scrapling/pull/418)에서 처음 수정했습니다.++- **MCP 서버의 HTTP 전송은 기본적으로 인증을 요구하고 localhost에 바인딩합니다(호환성에 영향을 줍니다)**. @yamantaka-singh의 [#414](https://github.com/D4Vinci/Scrapling/pull/414) 기여입니다([#413](https://github.com/D4Vinci/Scrapling/issues/413) 수정, [문서](ai/mcp-server.md#authentication) 참고):+ - Bearer 토큰을 요구하려면 `--auth-token` 또는 환경 변수 `SCRAPLING_MCP_AUTH_TOKEN`을 전달하세요. 의도적으로 인증 없이 서비스하려면 `--no-auth`를 전달하세요.+ - 네트워크에서 들어오는 연결을 허용하려면 `--host 0.0.0.0`을 전달하세요.++### 🐛 버그 수정 {#v0.4.15-bug-fixes}++- **브라우저 로캘과 관계없이 Cloudflare Turnstile/Interstitial 검사를 통과하며, 창 없는 모드에서 상호작용이 필요한 검사를 무한히 반복하지 않습니다**. 스텔스 페이지가 검사 처리 중에 비정상 종료되는 문제도 해결했습니다. @subediparas5의 [#412](https://github.com/D4Vinci/Scrapling/pull/412) 기여를 포함합니다([#411](https://github.com/D4Vinci/Scrapling/issues/411)과 [#422](https://github.com/D4Vinci/Scrapling/issues/422) 수정).+- **`find`/`find_all`에서 `class_`를 사용하면 클래스가 여러 개인 요소를 알림 없이 놓치는 문제를 수정했습니다**. @yetval의 [#410](https://github.com/D4Vinci/Scrapling/pull/410) 기여입니다. **빈 `class_` 값과 이스케이프하지 않은 CSS 문자열 값 문제도 수정했습니다**. @yamantaka-singh의 [#417](https://github.com/D4Vinci/Scrapling/pull/417) 기여입니다.+- **`development_mode`에서 캐시한 응답을 다시 사용할 때 요청 메타데이터가 사라지는 문제를 수정했습니다**. @Yigtwxx의 [#419](https://github.com/D4Vinci/Scrapling/pull/419) 기여입니다.+- **`retries`가 1보다 작은 HTTP 요청이 전송되지도 않고 실패하는 문제를 수정했습니다**. @Yigtwxx의 [#420](https://github.com/D4Vinci/Scrapling/pull/420) 기여입니다.++### 문서 {#v0.4.15-docs}++- **웹사이트의 구성을 정리했습니다**. 새 “AI와 함께 사용하기” 섹션에 MCP 서버, 새 [Agent Skill](ai/agent-skill.md) 페이지, [RAG 시스템 만들기](ai/building-rag-systems.md) 가이드를 모았습니다. BeautifulSoup 마이그레이션 가이드는 “통합과 마이그레이션” 섹션의 Scrapy 통합 옆으로 옮겼습니다.+- **저장소에 [변경 기록](changelog.md)을 추가했습니다**. 지금까지의 모든 릴리스 노트를 포함합니다.++## [v0.4.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.14) - 2026-08-10 {#v0.4.14}++**`uv` 설치 문제를 해결하는 작은 유지 보수 릴리스입니다 🔧**++### 🐛 버그 수정 {#v0.4.14-bug-fixes}++- **`uv`가 기본적으로 v0.4.13 설치를 거부하고 알림 없이 이전 버전으로 돌아가는 문제를 수정했습니다**. 이전 릴리스는 `curl_cffi`의 사전 릴리스 버전을 요구했지만, `uv`는 명시적으로 허용하지 않으면 사전 릴리스 버전을 설치하지 않습니다.+이제 모든 의존성을 안정 버전으로 설치할 수 있습니다([#407](https://github.com/D4Vinci/Scrapling/issues/407) 수정).++## [v0.4.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.13) - 2026-08-09 {#v0.4.13}++**피드 스파이더와 더 똑똑한 MCP 서버를 제공하는 업데이트입니다 🎉**++### 🚀 새 기능과 사용 편의 개선 {#v0.4.13-new-stuff-and-quality-of-life-changes}++- **피드 스파이더 템플릿을 추가했습니다**. `XMLFeedSpider`는 XML 피드(RSS, Atom, 상품 피드 등)의 노드를 순회하고, `CSVFeedSpider`는 CSV 행을 딕셔너리로 순회합니다. 둘 다 gzip으로 압축한 피드를 자동으로 풉니다([문서](spiders/generic-templates.md) 참고).++ ```python+ from scrapling.spiders import XMLFeedSpider++ class RSSSpider(XMLFeedSpider):+ name = "rss"+ start_urls = ["https://example.com/feed.xml"]++ async def parse_node(self, response, node):+ yield {"title": node.findtext("title"), "link": node.findtext("link")}++ result = RSSSpider().start()+ ```++- **MCP 서버를 MCP SDK v2로 업그레이드하고 더 똑똑하게 만들었습니다**. AI 에이전트에 도구를 효율적으로 사용하는 방법을 알려 주는 지침을 포함합니다. 각 도구가 어노테이션을 선언하므로 Claude Code 같은 클라이언트는 읽기 전용 도구를 자동으로 승인할 수 있습니다. 토큰을 아끼도록 도구 설명도 줄였습니다. 서버의 버전과 로고도 MCP 클라이언트에 알립니다([문서](ai/mcp-server.md) 참고).+- **`scrapling-mcp` 명령을 추가했습니다**. `scrapling mcp`에 직접 대응하므로, 단일 명령을 요구하는 MCP 클라이언트와 레지스트리에 한 줄로 Scrapling을 등록할 수 있습니다.+- **Playwright/Patchright와 브라우저의 버전 고정을 해제했습니다**. 생성한 브라우저 User-Agent는 이제 설치된 Playwright/Patchright가 실제로 구동하는 Chromium 버전과 항상 일치합니다. 따라서 Scrapling이 버전을 고정할 필요가 없어 자유롭게 업그레이드할 수 있습니다. 업데이트 후 `scrapling install --force`를 실행해 브라우저를 갱신하세요.++### 🐛 버그 수정 {#v0.4.13-bug-fixes}++- **지문 데이터 패키지가 브라우저 버전보다 뒤처졌을 때 Scrapling을 임포트하면 `browserforge`의 ValueError로 비정상 종료되는 문제를 수정했습니다**([#394](https://github.com/D4Vinci/Scrapling/issues/394), [#396](https://github.com/D4Vinci/Scrapling/issues/396), [#400](https://github.com/D4Vinci/Scrapling/issues/400) 수정).+- **MCP 일괄 브라우저 도구의 페이지 풀 크기가 잘못 설정되는 문제를 수정했습니다**. 이 문제로 `bulk_fetch`는 한 번에 URL 50개를 넘게 처리하면 실패했고, `bulk_stealthy_fetch`는 탭 하나로 모든 URL을 가져왔습니다. @Yigtwxx의 [#393](https://github.com/D4Vinci/Scrapling/pull/393) 기여입니다.++### 프로젝트 {#v0.4.13-project}++- **새 [AI 기여 정책](https://github.com/D4Vinci/Scrapling/blob/main/AI_POLICY.md)을 추가했습니다**. AI를 활용한 기여는 환영하지만 PR이나 이슈에 사용 사실을 밝혀야 합니다. AI 사용 사실을 밝히지 않은 생성물로 보이는 제출물은 라벨을 붙이고 닫습니다.++## [v0.4.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.12) - 2026-07-26 {#v0.4.12}++**스파이더가 크롤링하는 웹사이트에 맞춰 더 똑똑하게 동작하도록 하는 릴리스입니다**++### 🚀 새 기능과 사용 편의 개선 {#v0.4.12-new-stuff-and-quality-of-life-changes}++- **스파이더가 AutoThrottle로 속도를 스스로 조정할 수 있습니다.** 너무 느리거나 차단을 일으킬 수 있는 `download_delay`를 추측할 필요가 없습니다. 스파이더가 각 웹사이트의 응답 속도를 측정해 도메인별 지연을 자동으로 조정합니다. 사이트가 요청을 차단하거나 요청 수를 제한하면, 제한이 없어질 때까지 지연을 두 배로 늘리거나 `Retry-After` 헤더가 지정한 시간만큼 기다립니다. 이후 다시 속도를 높입니다. 설정한 `download_delay`와 robots.txt의 `Crawl-delay`는 계속 최소 대기 시간으로 지킵니다([문서](spiders/advanced.md#autothrottle) 참고).++ ```python+ class MySpider(Spider):+ name = "adaptive"+ start_urls = ["https://example.com"]+ autothrottle_enabled = True+ autothrottle_start_delay = 2.0+ autothrottle_max_delay = 30.0+ autothrottle_block_backoff = True+ ```++- **결과를 CSV와 XML로 내보낼 수 있습니다**. 기존 JSON/JSONL 내보내기도 계속 사용할 수 있습니다. 항목마다 키가 달라도 빠짐없이 내보내며, 중첩된 값은 JSON으로 기록합니다([문서](spiders/getting-started.md) 참고).++ ```python+ result = MySpider().start()+ result.items.to_csv("products.csv")+ result.items.to_xml("products.xml")+ ```++- **MCP 서버에서 인증을 요구할 수 있습니다**. 자신의 컴퓨터에서만 쓰지 않고 안전하게 외부에 공개할 수 있습니다. 토큰이 없는 요청은 거부하며, 서버가 응답할 호스트 이름도 제한할 수 있습니다([문서](ai/mcp-server.md) 참고).++ ```bash+ scrapling mcp --http --auth-token "$(openssl rand -hex 32)"+ ```++- **브라우저가 HTTP 형식의 CDP URL도 받습니다**. WebSocket에만 한정되지 않습니다. 관리형 브라우저 서비스의 `wss://` 주소뿐 아니라, `--remote-debugging-port=9222`로 직접 실행한 Chrome에도 브라우저 Fetcher나 MCP 세션을 연결할 수 있습니다.++- **게시하는 Docker 이미지에 릴리스 버전 태그를 붙입니다**. 이제 `latest`뿐 아니라 원하는 버전을 정확히 고정할 수 있습니다. @JanRK의 [#384](https://github.com/D4Vinci/Scrapling/pull/384) 기여입니다.++### 🐛 버그 수정 {#v0.4.12-bug-fixes}++- **브라우저 엔진의 응답을 캐시하면 쿠키가 모두 사라지는 문제를 수정했습니다**. 스파이더 개발 모드에서 쿠키에 의존하는 세션이나 인증 로직이 알림 없이 동작하지 않게 되는 원인이었습니다. @amitvijapur의 [#379](https://github.com/D4Vinci/Scrapling/pull/379) 기여입니다([#376](https://github.com/D4Vinci/Scrapling/issues/376) 수정).++- **`StealthyFetcher`가 시스템 설정을 따르지 않고 모든 브라우저에 `en-US` 로캘을 강제하는 문제를 수정했습니다**. 사이트가 로캘과 IP 주소의 불일치를 보고 의심스러운 요청으로 판단해, Google에서 429를 반환하는 등의 문제가 생겼습니다([#381](https://github.com/D4Vinci/Scrapling/issues/381) 수정).++- **저장 시스템에서 혼동을 주는 오류 메시지를 수정했습니다**. 데이터 삽입 후 남아 있던 불필요한 호출도 제거했습니다. @fix2015의 [#377](https://github.com/D4Vinci/Scrapling/pull/377) 기여입니다.++### 성능 {#v0.4.12-performance}++- **`get_all_text()`의 실행 시간이 이제 노드 수에 비례합니다(O(nodes))**. 각 텍스트 노드의 조상을 매번 따라가지 않으므로, 깊게 중첩된 페이지에서 약 5-6배 빠르게 동작합니다. @yetval의 [#378](https://github.com/D4Vinci/Scrapling/pull/378) 기여입니다.++## [v0.4.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.11) - 2026-07-12 {#v0.4.11}++**첫 플랫폼별 스파이더 템플릿, 더 빠른 파서, 중요한 수정 사항을 담은 업데이트입니다 🎉**++### 🚀 새 기능과 사용 편의 개선 {#v0.4.11-new-stuff-and-quality-of-life-changes}++- **첫 플랫폼별 스파이더 템플릿 `ShopifySpider`를 추가했습니다!** Shopify 기반 상점의 JSON API로 모든 상품을 추출할 수 있습니다. 사이트의 HTML을 다룰 필요가 없습니다. 이 클래스를 상속하고 상점 도메인만 설정하면 됩니다([문서](spiders/platform-templates.md) 참고).++ ```python+ from scrapling.spiders import ShopifySpider++ class MyStore(ShopifySpider):+ target_website = "example.com"++ result = MyStore().start()+ ```++- **CLI 브라우저 명령에 `--executable-path`를 추가했습니다**. `scrapling extract fetch`와 `scrapling extract stealthy-fetch` 모두 원하는 Chromium 호환 브라우저 실행 파일을 지정할 수 있습니다. 옵션을 전달하지 않으면 환경 변수 `SCRAPLING_EXECUTABLE_PATH`를 사용하므로 MCP 서버와 같은 기능을 제공합니다([#371](https://github.com/D4Vinci/Scrapling/issues/371) 해결).++ ```bash+ scrapling extract fetch "https://example.com" page.html --executable-path "/path/to/chromium"+ ```++### 🤖 사용 편의 개선 {#v0.4.11-quality-of-life-changes}+- **`find_by_text`와 `find_by_regex`가 최대 약 2배 빨라졌습니다**. `first_match`가 켜진 경우(기본값) 요소를 필요할 때만 객체로 감싸므로 첫 일치 항목에서 검색을 멈춥니다. @yetval의 [#370](https://github.com/D4Vinci/Scrapling/pull/370) 기여입니다.+- **모든 라이브러리의 최신 버전과 비교한 새 수치로 벤치마크를 갱신했습니다.**+- **기여 규칙을 갱신했습니다.**++### 🐛 버그 수정 {#v0.4.11-bug-fixes}++- **제어 문자가 있는 페이지에서 MCP 서버의 가져오기 도구가 비정상 종료되는 문제를 수정했습니다**. `All strings must be XML compatible` 오류가 발생하던 문제입니다. @yetval의 [#368](https://github.com/D4Vinci/Scrapling/pull/368) 기여입니다([#366](https://github.com/D4Vinci/Scrapling/issues/366) 수정).++## [v0.4.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.10) - 2026-07-04 {#v0.4.10}++**새 Scrapy 통합 기능과 커뮤니티의 여러 수정 사항을 담은 업데이트입니다 🎉**++### 🚀 새 기능과 사용 편의 개선 {#v0.4.10-new-stuff-and-quality-of-life-changes}++- **Scrapy 통합을 추가했습니다**. 기존 Scrapy 프로젝트를 다시 작성하지 않고 Scrapling의 파싱 API를 사용할 수 있습니다. 스파이더 콜백에 `scrapling_response` 데코레이터를 붙이면 받는 응답이 Scrapling의 `Response`로 바뀝니다. 크롤링은 계속 Scrapy가 처리합니다([문서](integrations/scrapy.md) 참고):++ ```python+ import scrapy+ from scrapling.integrations.scrapy import scrapling_response++ class QuotesSpider(scrapy.Spider):+ name = "quotes"+ start_urls = ["https://quotes.toscrape.com"]++ @scrapling_response+ def parse(self, response): # `response` is now a Scrapling Response+ first_quote = response.find_by_text("The world as we have created it", partial=True)+ for quote in [first_quote, *first_quote.find_similar()]:+ yield {"text": quote.get_all_text(strip=True)}+ ```++- **MCP 서버의 모든 브라우저 도구에서 원하는 Chromium 호환 브라우저를 사용할 수 있습니다**. `scrapling mcp --executable-path "/path/to/chromium"` 또는 환경 변수 `SCRAPLING_EXECUTABLE_PATH`로 공통 설정을 하거나, `executable_path` 인수로 요청별로 지정할 수 있습니다. @samrusani의 [#360](https://github.com/D4Vinci/Scrapling/pull/360) 기여입니다([#347](https://github.com/D4Vinci/Scrapling/issues/347) 해결).+- **모든 브라우저와 지문을 갱신했습니다**. 업데이트 후 `scrapling install --force`를 실행해 적용하세요.++### 🐛 버그 수정 {#v0.4.10-bug-fixes}++- **UTF-8이 아닌 웹사이트에서 브라우저 Fetcher가 깨진 텍스트(mojibake)를 반환하는 문제를 수정했습니다**. @yehudalevy-collab의 [#365](https://github.com/D4Vinci/Scrapling/pull/365) 기여입니다([#364](https://github.com/D4Vinci/Scrapling/issues/364) 수정).+- **`LinkExtractor`가 `.tar.gz` 같은 복합 확장자를 걸러내지 못하는 문제를 수정했습니다**. @renbkna의 [#359](https://github.com/D4Vinci/Scrapling/pull/359) 기여입니다([#349](https://github.com/D4Vinci/Scrapling/issues/349) 수정).+- **크롤링을 일시 중지할 때 실행 중인 요청이 체크포인트에서 사라지는 문제를 수정했습니다. 이제 재개할 때 해당 요청을 건너뛰지 않습니다**. @yetval의 [#358](https://github.com/D4Vinci/Scrapling/pull/358) 기여입니다.+- **스파이더가 robots.txt의 `Request-rate` 지시에서 잘못된 크롤링 지연을 계산하는 문제를 Protego 업그레이드로 수정했습니다**. @Disaster-Terminator가 [#355](https://github.com/D4Vinci/Scrapling/pull/355)에서 테스트도 이에 맞게 수정했습니다.++### 문서 {#v0.4.10-docs}++- **스텔스 모드에서 `init_script`가 Patchright의 격리된 실행 컨텍스트와 상호작용하는 방식을 명확히 설명했습니다**. @mturac의 [#353](https://github.com/D4Vinci/Scrapling/pull/353) 기여입니다([#350](https://github.com/D4Vinci/Scrapling/issues/350) 해결).+- **에이전트 스킬을 [skills.sh](https://skills.sh/D4Vinci/Scrapling)로 설치하는 방법을 추가했습니다**. @ob-aion의 [#363](https://github.com/D4Vinci/Scrapling/pull/363) 기여입니다.++## [v0.4.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.9) - 2026-06-07 {#v0.4.9}++**커뮤니티에서 보고한 여러 문제를 수정한 유지 보수 업데이트입니다 🛠️**++### 🚀 새 기능과 사용 편의 개선 {#v0.4.9-new-stuff-and-quality-of-life-changes}++- **모든 브라우저와 지문을 갱신했습니다**. 업데이트 후 `scrapling install --force`를 실행해 적용하세요.+- **CLI에 `--version` 플래그를 추가했습니다**. @ETM-Code의 [#303](https://github.com/D4Vinci/Scrapling/pull/303) 기여입니다([#299](https://github.com/D4Vinci/Scrapling/issues/299) 해결).++### 🐛 버그 수정 {#v0.4.9-bug-fixes}++- **HTTP 세션에서 세션 수준의 `proxy` 인수가 알림 없이 무시되는 문제를 수정했습니다**. 실제 IP가 노출될 수 있던 문제입니다([#295](https://github.com/D4Vinci/Scrapling/issues/295) 해결). 이제 세션 수준의 `proxy`와 요청별 `proxies` 인수를 섞어 쓰거나 그 반대로 쓰면, 하나를 알림 없이 버리지 않고 오류를 냅니다.+- **`init_script`와 `user_data_dir`을 함께 쓰면 브라우저의 페이지 이동이 실패하는 문제를 수정했습니다**([#294](https://github.com/D4Vinci/Scrapling/issues/294) 해결).+- **사이트가 `Content-Type` 헤더의 charset 값을 따옴표로 감쌀 때 인코딩을 잘못 감지하는 문제를 수정했습니다**. @Bortlesboat의 [#323](https://github.com/D4Vinci/Scrapling/pull/323) 기여입니다.+- **적응형 요소 재탐색에서 `IndexError`가 발생하는 문제를 수정했습니다. `auto_save`가 켜져 있을 때 발생하던 문제입니다**. @Mubashirrrr의 [#340](https://github.com/D4Vinci/Scrapling/pull/340) 기여입니다.+- **Windows에서 스파이더 체크포인트와 캐시 저장 중 비정상 종료되는 문제를 수정했습니다**. @MrStarkEG의 [#344](https://github.com/D4Vinci/Scrapling/pull/344) 기여입니다.+- **속성 수가 다른 요소에 대해 `find_similar`가 유사도 점수를 잘못 계산하는 문제를 수정했습니다**([#322](https://github.com/D4Vinci/Scrapling/issues/322) 해결).++### 문서 {#v0.4.9-docs}++- **기본 설치에는 파서 엔진만 포함된다는 점을 명확히 했습니다**. Fetcher와 스파이더는 선택 의존성 그룹을 설치해야 합니다([#343](https://github.com/D4Vinci/Scrapling/issues/343) 해결).+- **남아 있던 예제의 Docker 이미지 이름을 수정했습니다**. @evanclan의 [#315](https://github.com/D4Vinci/Scrapling/pull/315) 기여입니다.+- **기여 가이드의 잘못된 링크를 수정했습니다**. @Bortlesboat의 [#320](https://github.com/D4Vinci/Scrapling/pull/320) 기여입니다.++## [v0.4.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.8) - 2026-05-11 {#v0.4.8}++**크롤링 프레임워크를 한 단계 발전시키는 대규모 스파이더 업데이트입니다 🕷️**++### 🚀 새 기능과 사용 편의 개선 {#v0.4.8-new-stuff-and-quality-of-life-changes}++- **`LinkExtractor` 도구를 추가했습니다**. `scrapling.spiders.LinkExtractor`에서 사용하며, `Response`에서 URL을 추출합니다. 다양한 제어 옵션을 제공합니다([문서](spiders/generic-templates.md) 참고).++ ```python+ from scrapling.spiders import LinkExtractor++ extractor = LinkExtractor(allow=r"/posts/", deny_domains=["ads.example.com"])+ ```++- **범용 스파이더 템플릿 `CrawlSpider`와 `CrawlRule`을 추가했습니다**. 이제 “이 패턴과 일치하는 링크 따라가기” 같은 코드를 매번 직접 작성할 필요가 없습니다. `rules()`를 재정의해 `CrawlRule` 객체 목록을 반환하고, 각 객체에 `LinkExtractor`를 연결하세요([문서](spiders/generic-templates.md) 참고).++ ```python+ from scrapling.spiders import CrawlSpider, CrawlRule, LinkExtractor++ class QuotesSpider(CrawlSpider):+ name = "blog"+ start_urls = ["https://quotes.toscrape.com/"]++ def rules(self):+ return [+ CrawlRule(LinkExtractor(allow=r"/author/"), callback=self.parse_author),+ CrawlRule(LinkExtractor(allow=r"/page/\d+/")), # pagination, no callback+ ]++ async def parse_author(self, response):+ yield {+ "name": response.css(".author-title::text").get(),+ "birthday": response.css(".author-born-date::text").get(),+ "url": response.url,+ }+ ```++- **`SitemapSpider` 템플릿을 추가했습니다**. 사이트맵이나 `robots.txt` URL에서 바로 크롤링을 시작합니다. gzip으로 압축한 사이트맵과 다양한 제어 옵션을 지원합니다. 위의 **CrawlSpider** 예제처럼 크롤링 규칙에 따라 URL을 처리합니다([문서](spiders/generic-templates.md) 참고).++ ```python+ from scrapling.spiders import SitemapSpider, CrawlRule, LinkExtractor++ class NewsSitemap(SitemapSpider):+ name = "news"+ sitemap_urls = ["https://example.com/robots.txt"]++ def rules(self):+ return [+ CrawlRule(LinkExtractor(allow=r"/articles/"), callback=self.parse_article),+ ]++ async def parse_article(self, response):+ yield {"url": response.url, "title": response.css("h1::text").get()}+ ```++- **적응형 요소 재탐색의 기본 유사도 기준을 모든 메서드에서 40%로 바꿨습니다**. 이전 기본값인 `0`보다 적응형 기능이 더 잘 동작하도록 합니다. 기준을 넘는 요소가 없으면 경고에 가장 높은 점수를 표시하므로, 필요할 때 확인하고 `percentage`를 낮출 수 있습니다.++- **모든 브라우저와 지문을 갱신했습니다**. 업데이트 후 `scrapling install --force`를 다시 실행해 브라우저와 지문을 갱신하세요.++### 🐛 버그 수정 {#v0.4.8-bug-fixes}++- **`Fetcher.configure(...)`가 개별 요청 호출에 적용되지 않는 문제를 수정했습니다**. `AsyncFetcher`에도 같은 수정을 적용했습니다.+- **잘못된 요청 지문 계산으로 스파이더가 중복 요청을 보내는 문제를 수정했습니다**. @yetval의 [#255](https://github.com/D4Vinci/Scrapling/pull/255) 기여입니다.+- **적응형 스크래핑 엔진이 유사도가 낮은 일치 결과를 알리지 않는 문제를 수정했습니다.** 위의 유사도 기준 변경과 함께, 재탐색에 실패하면 오해를 부르는 “가장 그럴듯한” 요소를 반환하는 대신 경고를 표시합니다.++### 문서 {#v0.4.8-docs}++- **문서 전체의 오래된 코드 예제를 갱신했습니다**. 현재 버전에 맞췄습니다.+- **문서 사이트에서 코드를 복사하고 붙여 넣기 쉽게 개선했습니다**. 에이전트 스킬도 정리해 호출할 때마다 쓰는 토큰을 줄였습니다.++## [v0.4.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.7) - 2026-04-17 {#v0.4.7}++**AI 에이전트가 페이지를 볼 수 있게 하는 업데이트입니다 📸**++### 🚀 새 기능과 사용 편의 개선 {#v0.4.7-new-stuff-and-quality-of-life-changes}++- **MCP 도구 `screenshot`을 추가했습니다**. 페이지를 캡처해 실제 MCP `ImageContent` 블록으로 반환하므로 모델이 이미지를 직접 볼 수 있습니다. 열린 브라우저 세션이 필요하므로 먼저 `open_session`을 호출하고(`dynamic` 또는 `stealthy` 사용), 그 `session_id`를 이 도구에 전달하세요. PNG와 JPEG, 전체 페이지 캡처, JPEG 품질 설정, 일반적인 대기 옵션(`wait`, `wait_selector`, `network_idle`, `timeout`)을 지원합니다([#244](https://github.com/D4Vinci/Scrapling/issues/244) 구현).+- **원하는 이름을 지정하는 `session_id` 매개변수를 `open_session`에 추가했습니다**. 기본값인 무작위 12자리 16진수 문자열 대신 의미 있는 이름(`"search"`, `"checkout"`)을 붙일 수 있습니다. @hauntedhost의 [#243](https://github.com/D4Vinci/Scrapling/pull/243) 기여입니다.++### 🐛 버그 수정 {#v0.4.7-bug-fixes}++- **`FetcherSession`의 상태가 손상되는 문제와 지연 초기화 세션을 닫을 때 비정상 종료되는 문제를 수정했습니다**. @yetval의 [#245](https://github.com/D4Vinci/Scrapling/pull/245) 기여입니다.+- **`TypeError: Session.request() got an unexpected keyword argument 'block_ads'` 오류를 수정했습니다**. CLI의 `--ai-targeted` 플래그를 HTTP 명령과 함께 사용할 때 발생하던 문제입니다. @voidborne-d의 [#249](https://github.com/D4Vinci/Scrapling/pull/249) 기여입니다([#247](https://github.com/D4Vinci/Scrapling/issues/247) 수정).++### 번역 {#v0.4.7-translations}++- **브라질 포르투갈어 README 번역을 추가했습니다**. @rgomids의 [#250](https://github.com/D4Vinci/Scrapling/pull/250) 기여입니다.++## [v0.4.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.6) - 2026-04-13 {#v0.4.6}++**브라우저의 스텔스 기능, 개인정보 보호, 개발 편의를 개선하는 업데이트입니다 🔒**++### 🚀 새 기능과 사용 편의 개선 {#v0.4.6-new-stuff-and-quality-of-life-changes}++- **브라우저 Fetcher에 광고 차단 기능을 내장했습니다**. `block_ads=True`를 전달하면 알려진 광고 및 추적 도메인 약 3,500개로 향하는 요청을 라우트 가로채기 단계에서 막습니다. DNS 조회나 TCP 연결 없이 즉시 중단합니다. `blocked_domains`와 함께 사용해 직접 만든 목록도 추가할 수 있습니다. MCP 서버와 CLI의 `--ai-targeted` 모드는 이를 자동으로 켜서 토큰을 아끼고 페이지 로드를 빠르게 합니다.++ ```python+ page = StealthyFetcher.fetch('https://example.com', block_ads=True)+ ```++- **DNS-over-HTTPS 지원을 추가했습니다**. 프록시를 사용할 때 DNS 정보가 새는 것을 막습니다. `dns_over_https=True`를 전달하면 Cloudflare의 DoH로 DNS 쿼리를 보냅니다. HTTP 트래픽이 프록시를 거쳐도 DNS 조회로 실제 위치가 노출되는 문제를 방지합니다.++ ```python+ page = StealthyFetcher.fetch('https://example.com', proxy='http://proxy:8080', dns_over_https=True)+ ```++- **브라우저 Fetcher에 `page_setup` 콜백을 추가했습니다**. `page.goto()` 전에 실행되는 함수로, 페이지 이동 전에 필요한 이벤트 리스너, 라우트, 스크립트를 등록할 수 있습니다. 페이지 이동 후 실행되는 `page_action`과 함께 사용합니다([#237](https://github.com/D4Vinci/Scrapling/issues/237) 해결).++ ```python+ def capture_websockets(page):+ page.on("websocket", lambda ws: print(f"WS: {ws.url}"))++ page = DynamicFetcher.fetch('https://example.com', page_setup=capture_websockets)+ ```++- **CLI 옵션 `--block-ads`와 `--dns-over-https`를 추가했습니다**. `fetch`와 `stealthy-fetch` 명령 모두에서 사용할 수 있습니다.++### 🐛 버그 수정 {#v0.4.6-bug-fixes}++- **`Seconds` 타입 별칭이 부동소수점 값을 허용하지 않는 문제를 수정했습니다**. 브라우저 Fetcher에 `wait=1.5`나 `timeout=500.0`을 전달하면 타입 오류가 났습니다. 타입 별칭이 `float`를 타입이 아니라 메타데이터로 잘못 취급했기 때문입니다. @kuishou68의 [#240](https://github.com/D4Vinci/Scrapling/pull/240) 기여입니다.+- **전체 경로 선택자를 생성할 때 ID 부분이 중복되는 문제를 수정했습니다**. 전체 CSS/XPath 경로를 만들 때 `id` 속성이 있는 요소의 선택자가 두 번 추가되어 `body > #main > #main > #target > #target` 같은 결과가 나왔습니다. 전체 XPath 경로에서 `[@id='x']` 조건만 출력해 유효하지 않은 XPath가 되는 문제도 수정하고, `*[@id='x']`를 출력하도록 했습니다. @sjhddh의 [#241](https://github.com/D4Vinci/Scrapling/pull/241) 기여입니다.+- **셸 함수 시그니처에서 빠진 매개변수를 추가했습니다**. 대화형 셸의 함수 시그니처에는 `blocked_domains`, `block_ads`, `retries`, `retry_delay`, `capture_xhr`, `executable_path`, `dns_over_https`가 빠져 있었습니다.++## [v0.4.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.5) - 2026-04-07 {#v0.4.5}++**스파이더 개발을 크게 편하게 해 주는 기능 하나와 중요한 수정 사항을 담은 업데이트입니다 🎉**++### 🚀 새 기능과 사용 편의 개선 {#v0.4.5-new-stuff-and-quality-of-life-changes}++- **스파이더 개발 모드**: 이전에는 스파이더의 `parse()` 로직을 수정하고 실행할 때마다 대상 서버에 다시 요청해야 했습니다. 느리고 불필요한 트래픽을 만들며, 선택자를 조정하는 중에 요청 수 제한에 걸릴 수도 있었습니다. 새 개발 모드는 첫 실행에서 모든 응답을 디스크에 캐시하고, 이후에는 디스크에서 다시 읽습니다. 네트워크 요청을 하나도 보내지 않고 콜백을 수정해 원하는 만큼 다시 실행할 수 있습니다. 클래스 속성 하나로 켤 수 있습니다:++ ```python+ class MySpider(Spider):+ name = "my_spider"+ start_urls = ["https://example.com"]+ development_mode = True++ async def parse(self, response):+ yield {"title": response.css("title::text").get("")}+ ```++ 기본 캐시 위치는 `.scrapling_cache/{spider.name}/`이며 `development_cache_dir`로 다른 위치를 지정할 수 있습니다. 새 통계 카운터 `cache_hits`와 `cache_misses`로 캐시 사용 상태를 확인할 수 있습니다. 캐시를 읽을 때는 `download_delay`, 요청 수 제한, 차단된 요청의 재시도 과정을 건너뛰므로 디스크가 허용하는 속도로 반복해서 확인할 수 있습니다. `development_mode = True`인 상태로 스파이더를 운영 환경에 배포하지 마세요. 개발 도구이지 운영용 캐시가 아닙니다. 자세한 내용은 [문서](spiders/advanced.md#development-mode)를 참고하세요.++- **기본 리디렉션를 더 안전하게 바꿨습니다**. 모든 HTTP Fetcher, MCP 서버, 셸에서 `follow_redirects`의 기본값이 `"safe"`가 됐습니다. 리디렉션는 계속 따라가지만, 내부 또는 사설 IP(루프백, 사설 네트워크, 링크 로컬)로 향하는 주소는 거부합니다. 사용자가 제공한 URL을 스크래핑할 때 SSRF를 방지합니다. 이전 동작을 사용하려면 `follow_redirects="all"`을, 리디렉션를 완전히 끄려면 `False`를 전달하세요.++### 🐛 버그 수정 {#v0.4.5-bug-fixes}++- **강제 종료해도 체크포인트가 사라지지 않습니다**. `crawldir`을 켠 스파이더에서 Ctrl+C를 두 번 눌러 강제 종료하면 체크포인트 쓰기와 충돌할 수 있었습니다. pickle 기록이 끝나기 전에 취소 범위가 작업을 종료해 `paused=False`가 남고, 이전 체크포인트를 *삭제하는* 정리 과정이 실행됐습니다. 그래서 긴 크롤링을 강제 종료하면 저장하려던 진행 상황을 모두 잃을 수 있었습니다. 이제 엔진은 **체크포인트를 먼저 기록한 뒤** `cancel_scope.cancel()`을 호출하므로, 강제 종료해도 최신 대기 상태를 항상 보존합니다. @voidborne-d의 [#230](https://github.com/D4Vinci/Scrapling/pull/230) 기여입니다.++## [v0.4.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.4) - 2026-04-05 {#v0.4.4}++**중요한 스파이더 개선과 버그 수정을 담은 업데이트입니다 🎉**++### 🚀 새 기능과 사용 편의 개선 {#v0.4.4-new-stuff-and-quality-of-life-changes}+- **스파이더 프레임워크에 robots.txt 준수 기능을 추가했습니다**. 새 `robots_txt_obey` 옵션을 켜면 크롤링 전에 robots.txt를 자동으로 가져와 `Disallow`, `Crawl-delay`, `Request-rate` 등의 규칙을 지킵니다. robots.txt 파일은 동시에 가져오고, 크롤링이 끝날 때까지 도메인별로 캐시합니다. @AbdullahY36의 [#226](https://github.com/D4Vinci/Scrapling/pull/226) 기여입니다.+- **robots.txt 캐시를 미리 준비하는 기능을 추가했습니다**. 크롤링 루프가 시작되기 전에 start_urls의 모든 도메인에서 robots.txt를 가져와 파싱합니다. 각 도메인의 첫 요청에서 기다릴 필요가 없어집니다.+- **새 통계 `robots_disallowed_count`를 추가했습니다**. `CrawlStats`에서 크롤링 중 robots.txt 규칙에 따라 차단된 요청 수를 기록합니다.++자세한 내용은 웹사이트의 [이 페이지](spiders/getting-started.md#robotstxt-compliance)를 확인하세요.++### 🐛 버그 수정 {#v0.4.4-bug-fixes}+- **`ProxyRotator`의 심각한 MRO 문제를 수정했습니다**. 임시 메서드 `_build_context_with_proxy`가 자식 클래스의 실제 구현을 가려, 프록시 순환 때마다 `NotImplementedError`가 발생했습니다([#215](https://github.com/D4Vinci/Scrapling/issues/215) 수정). @yetval에게 감사드립니다.+- **브라우저 세션에서 요청별로 프록시를 순환할 때 페이지 풀에 불필요한 참조가 남는 문제를 수정했습니다**. 임시 컨텍스트에서 만든 페이지가 정리할 때 풀에서 제거되지 않아, 유효하지 않은 참조가 계속 쌓였습니다. @yetval의 [#223](https://github.com/D4Vinci/Scrapling/pull/223) 기여입니다.+- **정적 Fetcher에 빠져 있던 타입 검증을 추가했습니다**. `curl_cffi`가 `None`을 `session.request()`에서 반환할 수 있어 후속 처리에 오류가 생기던 문제입니다.++### 기타 {#v0.4.4-other}+- 의존성을 갱신해 최신 지문과 다른 업데이트를 포함했습니다.+- robots.txt 파싱을 위해 `protego`를 선택 의존성 그룹 `fetchers`에 추가했습니다.++## [v0.4.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.3) - 2026-03-30 {#v0.4.3}++**여러 중요한 변경 사항을 담은 업데이트입니다 🎉**++### 🚀 새 기능과 사용 편의 개선 {#v0.4.3-new-stuff-and-quality-of-life-changes}+- **새 MCP 도구를 추가했습니다**. 일반 또는 스텔스 브라우저를 열고 그대로 유지해 다른 도구에서도 계속 사용할 수 있습니다. 브라우저를 닫는 도구도 추가했습니다([예제](https://github.com/D4Vinci/Scrapling/blob/v0.4.3/docs/ai/mcp-server.md#examples)).+- **새 MCP 도구를 추가했습니다**. 기존 브라우저 세션을 모두 나열하며, 새 도구들과 함께 사용하도록 만들었습니다.+- **브라우저 세션에 새 옵션을 추가했습니다**. 요청 중에 발생하는 모든 백그라운드 요청을 자동으로 수집합니다([#159](https://github.com/D4Vinci/Scrapling/pull/159) 해결) [[예제](https://github.com/D4Vinci/Scrapling/blob/v0.4.3/docs/fetching/dynamic.md#capturing-xhrfetch-requests)].+- **새 정리 도구를 추가했습니다**. 숨겨지거나 보이지 않는 내용을 제거해 일반적인 프롬프트 인젝션 공격으로부터 MCP 서버를 보호합니다.+- **웹 스크래핑 명령에 새 명령줄 옵션을 추가했습니다**. `--ai-targeted`를 사용하면 MCP 서버처럼 내용을 AI에 맞게 정리하고, 일반적인 프롬프트 인젝션 공격을 방지합니다.+- **브라우저 세션에 새 옵션을 추가했습니다**. `executable_path`로 원하는 브라우저 경로를 지정할 수 있습니다([#202](https://github.com/D4Vinci/Scrapling/pull/202) 해결).+- MCP 서버 코드를 **리팩터링**해 유지 보수를 쉽게 하고, 모든 도구를 비동기로 통일했습니다.+- CLI 명령 코드를 **리팩터링**해 유지 보수를 쉽게 하고, 210줄 줄였습니다.++### 🐛 버그 수정 {#v0.4.3-bug-fixes}+- 스파이더 세션에서 재시도할 때 HTTP 메서드를 유지하도록 수정했습니다. @karesansui-u의 [#201](https://github.com/D4Vinci/Scrapling/pull/201) 기여입니다.+- 페이지 내용을 가져올 때 재시도 횟수의 상한을 두어 무한 루프를 방지했습니다. @haosenwang1018 및 @D4Vinci의 [#197](https://github.com/D4Vinci/Scrapling/pull/197) 기여입니다.+- 예외를 지정하지 않은 `raise`를 `return False`로 바꿨습니다. 대상은 `_restore_from_checkpoint`입니다. @haosenwang1018의 [#196](https://github.com/D4Vinci/Scrapling/pull/196) 기여입니다.+- `get_all`을 `getall`로 바꿔 `Texthandler`를 Selector 클래스와 맞췄습니다.++### 커버리지와 테스트 개선 {#v0.4.3-coverage-tests-improvement}+- `_normalize_credentials`의 경계 사례를 검사하는 테스트를 추가했습니다. @Bortlesboat의 [#192](https://github.com/D4Vinci/Scrapling/pull/192) 기여입니다.+- 저장 후 같은 데이터를 다시 읽을 수 있는지 확인하는 테스트와 핵심 저장소 테스트를 추가했습니다. @haosenwang1018의 [#193](https://github.com/D4Vinci/Scrapling/pull/193) 기여입니다.+- `TextHandler`의 정규식 처리 경로와 `TextHandlers.re()`를 검사하는 테스트를 추가했습니다. @haosenwang1018의 [#194](https://github.com/D4Vinci/Scrapling/pull/194) 기여입니다.+- `filter`, `iterancestors`, `find_similar`의 경계 사례를 검사하는 테스트를 추가했습니다. @awanawana의 [#200](https://github.com/D4Vinci/Scrapling/pull/200) 기여입니다.++### Agent Skill 개선 {#v0.4.3-agent-skill-improvement}+- 스킬 참고 자료의 잘못된 Markdown 링크를 수정했습니다. @yetval의 [#204](https://github.com/D4Vinci/Scrapling/pull/204) 기여입니다.+- [Clawhub](https://clawhub.ai/d4vinci/scrapling-official) 검증을 더 잘 통과하도록 스킬 구성을 개선했습니다.+- 스킬이 명령줄로 스크래핑할 때 `--ai-targeted` 옵션을 반드시 사용하도록 했습니다.++### 문서 개선 {#v0.4.3-docs-improvement}+- 한국어 README 번역을 추가했습니다. @greatsk55의 [#187](https://github.com/D4Vinci/Scrapling/pull/187) 기여입니다.+- 중국어와 일본어 README에서 CJK 문자와 라틴 문자 사이의 공백을 수정했습니다.+- 이전 웹사이트 디자인에서 남아 있던 잘못된 링크를 수정했습니다.++## [v0.4.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.2) - 2026-03-08 {#v0.4.2}++**중요한 변경 사항이 포함된 새 유지 보수 업데이트입니다**++#### 버그 수정 {#v0.4.2-bug-fixes}+- 이제 `get_all_text()` 함수가 요소 뒤에 오는 텍스트 노드도 가져옵니다. 따라서 MCP 서버와 명령이 이전에 놓쳤던 텍스트도 읽을 수 있습니다([#168](https://github.com/D4Vinci/Scrapling/pull/168)). @mhillebrand 님 감사합니다.+- 이제 Referer는 Google 검색 URL 대신 Google 홈페이지 URL을 반환합니다. 이전 로직은 잘못되었으며, 봇을 식별하는 지문 신호가 되었을 수 있습니다([#179](https://github.com/D4Vinci/Scrapling/pull/179)). @Bortlesboat 님 감사합니다.+- 모든 브라우저에서 추가 플래그를 합칠 때 발생하던 문제를 수정했습니다. @rostchri 님 감사합니다.+- 3.12 미만의 Python 버전에서 실행이 중단되던 타입 힌트 문제를 수정했습니다. ([#163](https://github.com/D4Vinci/Scrapling/issues/163) 해결)++#### 기타 {#v0.4.2-other}+- Claude Code / OpenClaw 및 다른 AI 에이전트 도구를 위한 Agent Skill을 추가했습니다.+- Clawhub에 Agent Skill을 추가했습니다.+- 모든 브라우저와 Playwright를 최신 버전으로 업데이트했습니다.+- 기본 README 파일에 프랑스어 번역을 추가했습니다.++## [v0.4.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.1) - 2026-02-27 {#v0.4.1}++**중요한 변경 사항이 많이 포함된 새 업데이트입니다**++### 🚀 새 기능과 사용 편의 개선 {#v0.4.1-new-stuff-and-quality-of-life-changes}+- Cloudflare 검사를 감지하는 **정규식의 정확도를 개선했습니다**. (@Rinz27 님 감사합니다. [#133](https://github.com/D4Vinci/Scrapling/pull/133))+- Cloudflare 검사 처리의 **속도와 효율을 개선했습니다**. 이제 거의 두 배 빠릅니다.+- 웹사이트가 본 사이트로 이동하기 전에 Cloudflare 페이지를 두 번 표시하는 경우도 처리하도록 **Cloudflare 검사 처리를 개선했습니다**.+- 삽입하던 JS 파일을 제거하여 **스텔스 브라우저**의 스텔스 모드와 속도를 개선했습니다.+- OpenCode에서 사용할 수 있도록 **MCP 스키마를 개선했습니다**. (@robin-ede 님 감사합니다. [#137](https://github.com/D4Vinci/Scrapling/pull/137))+- VS Code Copilot과 검사가 엄격한 다른 도구에서도 사용할 수 있도록 **MCP 스키마의 호환성을 더 높였습니다**. (#150 해결)+- `main_content_only` 옵션이 켜져 있을 때 불필요한 HTML 태그를 제거하여 **MCP 서버의 토큰 사용량을 크게 줄였습니다**.+- PyPI 페이지를 수정하고 MCP 서버 레지스트리에 MCP 서버를 등록하는 데 필요한 파일을 추가했습니다.+- 자동화하기 쉽도록 명령줄 대신 코드로 브라우저 의존성을 설치하는 예제를 추가했습니다.+- 최신 버전의 액션을 사용하도록 모든 워크플로를 개선했습니다. (@salmanmkc 님 감사합니다. [#143](https://github.com/D4Vinci/Scrapling/pull/143)/[#144](https://github.com/D4Vinci/Scrapling/pull/144))++## [v0.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4) - 2026-02-15 {#v0.4}++**지금까지 가장 큰 Scrapling 릴리스입니다. 스파이더 프레임워크, 프록시 순환, 주요 파서 개선 사항을 소개합니다**++이번 릴리스는 완전한 비동기 스파이더/크롤링 프레임워크, 스마트한 프록시 관리, 중요한 API 변경을 제공합니다. Scrapling의 기능이 더 강력해지고 일관성도 높아졌습니다. 업데이트하기 전에 호환성에 영향을 주는 변경 사항을 자세히 확인하세요.++### 🕷️ 스파이더 프레임워크 {#v0.4-spider-framework}++`anyio`를 기반으로 만든 새 비동기 크롤링 프레임워크로 대규모 스크래핑을 체계적으로 처리할 수 있습니다.++```python+from scrapling.spiders import Spider, Response++class MySpider(Spider):+ name = "demo"+ start_urls = ["https://example.com/"]++ async def parse(self, response: Response):+ for item in response.css('.product'):+ yield {"title": item.css('h2::text').get()}++MySpider().start()+```++- **Scrapy와 비슷한 스파이더 API**: `start_urls`, 비동기 `parse` 콜백, `Request`/`Response` 객체, 우선순위 큐를 사용하여 스파이더를 정의합니다.+- **동시 크롤링**: 동시 요청 수 제한, 도메인별 속도 제한, 다운로드 지연을 설정할 수 있습니다.+- **여러 세션 지원**: 하나의 스파이더에서 HTTP 요청과 창 없는 모드의 스텔스 브라우저를 같은 인터페이스로 사용합니다. ID로 요청을 다른 세션에 보낼 수 있으며, 세션을 처음 사용할 때 초기화하는 방식도 지원합니다.+- **일시 중지와 재개**: 체크포인트로 크롤링 상태를 저장합니다. Ctrl+C로 안전하게 종료한 뒤 다시 실행하면 중단한 곳부터 계속합니다.+- **스트리밍 모드**: `async for item in spider.stream()`으로 수집한 항목을 즉시 받아 처리하고 실시간 통계도 확인합니다. UI, 파이프라인, 장시간 크롤링에 적합합니다.+- **차단된 요청 감지**: 차단된 요청을 자동으로 감지하고 다시 시도합니다. 처리 로직을 바꿀 수 있습니다.+- **기본 내보내기 기능**: 훅과 직접 만든 파이프라인으로 결과를 내보내거나, 기본 제공하는 `result.items.to_json()` / `result.items.to_jsonl()`로 각각 JSON/JSONL 형식으로 내보냅니다.+- **수명 주기 훅**: `on_start()`, `on_close()`, `on_error()`, `on_scraped_item()` 등 여러 훅으로 크롤링의 전체 수명 주기를 제어합니다.+- **자세한 크롤링 통계**: 요청, 응답, 바이트 수, 상태 코드, 프록시, 도메인별/세션별 통계, 로그 수준별 개수 등을 기록합니다.+- **uvloop 지원**: `use_uvloop=True`를 `spider.start()`에 전달하면 uvloop를 사용할 수 있는 환경에서 비동기 실행이 빨라집니다.++웹사이트에 자세한 설명을 담은 새 섹션을 추가했습니다. [여기](spiders/architecture.md)를 확인하세요.++### 🔄 프록시 순환 {#v0.4-proxy-rotation}++* 여러 스레드에서 안전하게 프록시를 순환하는 새 `ProxyRotator` 클래스입니다. 모든 Fetcher와 세션에서 사용할 수 있습니다.++ ```python+ from scrapling import ProxyRotator+ rotator = ProxyRotator(["http://proxy1:8080", "http://proxy2:8080"])+ Fetcher.get(url, proxy_rotator=rotator)+ ```++* **사용자 정의 순환 전략**: 프록시 순환 로직을 직접 만들 수 있습니다.+* **요청별 프록시 변경**: `proxy=`를 개별 `get()`/`post()`/`fetch()` 호출에 전달하면 해당 요청에서 세션의 프록시 대신 사용합니다.++### 🌐 브라우저 Fetcher 개선 {#v0.4-browser-fetcher-improvements}++* **도메인 차단**: 새 `blocked_domains` 매개변수를 `DynamicFetcher`/`StealthyFetcher`에 추가했습니다. 특정 도메인으로 가는 요청을 차단하며, 하위 도메인도 자동으로 포함합니다.+* **자동 재시도**: 이제 브라우저 Fetcher는 `retries`(기본값: 3)와 `retry_delay`(기본값: 1s) 매개변수에 따라 실패한 요청을 다시 시도합니다. 프록시 관련 오류도 감지합니다.+* **응답 메타데이터**: `Response.meta` 딕셔너리는 사용한 프록시를 자동으로 저장하고 요청 메타데이터를 합칩니다.+* **Response.follow()**: 스파이더 시스템을 위해 만든 기능으로, Referer를 자동으로 전달하는 후속 `Request` 객체를 생성합니다.+* **자동 재생 차단**: 브라우저 세션이 이전에 문제를 일으키던 자동 재생 콘텐츠를 차단합니다.+* **속도**: 브라우저 플래그를 조정하여 탐지 회피와 속도를 개선했습니다.++### 🔧 버그 수정 및 개선 {#v0.4-bug-fixes-improvements}+- **파서 최적화**: 반복 작업을 최적화하여 파서의 성능을 높였습니다.+- **페이지 오류**: 페이지에서 오류가 발생하면 브라우저가 닫히지 않던 버그를 수정했습니다.+- **빈 본문**: 본문이 비어 있는 응답을 처리합니다.+- **Playwright 루프**: CDP 연결이 실패하면 Playwright 루프가 열린 채로 남던 문제를 해결했습니다.+- **타입 안전성**: 모든 mypy 오류를 수정하고 타입이 없던 함수 본문 전체에 타입 힌트를 추가했습니다. CI 워크플로에 mypy와 pyright를 추가했습니다.++### ⚠️ 호환성에 영향을 주는 변경 사항 {#v0.4-breaking-changes}++* **`css_first`/`xpath_first` 제거**: 대신 `css('.selector').first`, `css('.selector')[0]` 또는 `css('.selector').get()`을 사용하세요.+* **모든 선택 작업이 `Selectors` 반환**: 이제 `css('::text')`, `xpath('//text()')`, `css('::attr(href)')`, `xpath('//@href')`는 `Selectors`를 반환합니다. 텍스트 노드를 `Selector` 객체로 감싸고 `tag="#text"`를 설정하며, 더 이상 `TextHandlers`를 반환하지 않습니다. 모든 선택 메서드와 타입 힌트에서 API가 일관되게 동작합니다.+* **`Response.body`는 항상 `bytes`**: 이전에는 `str` 또는 `bytes`였지만 이제 항상 `bytes`를 반환합니다.+* **`get()`/`getall()` 동작**: `Selector`에서 `get()`은 `TextHandler`(직렬화된 HTML 또는 텍스트 값)를, `getall()`은 `TextHandlers`를 반환합니다. 별칭은 `extract_first = get`, `extract = getall`입니다. 이전 `get_all()` 메서드는 `Selectors`에서 제거했습니다.+* **`Selectors.first`/`.last`**: `Selector | None`을 반환하며 `IndexError`를 발생시키지 않는 안전한 접근 속성입니다.+* **내부 상수 이름 변경**: `DEFAULT_FLAGS` → `DEFAULT_ARGS`, `DEFAULT_STEALTH_FLAGS` → `STEALTH_ARGS`, `HARMFUL_DEFAULT_ARGS` → `HARMFUL_ARGS`, `DEFAULT_DISABLED_RESOURCES` → `EXTRA_RESOURCES`.++### 🔨 기타 변경 사항 {#v0.4-other-changes}++* **의존성 변경**: `tldextract`를 `tld`로 교체하고 내부 `_html_utils.py` 대신 `w3lib.html.replace_entities`를 사용합니다. `typing_extensions`를 필수 의존성으로 추가했습니다.+* **문서 개편**: MkDocs에서 Zensical로 완전히 전환했습니다. 스파이더 문서 섹션을 새로 만들고 기존 페이지를 모두 업데이트했으며 새 API 참고 문서를 추가했습니다.++## [v0.3.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.14) - 2026-01-03 {#v0.3.14}++**v0.3.13에서 일부 기기에 발생한 문제를 수정하는 작은 유지 보수 업데이트입니다**++- Windows 기기에서 페이지 간에 쿠키가 유지되지 않아 `StealthyFetcher`와 해당 세션 클래스의 시크릿 모드를 껐습니다. MacOS와 Linux에서는 발생하지 않았습니다. ([#123](https://github.com/D4Vinci/Scrapling/issues/123) 수정. 문제를 알려 준 @frugality4121 님과 해결 방법을 알려 준 @gembleman 님 감사합니다.)+- 이미 오래된 browserforge를 사용하는 환경에서 이전 헤더 모델 때문에 발생하는 문제를 해결하도록 browserforge의 최신 버전을 고정했습니다.++## [v0.3.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.13) - 2026-01-01 {#v0.3.13}++**여러 부분을 개선한 큰 업데이트입니다. 필요에 따라 호환성에 영향을 주는 변경도 많이 포함했습니다. 업데이트하기 전에 아래 내용을 읽어 주세요**++* 여러 이유로 앞으로 Camoufox 사용을 완전히 중단하기로 했습니다. 개발이 계속된다면 나중에 다시 사용할 수도 있습니다. 이번 릴리스 이전처럼 Camoufox를 계속 사용하려면 이 [섹션](https://github.com/D4Vinci/Scrapling/blob/v0.3.13/docs/fetching/stealthy.md#using-camoufox-as-an-engine)의 설명을 따르세요.++* 이전에는 `DynamicFetcher`와 해당 세션 클래스의 스텔스 모드에서 patchright를 사용했습니다. 이제 해당 클래스에서 스텔스 모드를 제거하고 `StealthyFetcher`와 해당 세션 클래스에서 patchright를 사용합니다. 아래에서 설명하는 여러 개선을 더해 patchright의 기본 기능보다 전반적인 탐지 회피 성능을 높였습니다.++**이 변경으로 `StealthyFetcher`와 해당 세션 클래스는 이전보다 101% 빨라졌고 메모리와 저장 공간도 덜 사용하며, 코드가 약 400줄 줄었습니다. 무엇보다 이전에 Camoufox를 사용할 때보다 안정적입니다.**++또한 `scrapling install` 명령의 설치 시간을 줄이고 Docker 이미지 크기를 줄이며, GitHub CI에서 테스트가 더 원활하게 실행됩니다. 처음 쓰는 사람도 Scrapling을 더 쉽게 이해할 수 있습니다.++### 호환성에 영향을 주는 변경 사항 {#v0.3.13-breaking-changes}+1. `stealth` 인수를 `DynamicFetcher` 클래스와 해당 세션 클래스에서 제거했습니다. `hide_canvas` 인수는 `StealthyFetcher`와 해당 세션 클래스로 옮겼습니다.+2. `disable_webgl` 인수를 `DynamicFetcher`에서 `StealthyFetcher` 클래스로 옮기고 이름을 `allow_webgl`로 바꿨습니다. 모든 세션 클래스에도 적용됩니다.+3. 이제 `StealthyFetcher` 클래스는 기본적으로 `DynamicFetcher`의 새 스텔스 버전입니다. 따라서 `block_images`, `humanize`, `addons`, `os_randomize`, `disable_ads`, `geoip` 인수를 제거했습니다. Chromium에서 같은 기능을 구현하려고 했지만 각 기능마다 문제가 있었습니다. v0.4 이전의 후속 릴리스에서 바뀔 수도 있습니다.++좋은 소식도 있습니다. 많은 부분을 개선하고 수정했습니다 :)++### 개선 사항 {#v0.3.13-improvements}+- 앞에서 설명했듯이 `StealthyFetcher` 클래스와 해당 세션 클래스는 이전보다 101% 빨라졌습니다. `DynamicFetcher` 클래스와 해당 세션 클래스도 20% 빨라졌습니다.+- Cloudflare 검사 처리 알고리즘을 개선하여 더 빠르게 완료하고 더 많은 경우를 처리합니다. 새 리팩터링 덕분에 CAPTCHA도 두 배 빠르게 해결할 수 있습니다!+- 모든 Fetcher가 메모리를 덜 사용합니다.+- MCP 서버의 토큰 사용량이 줄어 비용을 더 아낄 수 있습니다!+- Docker 이미지가 60% 작아졌습니다.+- 문서 웹사이트 전체에 새 내용을 반영했습니다. 동시에 설명을 더 명확하게 쓰고 여러 섹션을 짧게 줄였으며, 예제를 추가하고 누락된 인수를 포함했습니다. API 참고 문서에 그래프를 추가하는 등 여러 부분을 개선했습니다. 이제 웹사이트가 130% 빨리 로드되고 데이터를 덜 사용하며 SEO에도 더 적합합니다.++### 수정 사항 {#v0.3.13-fixes}+- 웹 스크래핑 셸의 단축 함수에 누락되었던 인수를 추가하고 더 정확하게 동작하도록 수정했습니다.+- URL이 localhost/IP여도 `google_search` 인수가 Google Referer를 만들던 문제를 수정했습니다.++## [v0.3.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.12) - 2025-12-18 {#v0.3.12}++### 변경 사항 {#v0.3.12-what-s-changed}+- `DynamicSession`/`AsyncDynamicSession` 클래스에 `timezone_id`라는 새 인수를 추가했습니다. 사용 중인 프록시/VPN의 시간대에 맞게 브라우저의 시간대를 설정할 수 있습니다. 따라서 웹사이트가 시간대 불일치로 프록시 사용을 감지할 수 없습니다.+- 응답을 JSON으로 자동 변환하는 기능을 개선했습니다.+- Fetcher의 세션 클래스에서 내부 함수 `__create__`의 이름을 `start`로 바꿨습니다. `with` 컨텍스트 밖에서도 더 쉽게 사용할 수 있습니다.+- `curl_cffi`와 다른 의존성을 최신 버전으로 업데이트했습니다.++## [v0.3.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.11) - 2025-12-03 {#v0.3.11}++### 변경 사항 {#v0.3.11-what-s-changed}+- 불안정한 웹사이트(미디어가 재생되는 사이트 등)에서 `network_idle` 인수를 사용할 때 타임아웃 오류를 더 잘 처리하도록 개선했습니다.+- 웹 스크래핑 셸에서 `stealthy_fetch` 단축 함수의 자동 완성을 수정했습니다.++## [v0.3.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.10) - 2025-11-26 {#v0.3.10}++**많은 주요 변경 사항과 호환성에 영향을 줄 수 있는 변경이 포함된 유지 보수 업데이트입니다**++- 인코딩이 올바르게 선언되지 않은 웹페이지도 처리하는 더 나은 방식으로 모든 인코딩 문제를 **해결했습니다**. (@Kemsty2 님이 [#110](https://github.com/D4Vinci/Scrapling/issues/110) [#111](https://github.com/D4Vinci/Scrapling/pull/111)에서 문제를 알려 주셨습니다. 감사합니다.)+- 모든 브라우저 Fetcher에서 요청 수준의 매개변수로 세션 수준의 매개변수를 덮어쓸 때 발생하던 로직 문제를 **해결했습니다**. v0.3부터 있던 문제입니다.+- 대화형 웹 스크래핑 셸의 단축 함수 시그니처를 **수정하여** 셸에서 단축 함수의 자동 완성이 완벽하게 동작하도록 했습니다. 이 문제도 v0.3부터 있었습니다.+- Maxmind 데이터베이스의 버전을 **높였습니다**. `geoip` 인수가 `StealthyFetcher`와 해당 세션 클래스에서 더 잘 동작합니다.+- 사용하는 모든 브라우저를 최신 버전으로 **업데이트했습니다**.+- **호환성에 영향을 주는 변경** - 모든 Fetcher를 크게 리팩터링했습니다. 다음 변경으로 기존 코드가 동작하지 않을 수 있습니다.+ 1. Scrapling 코드가 약 750줄 줄었습니다. 여러 변경으로 앞으로 유지 보수가 훨씬 쉬워지고 리소스 사용량도 조금 줄어듭니다.+ 2. 모든 Fetcher와 해당 세션 클래스의 검증 속도가 크게 빨라져 전체 속도도 높아집니다.+ 3. 이를 위해 모든 Fetcher에서 `url` 인수만 위치 인수로 받을 수 있게 했습니다. 나머지는 키워드 인수여야 합니다. 코드를 `Fetcher.get('https://google.com', stealthy_headers=True)`처럼 작성해야 합니다. 어떤 이유로든 `Fetcher.get('https://google.com', True)`처럼 사용했다면 수정하세요!+ 4. v0.3부터 브라우저 Fetcher와 해당 세션 클래스 사이에 불편한 차이가 있었습니다. 요청별 파서 설정을 전달하는 인수가 Fetcher에서는 `custom_config`, 세션 클래스에서는 `selector_config`였습니다. 이번 리팩터링으로 기존 코드를 깨뜨리지 않고 이름을 `selector_config`로 통일했습니다. 기본 이름은 이제 `selector_config`이며, `custom_config` 인수와의 하위 호환성도 유지합니다. 자동 완성은 `selector_config` 인수에만 지원됩니다.+ 5. 이 모든 변경을 위해 Fetcher 함수의 타입 힌트를 동적으로 생성하도록 바꿨습니다. IDE의 자동 완성이 제대로 동작하지 않으면 오래된 버전은 아닌지 확인하세요. 거의 모든 주요 IDE와 편집기에서 테스트했습니다.++> 모든 벤치마크 표도 현재 수치로 업데이트하여 다른 라이브러리의 최신 버전과 비교했습니다.++## [v0.3.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.9) - 2025-11-17 {#v0.3.9}++**중요한 변경 사항이 많이 포함된 새 업데이트입니다**++### 🚀 새 기능과 사용 편의 개선 {#v0.3.9-new-stuff-and-quality-of-life-changes}+- 이제 `impersonate` 인수는 `Fetcher`와 `FetcherSession`에서 브라우저 목록을 받을 수 있습니다. 요청마다 목록에서 브라우저 하나를 무작위로 선택합니다.++```python+from scrapling.fetchers import FetcherSession++with FetcherSession(impersonate=['chrome', 'firefox', 'safari']) as s:+ s.get('https://github.com/D4Vinci/Scrapling')+```++- `clean` 메서드에 새 인수를 추가했습니다. `TextHandler`의 현재 텍스트에서 HTML 엔티티를 쉽게 제거할 수 있습니다.+- 여러 부분의 설명을 더 정확하게 쓰고 기본 `README.md` 파일의 자동 번역을 추가하는 등 문서를 크게 개선했습니다.++### 🐛 버그 수정 {#v0.3.9-bug-fixes}+- 브라우저 Fetcher에서 응답을 가져올 때 발생하던 큰 문제를 수정했습니다. 이제 콘텐츠 유형을 감지하여 HTML일 때만 `response.body`에 브라우저가 렌더링한 내용을 넣습니다. 그 외에는 마지막 요청의 원본 내용을 넣습니다. 따라서 바이너리 파일과 텍스트 파일을 HTML 태그로 감싸지 않은 상태로 다운로드할 수 있으며, 웹사이트를 가져올 때는 원하는 렌더링 결과도 받을 수 있습니다.++### 🔨 기타 {#v0.3.9-misc}+- 기여 가이드를 더 명확하고 쉽게 업데이트했습니다.+- 코드 품질 도구를 반드시 실행하는 새 워크플로를 추가했습니다. pre-commit 훅과 같은 도구를 사용합니다.++## [v0.3.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.8) - 2025-10-27 {#v0.3.8}++**중요한 변경 사항이 많이 포함된 새 업데이트입니다**++### 🚀 새 기능과 사용 편의 개선 {#v0.3.8-new-stuff-and-quality-of-life-changes}+- 모든 브라우저 Fetcher에서 요청 로딩이 끝나지 않는 웹사이트에 `network_idle`을 사용해도 코드 실행이 중단되지 않습니다.+- 브라우저 Fetcher가 페이지 내용을 가져오고 확인하는 로직을 바꿨습니다. 이제 Windows에서도 Linux/MacOS처럼 브라우저가 더 안정적으로 동작합니다. 이 동작 차이는 Windows에서 Playwright의 구현 방식이 다르기 때문에 발생했습니다.+- 모든 검증 로직을 리팩터링하여 모든 브라우저 Fetcher의 요청이 8-15% 빨라졌습니다.+- `extra_flags`라는 새 옵션을 `DynamicFetcher`와 해당 세션에 추가했습니다. 브라우저를 시작할 때 기존 Chrome 플래그에 원하는 플래그를 더할 수 있습니다.+- `page_action`을 사용할 때는 응답을 가져오는 라우팅 로직을 이전 버전으로 되돌렸습니다. 이 로직은 직전 버전에서 바뀌었습니다. `page_action`이 요청을 보내지 않고 페이지 내용을 바꾸더라도 최신 내용을 가져오기 위한 변경입니다. ([#100](https://github.com/D4Vinci/Scrapling/issues/100)과 [#102](https://github.com/D4Vinci/Scrapling/pull/102)에서 알려 준 @gembleman 님 감사합니다.)++### 🐛 버그 수정 {#v0.3.8-bug-fixes}+- DynamicSession의 async_fetch에서 `load_dom`의 오타를 수정했습니다.+- 통과한 뒤에도 사라지지 않는 삽입형 CAPTCHA를 Cloudflare 검사 처리 중에 계속 기다리던 문제를 수정했습니다. 이제 CAPTCHA가 사라질 때까지 30초 동안 기다린 다음, 사라지지 않는 유형으로 간주합니다. (#100 수정)++### 🔨 기타 {#v0.3.8-misc}+- 사용자가 편리하게 쓸 수 있도록 Docker 이미지를 Dockerhub와 GitHub 컨테이너 레지스트리에 자동으로 푸시합니다.+- Scrapling에서 Scrapeless 브라우저를 사용하는 방법을 설명하는 [새 문서 페이지](https://github.com/D4Vinci/Scrapling/blob/v0.3.8/docs/tutorials/external.md)를 추가했습니다.++## [v0.3.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.7) - 2025-10-12 {#v0.3.7}++**중요한 변경 사항이 많이 포함된 새 업데이트입니다**++### 🚀 새 기능과 사용 편의 개선 {#v0.3.7-new-stuff-and-quality-of-life-changes}+- `solve_cloudflare` 인수를 다시 구현하여 `StealthyFetcher`가 모든 종류의 사용자 정의 Turnstile 구현을 해결할 수 있게 했습니다.+- Pyright 검사를 통과하도록 전체 코드를 리팩터링했습니다. 이제 모든 IDE에서 원활하게 작업할 수 있으며, 여러 버그도 해결했습니다.+- 요청 로직을 더 깔끔하고 빠르게 리팩터링했습니다. (#97도 해결)+- 모든 브라우저 세션 클래스에 새 `user_data_dir` 옵션을 추가했습니다. 이전 세션의 브라우저 데이터(쿠키/저장소 등)를 다시 사용할 수 있습니다. 지정하지 않으면 이전처럼 Playwright가 실행할 때마다 무작위 디렉터리를 사용합니다.+- 새 `additional_args` 옵션을 `Dynamic fetcher`와 해당 세션 클래스에 추가했습니다. 이전의 `StealthyFetcher`처럼 Playwright 컨텍스트에 추가 인수를 전달할 수 있습니다.+- 모든 브라우저에서 마지막 탐색 응답을 가져오는 라우팅 로직을 개선했습니다. 이전에는 브라우저가 먼저 처리했지만, 이제 처리 전의 원본 응답을 파서에 전달합니다. 텍스트/JSON 응답에 매우 유용합니다.++### 🐛 버그 수정 {#v0.3.7-bug-fixes}+- 라우팅 로직을 다시 구현하여 일부 Windows 기기에서 불안정한 웹사이트의 내용을 가져오지 못하던 문제를 해결했습니다.+- 이번 버전의 여러 리팩터링 과정에서 이전에는 찾기 어려웠던 많은 버그와 일부 IDE의 이상한 자동 완성 문제도 해결했습니다.+- 문서 웹사이트의 여러 부분을 수정했습니다.++## [v0.3.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.6) - 2025-10-01 {#v0.3.6}++### 🚀 새 기능 {#v0.3.6-new-stuff}+- `solve_cloudflare` 인수를 개선하여 `StealthyFetcher`와 해당 세션 클래스가 모든 종류의 Cloudflare Turnstile/Interstitial 검사를 통과할 수 있게 했습니다 🎉+- 이제 MCP 서버에서 `Streamable HTTP`를 사용할 수 있어 서버를 쉽게 외부에 제공할 수 있습니다.+- Docker 지원을 추가했습니다. 이제 릴리스마다 모든 브라우저가 포함된 이미지를 자동으로 빌드하고 Docker Hub에 푸시합니다.++### 🐛 버그 수정 {#v0.3.6-bug-fixes}+- 일부 상황에서 파서에 발생하던 인코딩 문제를 수정했습니다. 잘 알려진 `invalid start byte` 오류입니다.+- 라이브러리의 여러 부분을 재구성하여 메모리 누수를 수정했습니다. 이제 설정에 따라 메모리 사용량이 눈에 띄게 줄어듭니다. (#92도 해결)+- 코드 곳곳의 타입 표기를 개선하여 IDE를 더 편하게 사용할 수 있게 했습니다. (#93도 해결)++## [v0.3.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.5) - 2025-09-20 {#v0.3.5}++**여러 문제를 해결하는 필수 릴리스입니다**++### 🚀 새 기능 {#v0.3.5-new-stuff}+- 모든 브라우저 Fetcher(`DynamicFetcher`/`StealthyFetcher`/...)와 해당 세션 클래스가 웹사이트를 15-20% 더 빠르게 가져옵니다.+ 1. @AbdullahY36 님이 #87에서 로직을 개선하여 페이지 관리가 훨씬 빨라졌습니다.+ 2. 전체 검증 로직을 최적화하고 동기 요청의 페이지 생성을 개선하여 속도가 크게 높아졌습니다.++- `DynamicFetcher`와 해당 세션 클래스에서 `rebrowser-playwright`를 `PatchRight`로 교체하여 스텔스 모드를 크게 개선했습니다.+ 1. 이전에는 `rebrowser-playwright`가 `stealth`와 `real_chrome`을 함께 사용하면 제대로 동작하지 않아 비활성화되었습니다. 이제 `PatchRight`에서는 이 문제가 없습니다.+ 2. 이제 closed 모드의 Shadow Root와 상호작용할 수 있습니다. `PatchRight`가 자동으로 처리합니다.++### 🐛 버그 수정 {#v0.3.5-bug-fixes}+- `re` 메서드를 `Selectors` 클래스에서 사용할 때 발생하던 버그를 수정했습니다.+- 웹 스크래핑 셸의 `uncurl`과 `curl2fetcher` 명령이 curl의 `--data-raw` 플래그를 잘못 파싱하던 버그를 수정했습니다.+- 웹 스크래핑 셸의 `view` 명령에서 웹사이트의 인코딩에 따라 발생하던 버그를 수정했습니다.+- `mcp` 모드와 `extract` 명령에 영향을 주던 콘텐츠 변환 버그를 수정했습니다.++### 새 기여자 {#v0.3.5-new-contributors}+- @AbdullahY36 님이 #87에서 처음으로 기여했습니다.++## [v0.3.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.4) - 2025-09-16 {#v0.3.4}++**여러 문제를 해결하는 필수 릴리스입니다**++### 🚀 새 기능 {#v0.3.4-new-stuff}+- 대화형 셸에 모든 Fetcher 세션 클래스를 추가했습니다. 임포트 없이 바로 사용할 수 있습니다.++### 🐛 버그 수정 {#v0.3.4-bug-fixes}+- Cloudflare 검사를 처리하면서 페이지 내용을 가져올 때 Windows의 Playwright API에서 발생하던 버그를 우회하는 방법을 추가했습니다.+- 대화형 셸에서 `view` 명령의 인코딩 문제를 수정했습니다.+- `max_pages` 인수로 인해 `AsyncStealthySession`에서 실행이 중단되던 버그를 수정했습니다.+- `html_content`와 `prettify` 속성에 최근 업데이트로 생긴 문제를 수정했습니다. `Selector` 클래스의 두 속성이 인코딩에 따라 바이트를 반환했습니다. 이제 둘 다 이전처럼 문자열을 반환합니다.++## [v0.3.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.3) - 2025-09-15 {#v0.3.3}++- 브라우저 Fetcher에서 기본 브라우저 탭을 제거하는 로직을 없앴습니다. 이 로직이 실행을 중단시키는 오류를 일으켰기 때문입니다. Mac에서는 발생하지 않았고 Windows와 Linux에서만 재현했습니다.++## [v0.3.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.2) - 2025-09-15 {#v0.3.2}++v0.3.2 릴리스 노트++### 🚀 새 기능 {#v0.3.2-new-stuff}++- **선택적 Fetcher 의존성**: 모든 Fetcher를 선택적 의존성 그룹으로 옮겨 핵심 패키지 크기를 줄였습니다. 이제 기본 `scrapling` 모듈에는 파서만 있습니다. Fetcher나 명령줄 옵션을 사용하려면 `pip install "scrapling[fetchers]"`를 실행해야 합니다. 자세한 설치 방법은 [여기](index.md#installation)를 확인하세요.+- **세션의 페이지별 설정**: 브라우저 Fetcher의 세션 클래스에서 각 페이지를 별도로 설정할 수 있습니다. 이제 요청 수준의 모든 매개변수도 세션 수준의 매개변수처럼 검증합니다. 자세한 내용은 문서 웹사이트의 [이 페이지](fetching/stealthy.md#full-list-of-arguments)를 확인하세요.+ <br>예제:++ ```python+ with StealthySession(headless=True, solve_cloudflare=True) as session:+ page = session.fetch('https://nopecha.com/demo/cloudflare', google_search=False)+ ```++- **브라우저 Fetcher 개선**+ - 페이지에서 JavaScript 실행이 끝날 때까지 기다릴지 정하는 새 옵션을 추가했습니다. 이전과 같이 기본적으로 켜져 있습니다.++ ```python+ with DynamicSession(headless=True, disable_resources=False, network_idle=True) as session:+ page = session.fetch('https://quotes.toscrape.com/', load_dom=False)+ ```++ - `DynamicFetcher`와 해당 세션 클래스의 스텔스 모드가 더 안정적으로 동작합니다.+ - `DynamicFetcher`와 `StealthyFetcher` 모두 리소스를 덜 사용합니다. Playwright API의 영구 컨텍스트가 여는 기본 탭을 자동으로 찾아 닫습니다.+ - 브라우저 Fetcher의 페이지 순환 로직에서 중요한 버그를 수정했습니다. 이제 이전 페이지를 새 페이지로 교체합니다. 순환하며 재사용하는 탭에는 이전 설정이 남아 있을 수 있습니다.+ - `StealthyFetcher`와 해당 세션 클래스가 조금 더 빨라졌습니다(5%).++- **`.body` 속성 개선**: 전달받은 내용을 처리하지 않고 그대로 반환하므로 파일을 다운로드하고 HTML이 아닌 요청도 처리할 수 있습니다. 다음은 사진을 다운로드하는 예제입니다.++ ```python+ from scrapling.fetchers import Fetcher++ page = Fetcher.get('https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/poster.png')+ with open(file='poster.png', mode='wb') as f:+ f.write(page.body)+ ```++### 🐛 버그 수정 {#v0.3.2-bug-fixes}++- **인코딩 문제 해결**: 일부 웹사이트에서 파서, mcp 모드, extract 명령에 발생하던 여러 인코딩 문제를 수정했습니다. (#80과 #81도 해결)+- **더 빠른 파싱**: 여러 변경으로 라이브러리가 더 빨라졌으며, 업데이트된 벤치마크에서 확인할 수 있습니다.++### 🔨 기타 {#v0.3.2-misc}++- **벤치마크 업데이트**: 현재 속도 개선을 비슷한 라이브러리의 최신 버전과 비교하도록 성능 벤치마크를 갱신했습니다.+- **많은 코드를 리팩터링하고 사용하지 않는 코드를 더 나은 구현으로 교체했습니다**: 코드가 줄고 더 깔끔해져 유지 보수가 쉬워졌습니다.+- **YouTube 영상 추가**: MCP 문서에 영상을 포함했습니다.+- **새 이슈 템플릿**: 기존 템플릿을 사용할 수 없는 사용자를 위해 쉬운 새 템플릿을 추가했습니다.+- **CI 워크플로 최적화**: 문서나 코드가 아닌 파일만 바뀌면 테스트 워크플로를 건너뜁니다.+- **의존성 업데이트**: 여러 의존성을 최신 버전으로 높였습니다.+- **코드 스타일 개선**: 모든 파일에 새 ruff 규칙을 적용했습니다.+- **Pre-commit 훅**: pre-commit 설정을 업데이트했습니다.++### 🎯 호환성에 영향을 주는 변경 사항 {#v0.3.2-breaking-changes}++- `max_pages` 매개변수를 동기 `StealthySession`에서 제거하여 `DynamicSession`과 맞췄습니다. 동기 버전에서는 의미가 없는 매개변수입니다.++## [v0.3.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.1) - 2025-09-02 {#v0.3.1}++1. `shell` 선택 의존성 그룹 없이 Scrapling을 설치할 때 발생하던 문제를 수정했습니다. (#76)+2. 모든 브라우저 Fetcher와 해당 세션 클래스에 페이지 생성 시 실행할 JS 파일을 지정하는 새 인수를 추가했습니다. (#56):++```python+from scrapling.fetchers import StealthyFetcher++StealthyFetcher.fetch('https://example.com', init_script="/absolute/path/to/js/script.js")+```++## [v0.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3) - 2025-09-01 {#v0.3}++🎉 **주요 릴리스 - 전체 구조 개편**++Scrapling v0.3은 프로젝트 역사상 가장 큰 업데이트입니다. 전체 구조를 새로 작성하고 성능을 크게 개선했으며, AI 연동과 대화형 웹 스크래핑 셸을 비롯한 강력한 새 기능을 추가했습니다.++이번 릴리스에는 호환성에 영향을 주는 변경 사항이 여러 개 있습니다. 릴리스 노트를 주의 깊게 읽어 주세요.++### 🚀 주요 새 기능 {#v0.3-major-new-features}++#### 세션 기반 구조 {#v0.3-session-based-architecture}+- **새 세션 클래스**: 코드를 완전히 새로 작성해 세션을 유지하는 기능을 추가했습니다.+ - `FetcherSession` - 상태를 유지하는 HTTP 요청을 동기 코드와 비동기 코드 모두에서 사용할 수 있습니다.+ - `DynamicSession`/`AsyncDynamicSession` - 작업이 끝날 때까지 브라우저를 열어둔 채로 브라우저를 자동화합니다.+ - `StealthySession`/`AsyncStealthySession` - 작업이 끝날 때까지 브라우저를 열어둔 채로 스텔스 모드에서 탐색합니다.+- **비동기 브라우저 탭 관리**: 새 탭 풀 기능의 `max_pages` 인수로 브라우저 탭을 번갈아 사용하며 여러 페이지를 동시에 가져올 수 있습니다.+- **동시 세션**: 서로 분리된 여러 세션을 동시에 실행합니다.++자세한 내용은 웹사이트의 `Fetching` 섹션을 참고하세요.++#### 다양한 새 스텔스 및 봇 차단 우회 기능 {#v0.3-a-lot-of-new-stealth-anti-bot-capabilities}+- **🤖 Cloudflare 검사 통과**: [Cloudflare Turnstile 검사를 자동으로 통과하는 기능](fetching/stealthy.md#cloudflare-and-stealth-options)을 `StealthyFetcher`와 해당 세션 클래스에 추가했습니다.+- **브라우저 지문 모방**: 완전히 새로 만든 [Fetcher](fetching/static.md) 클래스로 실제 브라우저의 TLS 지문과 버전에 맞는 브라우저 헤더를 모방하고, HTTP/3 등을 사용할 수 있습니다.+- **스텔스 모드 개선**: `DynamicFetcher`와 해당 세션 클래스의 스텔스 모드가 더 강력하고 안정적으로 바뀌었습니다. (클래스의 다른 이름은 `PlayWrightFetcher`입니다.)++#### AI 연동 및 MCP 서버 {#v0.3-ai-integration-mcp-server}+- **기본 제공 MCP 서버**: AI로 웹 스크래핑을 돕는 Model Context Protocol 서버입니다.+- **강력한 도구 6개**: `get`, `bulk_get`, `fetch`, `bulk_fetch`, `stealthy_fetch`, `bulk_stealthy_fetch`+- **스마트 콘텐츠 추출**: 웹페이지나 요소를 Markdown 또는 HTML로 변환하거나 정리된 텍스트만 추출합니다.+- **CSS 선택자 지원**: AI에 콘텐츠를 전달하기 전에 Scrapling 엔진으로 특정 요소를 정확하게 선택합니다.+- **봇 차단 우회**: Cloudflare Turnstile과 다른 보호 장치를 처리합니다.+- **프록시 지원**: 프록시로 익명성을 유지하고 특정 지역에서 접속할 수 있습니다.+- **브라우저 모방**: TLS 지문과 버전에 맞는 실제 브라우저 헤더 등으로 실제 브라우저를 모방합니다.+- **병렬 처리**: 여러 URL을 동시에 스크래핑해 효율을 높입니다.+- [그 밖의 기능...](ai/mcp-server.md)++#### 새로운 대화형 웹 스크래핑 셸 {#v0.3-new-interactive-web-scraping-shell}+- **새로운 셸**: `get`, `post`, `put`, `delete`, `fetch`, `stealthy_fetch` 같은 편리한 단축 함수를 기본 제공하는 맞춤형 IPython 셸입니다.+- **스마트 페이지 관리**: 새 명령인 `page`와 `pages`가 셸에서 보낸 모든 요청의 현재 페이지와 기록을 자동으로 저장합니다.+- **curl 연동**: 브라우저 DevTools의 curl 명령을 `uncurl`과 `curl2fetcher` 함수로 `Fetcher` 요청으로 변환합니다.+- [그 밖의 기능...](cli/interactive-shell.md)++#### 프로그래밍 없이 터미널에서 스크래핑하기 {#v0.3-scrape-from-the-terminal-without-programming}+- **새 추출 명령**: 프로그래밍 없이 터미널에서 스크래핑합니다.+ - `scrapling extract get/post/put/delete` - 간단한 HTTP 요청+ - `scrapling extract fetch` - 동적 콘텐츠 스크래핑+ - `scrapling extract stealthy-fetch` - 봇 차단 우회+- **웹페이지를 다운로드**하고 콘텐츠를 파일에 저장합니다.+- **HTML을 Markdown처럼 읽기 쉬운 형식으로 변환**하거나, HTML 그대로 저장하거나, 페이지의 텍스트만 추출합니다.+- **사용자 지정 CSS 선택자를 지원**해 페이지의 특정 부분을 추출할 수 있습니다.+- **HTTP 요청과 브라우저를 통한 가져오기를 처리합니다.**+- **다양한 설정을 지원합니다.** 사용자 지정 헤더, 쿠키, 프록시 등 여러 옵션을 사용할 수 있습니다. 코드에서 쓸 수 있는 거의 모든 옵션을 터미널에서도 쓸 수 있습니다.+- [그 밖의 기능...](cli/extract-commands.md)++### 🔧 기술 개선 {#v0.3-technical-improvements}++#### 성능 개선 {#v0.3-performance-enhancements}+- **Fetcher가 이제 4배 빠릅니다.** 네, 제대로 읽으셨습니다!+- **DynamicFetcher가 이제 약 60% 빠릅니다.** 설정에 따라 훨씬 빨라집니다. 특히 스텔스 모드에서 그렇습니다.+- **StealthyFetcher가 이제 20–30% 빠릅니다.** 새 구조를 사용하고 `Camoufox` Python 인터페이스 대신 자체 구현을 사용하기 시작했습니다.+- 주요 선택 메서드(`find_by_text`, `find_similar`, `find_by_regex`, `relocate` 등)의 **전체 속도가 50%+ 향상됐습니다.** 🚀+- **첫 결과를 반환하는 CSS/XPath 메서드의 속도가 약 10% 향상됐습니다.** `css_first`와 `xpath_first`가 이제 `css`와 `xpath`보다 빠릅니다.+- 콘텐츠 추출에 쓰는 **`get_all_text()` 메서드가 40% 빨라졌습니다.**+- 적응형 기능으로 요소를 다시 찾는 **속도가 20% 향상됐습니다.**+- **탐색 속성 최적화**: `next`, `previous`, `below_elements` 등의 속성이 눈에 띄게 빨라졌습니다.+- **텍스트 정리 작업이 5배 빨라졌습니다.**+- 가져오기 구문을 최적화하고 부가 작업을 줄여 **메모리 효율을 개선했습니다.**+- **⚡ 매우 빠른 가져오기**: 모듈 로딩을 최적화해 시작 시간을 줄였습니다.+- **벤치마크 개선**: 속도 개선으로 Scrapling이 다른 라이브러리와 비교해 이전보다 훨씬 빨라졌습니다. BeautifulSoup보다 1775배, AutoScraper보다 5.1배 빠릅니다. [벤치마크](benchmarks.md)를 확인하세요.++#### 구조, 코드 품질 및 사용 편의 개선 {#v0.3-architecture-code-quality-and-quality-of-life}+- **영구 컨텍스트**: 모든 브라우저 기반 Fetcher가 이제 기본적으로 영구 컨텍스트를 사용합니다. (#64도 해결합니다.)+- **msgspec으로 모든 브라우저 기반 Fetcher의 설정을 빠르게 검증합니다.** 요청을 실행하기 전에 검증하므로 오류를 더 쉽게 찾을 수 있습니다.+- Fetcher가 반환하는 **모든 쿠키**가 이제 해당 Fetcher에서 받는 형식과 일치합니다. 따라서 쿠키를 가져온 뒤 모든 Fetcher와 해당 세션 클래스에 다시 전달할 수 있습니다.+- `ruff`로 전환해 **린트 검사와 서식 지정이 빨라졌습니다.**+- **현대적인 빌드 시스템**: setup.py에서 pyproject.toml로 전환했습니다. 📦+- **GitHub Actions와 워크플로를 개선**해 개발과 테스트를 더 원활하게 진행할 수 있습니다.+- **🎨 타입 힌트 개선**: 최신 Python 표준으로 모든 타입을 표시해 IDE 지원과 안정성을 높였습니다.+- **더 깔끔한 코드**: 사용하지 않는 코드를 제거하고 핵심 함수를 최적화했습니다. 🧹+- **🚀 하위 호환성**: 이전 코드와의 호환성을 유지하는 단축 기능을 추가했습니다.++### 호환성에 영향을 주는 변경 사항 {#v0.3-breaking-changes}++#### 최소 Python 버전 {#v0.3-minimum-python-version}+- **Python 3.10+ 필요**: Python 3.9 이하 버전의 지원을 중단했습니다.++#### 클래스와 메서드 이름 {#v0.3-class-and-method-naming}+특히 새 사용자가 더 쉽게 이해하고 일관되게 사용할 수 있도록 이름을 바꿨습니다.++- **`Adaptor` → `Selector`**: 핵심 파싱 클래스의 이름을 바꿨습니다. 하위 호환성을 위해 `Adaptor`로도 가져올 수 있습니다.+- **`Adaptors` → `Selectors`**: 컬렉션 클래스의 이름을 바꿨습니다. 하위 호환성을 위해 `Adaptors`로도 가져올 수 있습니다.+- **`auto_match` → `adaptive`**: 모든 메서드에서 인수 이름을 바꿨습니다.+- **`adaptor_arguments` → `selector_config`**: 설정 인수의 이름을 바꿨습니다.+- **`automatch_domain` → `adaptive_domain`**: 도메인 인수의 이름을 바꿨습니다.+- **`additional_arguments` → `additional_args`**: 인수 이름을 줄였습니다.+- **⚠️ `text/body` → `content`**: Selector 생성자 인수가 이제 `str`과 `bytes` 형식을 모두 받습니다.+- **`PlayWrightFetcher` → `DynamicFetcher`**: 브라우저 자동화 클래스의 이름을 바꿨습니다. 하위 호환성을 위해 `PlayWrightFetcher`로도 가져올 수 있습니다.+- **DynamicFetcher에서 NSTBrowser 로직과 인수를 제거했습니다.** 이제 이 로직을 남겨둘 이유가 없기 때문입니다.+- **StealthyFetcher의 headless 인수에 더 이상 'virtual'을 전달할 수 없습니다.** 이제 Camoufox 라이브러리는 브라우저 설치 경로와 나머지 실행 옵션을 가져오는 용도로만 사용하기 때문입니다.++### 🐛 버그 수정 {#v0.3-bug-fixes}++- `get_all_text`에서 무시하는 태그 안에 중첩된 자식 요소를 세는 방식을 수정했습니다. (#61)+- Python 실행 파일 경로에 공백이 있으면 설치에 문제가 생기는 오류를 수정했습니다. (#57)+- 적응형 기능을 켰을 때 저장소의 재귀 처리에서 생기는 스레드 문제를 해결했습니다.+- `FetcherSession`에 Sentinel 패턴을 사용해 인수 우선순위 문제를 수정했습니다.+- `StealthyFetcher`의 프록시 타입 처리 문제를 해결했습니다.+- `referer`와 `google_search` 인수의 충돌을 수정했습니다.+- 비동기 스텔스 스크립트 삽입 문제를 수정했습니다.++## [v0.2.99](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.99) - 2025-04-08 {#v0.2.99}++**Scrapling의 기능을 온전히 사용하려면 꼭 필요한 업데이트입니다.**++### 변경 사항 {#v0.2.99-what-s-changed}+#### 전체 문서를 담은 새 웹사이트 {#v0.2.99-new-full-documentation-website}+- 드디어 완성했습니다. 😄 [여기](index.md)에서 확인하세요.+#### Fetcher 가져오기 방식 통일 {#v0.2.99-unified-import-logic-for-fetchers}+- 이제 `from scrapling.fetchers import Fetcher, AsyncFetcher, StealthyFetcher, PlayWrightFetcher`로 모든 Fetcher를 가져온 뒤, 객체를 만들지 않고 `page = Fetcher.get(...)`처럼 바로 사용할 수 있습니다.<br/> 기존의 `from scrapling.defaults import Fetcher, AsyncFetcher, StealthyFetcher, PlayWrightFetcher`를 대체합니다.+#### 호환성에 영향을 주는 변경: automatch가 이제 기본적으로 꺼집니다 {#v0.2.99-breaking-change-automatch-is-now-turned-off-by-default}+- Fetcher에서 automatch를 켜거나 다른 파싱 옵션을 설정하는 새 방식을 추가했습니다. 자세한 내용은 [문서 페이지](fetching/choosing.md#parser-configuration-in-all-fetchers)를 참고하세요.+> 하위 호환성을 위해 기존 가져오기 구문과 로직도 경고와 함께 계속 사용할 수 있습니다.+#### Fetcher에 새 옵션 추가 {#v0.2.99-new-options-added-to-fetchers}+- `StealthyFetcher`와 `PlayWrightFetcher` 모두 페이지를 가져올 때 쓰는 새 인수 `wait`를 지원합니다. 페이지를 닫고 응답을 반환하기 전에 지정한 시간(밀리초)만큼 기다립니다.+- 이제 `StealthyFetcher`의 `fetch`와 `async_fetch` 메서드가 `additional_arguments` 인수를 지원합니다. Camoufox에 추가 설정으로 전달하며 Scrapling 설정보다 우선합니다. (#54)+#### 버그 수정 {#v0.2.99-bugs-squashed}+- `async_fetch`에서 리디렉션을 처리하는 버그를 수정했습니다. `StealthyFetcher`와 `PlayWrightFetcher` 클래스 모두에 해당합니다.++**_모든 응원과 기부에 감사드립니다!_**++## [v0.2.98](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.98) - 2025-03-17 {#v0.2.98}++**Scrapling의 기능을 온전히 사용하려면 꼭 필요한 업데이트입니다.**++### 변경 사항 {#v0.2.98-what-s-changed}+#### 다양한 메모리 사용량 및 속도 최적화 {#v0.2.98-various-memory-usage-and-speed-optimizations}+- 모든 선택 메서드의 메모리 사용량이 이전의 약 40%로 줄었고 속도도 조금 빨라졌습니다.+- 라이브러리의 모든 하위 모듈에 지연 로딩을 적용해 사용하는 부분만 로드합니다. 예를 들면 다음과 같습니다.+업데이트 전에는 `from scrapling import Adaptor`를 실행하면 모든 Fetcher 등도 함께 로드되어 RAM을 `30-40mb` 사용했습니다. 이제는 `~1.2mb`만 사용합니다.+- 지난 업데이트에서는 큰 요청 풀을 사용할 때 메모리 사용량을 이전의 약 32%로 줄였습니다. 이번에는 캐시를 더 조정해 그보다 적게 사용합니다.+- 파서의 전체 속도가 2-5% 정도 향상됐습니다.++**_모든 응원과 기부에 감사드립니다!_**++## [v0.2.97](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.97) - 2025-03-15 {#v0.2.97}++**Scrapling의 기능을 온전히 사용하려면 꼭 필요한 업데이트입니다.**++### 변경 사항 {#v0.2.97-what-s-changed}+#### 모든 Fetcher의 메모리 사용량 감소 및 소폭 속도 향상 {#v0.2.97-lower-memory-usage-and-small-speed-increase-across-all-fetchers}+- 라이브러리 전반에 캐시 크기 제한을 새로 적용했습니다. 많은 요청이나 작업을 처리할 때 메모리 사용량이 눈에 띄게 줄어듭니다.+- Fetcher 코드의 많은 부분을 정리해 유지보수를 쉽게 하고 속도를 조금 높였습니다.++#### 버그 수정 {#v0.2.97-bugs-fixed}+- `TextHandler`만 가져와 문자열이 아닌 값을 전달하면 빈 문자열로 바뀌던 버그를 수정했습니다. 이제 `TextHandler`에 전달한 값은 먼저 문자열로 바뀐 다음 `TextHandler`로 변환됩니다. 어떤 값이든 이 과정을 거칩니다. `TextHandler`는 이름 그대로 문자열만 다루는 클래스입니다! (#45)+- 대부분의 AsyncFetcher 메서드에서 `retries` 인수가 반영되지 않던 버그를 수정했습니다.++#### 기타 {#v0.2.97-miscellaneous}+- 모든 Fetcher에서 대부분의 인수에 대한 타입 힌트를 더 명확하고 정확하게 바꿨습니다.++**_모든 응원과 기부에 감사드립니다!_**++## [v0.2.96](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.96) - 2025-03-05 {#v0.2.96}++**Scrapling의 기능을 온전히 사용하려면 꼭 필요한 업데이트입니다.**++### 변경 사항 {#v0.2.96-what-s-changed}+1. `-f` 옵션을 `scrapling install`에 추가해 브라우저 의존 패키지를 강제로 다시 설치할 수 있습니다. 지금 `scrapling install -f`를 실행하는 것을 권장합니다. 새 Camoufox 브라우저 버전으로 `StealthyFetcher`가 훨씬 빨라진 것을 느낄 수 있습니다. :)+2. `TextHandler`를 슬라이싱하면 `TextHandlers`가 반환되던 버그를 수정했습니다. 이제 `TextHandler`를 반환하며 관련 타입 힌트도 수정했습니다. (#41)+3. `scrapling install`이 일부 상황에서 Python 셸을 열던 문제를 수정했습니다!++## [v0.2.95](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.95) - 2025-02-25 {#v0.2.95}++**Scrapling의 기능을 온전히 사용하려면 꼭 필요한 업데이트입니다.**++### 변경 사항 {#v0.2.95-what-s-changed}+1. `Fetcher`에서 `stealthy_headers` 인수로 생성한 헤더가 `Accept` 등 사용자가 지정한 일부 헤더를 덮어쓰던 버그를 수정했습니다. (#39)+2. 헤더 생성 로직을 조금 개선해 속도도 약간 빨라질 것입니다.++## [v0.2.94](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.94) - 2025-02-22 {#v0.2.94}++**Scrapling의 기능을 온전히 사용하려면 꼭 필요한 업데이트입니다.**++### 변경 사항 {#v0.2.94-what-s-changed}+1. 리디렉션을 확인할 수 있도록 모든 Fetcher에 `history` 속성을 추가했습니다. (#32)+2. `case_sensitive` 인수의 로직을 모든 `re`/`re_first`에서 수정했습니다. 이 인수를 사용했다면 코드가 다른 결과를 반환할 수 있습니다. (제대로 작동하지 않는 것을 알면서 이슈를 열지 않으셨으니 어쩔 수 없죠. ㅎㅎ)+3. 의존 패키지를 업데이트하고 Camoufox 엔진(StealthyFetcher)에서 `coop`을 다시 켰습니다.++## [v0.2.93](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.93) - 2025-01-31 {#v0.2.93}++**Scrapling의 기능을 온전히 사용하려면 꼭 필요한 업데이트입니다.**++### 변경 사항 {#v0.2.93-what-s-changed}+1. 파싱 엔진 전체의 반환 타입을 통일했습니다. 항상 `Adaptor`, `Adaptors`, `TextHandler`, `TextHandlers`, `None` 중 하나를 반환하며, CSS 선택자를 조합한 경우처럼 결과가 섞여 있으면 리스트를 반환합니다. 타입을 직접 확인하는 작업을 줄여 코드를 더 편하게 작성하고, 라이브러리를 더 안정적으로 사용하며, 메서드를 항상 이어서 호출할 수 있습니다.+2. 파싱 엔진 대부분, 특히 `Adaptor` 클래스를 더 깔끔하고 빠르게 정리했습니다. 거의 모든 메서드와 속성, 특히 검색 메서드의 속도가 5-40% 향상됐습니다. 일부 메서드는 더 크게 빨라졌습니다. `find_by_regex`는 약 60% 빨라졌습니다! automatch 기능도 약 5% 빨라졌습니다.+3. `find_all`/`find` 메서드가 전달받은 필터를 어떤 때는 OR로, 어떤 때는 AND로 적용하던 로직 버그를 수정했습니다. 이제 반환되는 모든 요소는 전달한 모든 필터를 만족해야 합니다.+4. 정규식 관련 메서드가 모두 `TextHandler`/`TextHandlers`를 반환해 메서드를 쉽게 이어서 호출할 수 있습니다.+5. **새로운** `below_elements` 속성을 추가했습니다. DOM 트리에서 현재 요소 아래에 있는 모든 요소를 담은 `Adaptors` 객체를 반환합니다.+6. HTML 소스를 문자열로 반환하던 모든 메서드와 속성이 이제 `TextHandler`로 반환합니다. 결과에 정규식을 쉽게 적용하는 등의 작업을 할 수 있습니다.+7. StealthyFetcher가 조금 더 빨라졌고 탐지도 더 잘 피합니다. **Cloudflare Turnstile**처럼 iframe 안에 있는 CAPTCHA도 클릭할 수 있습니다.+8. 라이브러리의 거의 절반에서 자동 완성과 타입 힌트를 크게 개선했습니다. 특히 `Adaptor`, `TextHandler`, `TextHandlers`를 개선했습니다.+9. `TextHandler`를 슬라이싱하거나 인덱스로 접근하거나 `split` 메서드를 쓰면 이제 다른 `TextHandler`를 반환합니다. 표준 Python 문자열은 반환하지 않습니다. 거의 모든 표준 문자열 연산과 메서드가 일반 문자열 대신 다른 `Texthandler`를 반환하므로 메서드와 함수를 항상 이어서 호출할 수 있습니다.+10. 작은 버그와 오타를 수정했습니다. 예를 들어 Fetcher의 async_put이 put 요청 대신 post 요청을 보내고 있었습니다. 😶🌫️+11. 문서 웹사이트를 완성하기 전에 README를 조금 개선했습니다.++원래는 0.3 버전까지 기다리는 동안 작은 업데이트만 하려 했지만, 더 나은 버전으로 만들기로 했습니다.++## [v0.2.92](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.92) - 2024-12-26 {#v0.2.92}++### 변경 사항 {#v0.2.92-what-s-changed}+- 로드한 페이지에 iframe이 많을 때 브라우저 기반 Fetcher가 반환하는 응답은 이제 더 신뢰할 수 있는 데이터 소스를 사용합니다.+- **`Scrapling` 설치가 더 쉬워졌습니다. pip로 설치한 다음 터미널에서 `scrapling install`을 실행하면 준비가 끝납니다!**+- 파서의 부정확한 타입 힌트를 수정했습니다.++## [v0.2.91](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.91) - 2024-12-19 {#v0.2.91}++### 변경 사항 {#v0.2.91-what-s-changed}+- 페이지를 가져왔다는 로그가 첫 요청에서만 표시되던 버그를 수정했습니다.+- Playwright API는 기본적으로 페이지를 탐색할 때 `goto` 메서드에 지정한 로드 상태 `["load", "domcontentloaded", "networkidle"]`를 만족하는 첫 응답을 반환합니다. 따라서 Cloudflare처럼 대기 페이지를 거쳐 실제 웹사이트로 이동하면 Playwright는 첫 상태 코드를 반환하며, 이 코드는 403일 수 있습니다. 이번 업데이트에서는 Playwright API를 사용하는 `PlaywrightFetcher`와 `StealthyFetcher` 모두에서 이 문제를 해결했습니다. 이제 결과가 Playwright의 기본 동작에 영향을 받지 않습니다.+- `Fetcher` 클래스에 SOCKS 프록시 지원을 추가했습니다.+- `wait_selector_state` 인수의 타입 힌트를 수정했습니다. 이제 자동 완성에서 실제로 사용할 수 있는 값이 표시됩니다.++## [v0.2.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.9) - 2024-12-16 {#v0.2.9}++### 변경 사항 {#v0.2.9-what-s-changed}+##### 새 기능 {#v0.2.9-new-features}+1. **오랫동안 기다려온** Scrapling의 비동기 지원을 추가했습니다! `AsyncFetcher`는 `Fetcher`의 비동기 버전입니다. `StealthyFetcher`와 `PlayWrightFetcher` 모두 같은 옵션을 지원하는 새 메서드 `async_fetch`를 제공합니다.++```python+>> from scrapling import StealthyFetcher+>> page = await StealthyFetcher().async_fetch('https://www.browserscan.net/bot-detection') # the async version of fetch+>> page.status == 200+True+```++2. `StealthyFetcher` 클래스의 가져오기 메서드에 `geoip` 인수를 추가했습니다. 켜면 IP 주소의 경도, 위도, 시간대, 국가, 로캘을 자동으로 사용하고 WebRTC IP 주소를 위장합니다. 대상 지역의 언어 사용자 분포를 바탕으로 브라우저 언어도 계산하고 위장합니다.+3. `retries` 인수를 `Fetcher`/`AsyncFetcher` 클래스에 추가했습니다. 이제 `httpx`로 보내는 각 요청의 재시도 횟수를 설정할 수 있습니다.+4. `url_join` 메서드를 `Adaptor`와 Fetcher에 추가했습니다. 상대 URL을 현재 URL과 합쳐 완전한 절대 URL을 만듭니다!+5. `keep_cdata` 메서드를 `Adaptor`와 Fetcher에 추가했습니다. 필요할 때 파서가 cdata를 제거하지 않도록 할 수 있습니다.+6. 이제 `Adaptor`/`Response`의 `body` 메서드가 가능하면 원본 HTML 응답을 반환합니다. 라이브러리에서 처리하지 않은 응답입니다.+7. `Response` 클래스에 로깅을 추가했습니다. 이제 Fetcher를 사용하면 받은 응답의 정보를 로그로 확인할 수 있습니다.+예:++ ```python+ >> from scrapling.defaults import Fetcher+ >> Fetcher.get('https://books.toscrape.com/index.html')+ [2024-12-16 13:33:36] INFO: Fetched (200) <GET https://books.toscrape.com/index.html> (referer: https://www.google.com/search?q=toscrape)+ >>+ ```++8. 이제 `TextHandler`에 `.replace()` 같은 표준 문자열 메서드를 사용하면 다른 `TextHandler`를 반환합니다. 이전에는 표준 문자열을 반환했습니다.+9. 라이브러리 전반의 속도를 크게 개선하고 Fetcher 클래스 전체의 탐지 회피 성능도 개선했습니다.+10. `extract_first`\`extract`처럼 원래 객체와 같은 결과를 반환하는 호환용 함수를 추가했습니다. 이 함수들은 Scrapy/Parsel에서 쓰이므로, 필요할 때 그 코드를 Scrapling으로 쉽게 옮기기 위해서만 추가했습니다!+11. 코드의 많은 부분을 정리하고 필요한 곳에 캐시를 적용했습니다. 이제 요청을 한꺼번에 많이 보내면 속도가 크게 빨라집니다.++##### 호환성에 영향을 주는 변경 사항 {#v0.2.9-breaking-changes}+- Python 3.8 지원을 중단했습니다. 주된 이유는 Playwright가 지원을 중단했기 때문이지만, 원래 문제가 많던 버전이기도 합니다.+- 라이브러리 전체에서 `debug` 인수를 제거했습니다. 이제 디버깅 모드로 설정하려면 라이브러리를 가져온 뒤 다음 코드를 실행하세요.++ ```python+ >>> import logging+ >>> logging.getLogger("scrapling").setLevel(logging.DEBUG)+ ```++##### 버그 수정 {#v0.2.9-bugs-squashed}+1. 많은 보호 장치가 WebGL의 활성화 여부를 확인하므로 이제 기본적으로 켜집니다.+2. 문서와 README의 일부 잘못된 내용과 오타를 수정했습니다.++##### 사용 편의 개선 {#v0.2.9-quality-of-life-changes}+1. 모든 로깅을 `scrapling`이라는 로거로 통일해 더 쉽고 깔끔하게 제어할 수 있습니다. 이전에는 루트 로거를 사용했습니다.+2. 테스트 폴더를 더 깔끔하게 구성하고 새 기능의 테스트를 추가했습니다. 모든 테스트를 더 깔끔하게 다시 작성했으며, 더 많은 코드를 확인하도록 테스트를 추가했습니다.+3. 코드의 많은 부분을 더 깔끔하고 유지보수하기 쉽게 정리했습니다.++> 이 변경 사항은 원래 0.3에 넣으려던 내용입니다. 다음 버전까지 시간이 걸릴 것 같아 이번에 넣었습니다. 이제 자세한 설명을 담은 문서 웹사이트를 완성한 뒤 0.3 버전을 작업할 예정입니다.++## [v0.2.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.8) - 2024-11-30 {#v0.2.8}++### 변경 사항 {#v0.2.8-what-s-changed}+- 코드 사용에 꼭 필요한 편의 개선을 하고 기본 README 파일의 오타를 수정한 작은 업데이트입니다. (#20)++## [v0.2.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.7) - 2024-11-26 {#v0.2.7}++### 변경 사항 {#v0.2.7-what-s-changed}+##### 새 기능 {#v0.2.7-new-features}+- 이제 `wait_selector` 인수를 `StealthyFetcher`와 `PlayWrightFetcher` 클래스에서 사용하면, Scrapling이 평소처럼 JS가 완전히 로드되고 실행될 때까지 다시 기다립니다. `network_idle` 인수도 사용했다면 이 과정이 끝난 뒤 해당 상태도 다시 기다립니다. 물론 모든 상태가 이미 충족됐다면 기다리지 않습니다.+- 이제 `StealthyFetcher`에서 `disable_ads` 인수로 광고를 켜거나 끌 수 있습니다. 이 옵션은 기본적으로 켜져 있으며 `ublock origin` 확장 기능을 설치합니다.+- 이제 `PlayWrightFetcher`가 사용하는 로캘을 `locale` 인수로 설정할 수 있습니다. 기본값은 여전히 `en-US`입니다.+- 이제 `Fetcher`로 보내는 기본 요청에 `http://username:password@localhost:8030` 형식의 프록시를 사용할 수 있습니다.+- `PlayWrightFetcher`의 스텔스 모드를 조금 개선했습니다.++##### 버그 수정 및 개선 {#v0.2.7-bugs-squashed-improvements}+1. 이제 `PlayWrightFetcher` 클래스에서 프록시를 켜는 것은 `stealth` 모드의 활성화 여부와 관계없습니다. 알려주신 [@AbdullahY36](https://github.com/AbdullahY36) 님께 감사드립니다.+2. 이제 `ResponseEncoding`이 응답에서 받은 인코딩을 해당 페이지에 사용할 수 있는지 확인합니다. 받은 인코딩에서 오류가 나면 Scrapling은 `utf-8`을 사용합니다.++## [v0.2.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.6) - 2024-11-24 {#v0.2.6}++### 변경 사항 {#v0.2.6-what-s-changed}+##### 새 기능 {#v0.2.6-new-features}+- 이제 `PlayWrightFetcher`는 `real_chrome` 인수를 `PlayWrightFetcher.fetch` 함수에 전달해 실제 브라우저를 바로 사용할 수 있습니다. Chrome이 설치되어 있어야 합니다. Scrapling이 설치된 Chrome을 실행하며 대부분의 옵션을 평소처럼 사용할 수 있습니다. 이전에는 `cdp_url` 인수로만 가능했습니다.+- 실제 브라우저용으로 생성하는 헤더의 버전을 높였습니다.++##### 버그 수정 {#v0.2.6-bugs-squashed}+1. `BrowserForge`가 생성하는 브라우저 헤더의 형식이 오래되어 일부 보호 장치가 Scrapling을 탐지한다는 것을 알게 됐습니다. 이제 `BrowserForge`는 실제 브라우저의 User-Agent를 생성하는 데만 사용합니다.+2. Google의 ReCaptcha가 탐지하므로 이제 `hide_canvas` 인수는 기본적으로 꺼져 있습니다.++## [v0.2.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.5) - 2024-11-23 {#v0.2.5}++### 변경 사항 {#v0.2.5-what-s-changed}++##### 버그 수정 {#v0.2.5-bugs-squashed}+- 'wait_selector' 인수에 맞는 요소가 1개보다 많을 때 생기는 오류를 처리했습니다. `StealthyFetcher`와 `PlayWrightFetcher` 클래스에 해당합니다.+- `content_type` 헤더의 값에 `charset` 같은 매개변수가 있을 때 인코딩 타입이 잘못되던 문제를 수정했습니다. [#12](https://github.com/D4Vinci/Scrapling/issues/12)를 알려주신 @andyfcx 님께 감사드립니다.++##### 사용 편의 개선 {#v0.2.5-quality-of-life}+- 새로운 코드 영역도 확인하도록 테스트를 추가하고 스레드에서 테스트를 실행하게 했습니다.+- Sphinx의 apidoc이나 비슷한 도구에서 제대로 읽을 수 있도록 docstring을 수정했습니다.++##### 새 기여자 {#v0.2.5-new-contributors}+- @andyfcx 님이 [#13 ](https://github.com/D4Vinci/Scrapling/pull/13)에서 처음 기여했습니다.++## [v0.2.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.4) - 2024-11-20 {#v0.2.4}++### 변경 사항 {#v0.2.4-what-s-changed}++##### 버그 수정 {#v0.2.4-bugs-squashed}+- `network_idle` 인수를 사용한 뒤 응답 바이트를 가져올 때 생기는 버그를 수정했습니다. `StealthyFetcher`와 `PlayWrightFetcher` 클래스 모두에 해당합니다. <br/> 이 버그로 다음 오류 메시지가 표시됐습니다.++ ```+ Response.body: Protocol error (Network.getResponseBody): No resource with given identifier found+ ```++- PlayWright API가 응답에 빈 상태 메시지를 반환할 때가 있습니다. 이제 이런 경우 `Scrapling`이 상태 메시지를 직접 생성합니다. `StealthyFetcher`와 `PlayWrightFetcher` 클래스 모두에 해당합니다.++## [v0.2.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.3) - 2024-11-19 {#v0.2.3}++### 변경 사항 {#v0.2.3-what-s-changed}++##### 버그 수정 {#v0.2.3-bugs-squashed}+- pip로 설치하면 PlayWright Fetcher의 스텔스 모드가 전혀 작동하지 않던 버그를 수정했습니다.++## [v0.2.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.2) - 2024-11-16 {#v0.2.2}++### 변경 사항 {#v0.2.2-what-s-changed}+##### 새 기능 {#v0.2.2-new-features}+- 생성되는 `Adaptor` 객체에 인수를 전달하지 않고 기본값을 쓰려면, 이제 다음 가져오기 구문으로 코드를 더 깔끔하게 작성할 수 있습니다.++ ```python+ >> from scrapling.default import Fetcher, StealthyFetcher, PlayWrightFetcher+ >> page = Fetcher.get('https://example.com', stealthy_headers=True)+ ```++ 그렇지 않으면 다음처럼 작성합니다.++ ```python+ >> from scrapling import Fetcher, StealthyFetcher, PlayWrightFetcher+ >> page = Fetcher(auto_match=False).get('https://example.com', stealthy_headers=True)+ ```++##### 버그 수정 {#v0.2.2-bugs-squashed}+1. 어제 배포한 v0.2.1 패치에서 `Response` 객체에 생긴 버그를 수정했습니다. 일부 중첩된 선택 및 파싱 작업에서 발생했습니다.++## [v0.2.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.1) - 2024-11-15 {#v0.2.1}++### 변경 사항 {#v0.2.1-what-s-changed}+##### 새 기능 {#v0.2.1-new-features}+1. 이제 모든 Fetcher가 반환하는 `Response` 객체는 `Adaptor` 객체와 같으며, `status`, `reason`, `cookies`, `headers`, `request_headers` 속성만 추가로 있습니다. `cookies`, `headers`, `request_headers`는 항상 `dictionary` 타입입니다. <br/>이제 다음처럼 코드를 작성할 수 있습니다.++ ```python+ >> from scrapling import Fetcher+ >> page = Fetcher().get('https://example.com', stealthy_headers=True)+ >> print(page.status)+ 200+ >> products = page.css('.product')+ ```++ 이전에는 다음처럼 작성했습니다.++ ```python+ >> from scrapling import Fetcher+ >> fetcher = Fetcher().get('https://example.com', stealthy_headers=True)+ >> print(fetcher.status)+ 200+ >> page = fetcher.adaptor+ >> products = page.css('.product')+ ```++ 하위 호환성을 위해 `.adaptor` 속성도 계속 작동하도록 남겨두었습니다.++2. 이제 `StealthyFetcher`와 `PlayWrightFetcher` 클래스 모두 가져오기 메서드에 `proxy` 인수를 받습니다. 문자열이나 딕셔너리를 전달할 수 있습니다.+3. 이제 `StealthyFetcher` 클래스에 `os_randomize` 인수가 있습니다. `fetch` 메서드에서 사용합니다. 켜면 Scrapling이 사용할 OS 지문을 무작위로 선택합니다. 기본적으로는 현재 OS와 일치하는 지문을 사용합니다.++##### 버그 수정 {#v0.2.1-bugs-squashed}+1. `Fetcher` 클래스에서 헤더를 전달할 때 생기는 버그를 수정했습니다.+2. Fetcher 유형의 클래스에서 전달한 JSON 응답을 파싱할 때 생기는 버그를 수정했습니다.++##### 사용 편의 개선 {#v0.2.1-quality-of-life-changes}+1. 텍스트 기능은 원래 텍스트를 반환하기 전에 HTML 주석을 제거하려고 했습니다. 하지만 일부 상황에서 오류가 발생했고 코드가 필요 이상으로 복잡해졌습니다. 이제 lxml의 기본 동작으로 되돌렸습니다. **선택자처럼 요소의 텍스트를 사용하는 모든 작업이 조금 빨라집니다.** lxml/parsel/scrapy에서 텍스트가 이상하게 나뉘는 것을 피하려고 텍스트를 반환하기 전에 요소의 HTML 주석을 제거하려면, `keep_comments` 인수를 기본값인 True로 유지하세요.++## [v0.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2) - 2024-11-11 {#v0.2}++### 변경 사항 {#v0.2-what-s-changed}+##### 새 기능 {#v0.2-new-features}+1. 3개의 새로운 주요 유형을 갖춘 `Fetchers` 기능을 추가했습니다. 다양한 옵션으로 Scrapling이 페이지를 가져오게 할 수 있습니다!+ - `Fetcher` 클래스는 기본 HTTP 요청에 사용합니다.+ - `StealthyFetcher` 클래스는 [스텔스 기능을 추가한 Firefox](https://github.com/daijro/camoufox)를 사용하는 완전한 스텔스 Fetcher입니다.+ - `PlayWrightFetcher` 클래스는 기본 PlayWright, 제가 만든 스텔스 모드의 PlayWright, CDP를 통한 실제 브라우저, [NSTBrowser](https://app.nstbrowser.io/r/1vO5e5)의 [docker browserless](https://hub.docker.com/r/nstbrowser/browserless)로 브라우저 기반 요청을 보낼 수 있습니다!+2. 페이지에서 마법처럼 요소를 쉽게 찾는 완전히 새로운 `find_all`/`find` 메서드를 추가했습니다!+3. `filter`와 `search` 메서드를 `Adaptors` 클래스에 추가해 `Adaptor` 객체 그룹을 한꺼번에 쉽게 처리할 수 있습니다.+4. 더 편하게 쓸 수 있도록 `css_first`와 `xpath_first` 메서드를 추가했습니다.+5. 새 클래스 타입 `TextHandlers`를 추가했습니다. `TextHandler` 객체를 한꺼번에 처리하는 데 사용하며, `Adaptors` 클래스와 비슷합니다.+6. `generate_full_css_selector`와 `generate_full_xpath_selector` 메서드를 추가했습니다.++##### 버그 수정 {#v0.2-bugs-squashed}+1. 이제 `Adaptors` 클래스의 `re_first`는 내부의 모든 `Adaptor` 객체에서 처음 일치하는 결과를 반환합니다. 이전에는 `re_first`를 모든 `Adaptor` 객체에 호출한 결과를 모아 반환하는 잘못된 로직이 있었습니다.+2. CSS의 `::text` 함수처럼 텍스트 콘텐츠를 선택해 반환하려고 `.css`나 `.xpath` 같은 메서드를 사용하면, 이제 `Adaptor` 객체가 `TextHandlers` 클래스를 반환합니다. 이전처럼 문자열 리스트를 반환하지 않습니다. 따라서 이제 `page.css('something::text').re_first(r'regex_pattern').json()`을 사용할 수 있으며, 기존의 `page.css('something::text')[0].re_first(r'regex_pattern').json()`은 필요하지 않습니다.+3. 이제 `Adaptor`/`Adaptors`의 re/re_first 인수가 `TextHandler`와 일치합니다. `clean_match`와 `case_sensitive` 인수를 사용할 수 있습니다.+4. 이제 `auto_match` 인수는 `Adaptor`를 초기화할 때 기본적으로 켜집니다. 하지만 요소를 선택할 때도 이 기능을 따로 켜야 사용할 수 있습니다. 버그가 아닌 설계상의 결정입니다.+5. Scrapling으로 코드를 작성할 때 자동 완성을 더 편하게 쓸 수 있도록 여러 타입 표기를 수정했습니다.++##### 사용 편의 개선 {#v0.2-quality-of-life-changes}+1. `css_selector`와 `xpath_selector` 메서드의 이름을 `generate_css_selector`와 `generate_xpath_selector`로 바꿨습니다. 의미를 명확하게 하고 코드 작성 중 자동 완성을 방해하지 않도록 했습니다.+2. 기존 코드 대부분을 `core` 하위 패키지로 옮기고 다른 설계도 바꿔 앞으로 더 깔끔하고 쉽게 유지보수할 수 있게 했습니다.+3. 테스트 폴더를 더 깔끔하게 구성하고 새 기능의 테스트를 추가했습니다. 이제 GitHub에서 tox 환경을 캐시하므로 커밋마다 실행하는 자동 테스트가 더 빨라집니다.++## [v0.1.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.2) - 2024-10-16 {#v0.1.2}++**변경 기록**:++- `keep_comments` 인수가 의도대로 작동하지 않던 버그를 수정했습니다.+- Lxml 특유의 동작을 피하도록 텍스트 함수를 수정했습니다. 이제 텍스트를 추출하기 전에 요소의 HTML 주석을 자동으로 제거합니다. 예를 들면 다음과 같습니다.++ ```python+ >>> page = Adaptor('<span>CONDITION: <!-- -->Excellent</span>', keep_comments=True)+ >>> page.css('span::text')+ ['CONDITION: ', 'Excellent']+ ```++ 이전에는 Lxml의 기본 동작 때문에 위와 같은 결과가 나왔지만, 이제는 전체 텍스트 'CONDITION: Excellent'를 반환합니다.+ parsel\scrapy에서도 알려진 동작이라 여기서 처리하고자 했습니다.++- `pip uninstall scrapling` 같은 명령을 실행해도 라이브러리가 만든 SQLite DB 파일이 삭제되지 않던 버그를 수정했습니다.++## [v0.1.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.1) - 2024-10-14 {#v0.1.1}++작은 수정 사항++## [v0.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1) - 2024-10-13 {#v0.1}++**전체 변경 기록**: <https://github.com/D4Vinci/Scrapling/commits/v0.1>diff --git a/docs/locales/pt-BR/changelog.md b/docs/locales/pt-BR/changelog.mdnew file mode 100644index 0000000..b828af1--- /dev/null+++ b/docs/locales/pt-BR/changelog.md@@ -0,0 +1,1279 @@+---+title: "Histórico de mudanças do Scrapling"+description: "Notas das versões do Scrapling, com novos recursos, correções e mudanças incompatíveis."+---++# Histórico de mudanças {#changelog}++Todas as mudanças importantes do Scrapling, extraídas das [versões no GitHub](https://github.com/D4Vinci/Scrapling/releases).++## [v0.4.15](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.15) - 2026-08-23 {#v0.4.15}++**Uma das maiores versões deste ano: um servidor MCP reformulado, Markdown pronto para RAG em uma linha, um solucionador de Cloudflare melhorado e abas do navegador que continuam abertas para automação 🚀**++!!! warning "Aviso"++ **Esta versão traz mudanças incompatíveis no servidor MCP. Confira a seção de [mudanças incompatíveis](https://github.com/D4Vinci/Scrapling/blob/v0.4.15/docs/ai/mcp-server.md#breaking-changes) antes de atualizar.**++### 🚀 Novidades e melhorias de uso {#v0.4.15-new-stuff-and-quality-of-life-changes}++- **As abas do navegador agora continuam abertas e são reutilizadas entre solicitações** (confira a [documentação](fetching/stealthy.md#session-management)):+ - Todas as sessões do navegador mantêm suas abas após uma solicitação, e a próxima reutiliza uma aba livre em vez de abrir outra.+ - Cada solicitação reaplica suas próprias configurações (tempos limite, cabeçalhos e bloqueio de recursos) à aba que recebe, para que as configurações não passem de uma solicitação para outra.+ - As abas que apresentam erro são fechadas e substituídas, e o novo método `close_pages()` fecha todas as abas abertas.+ - A página que você buscou continua carregada, então uma função `page_setup` na próxima solicitação é executada nela antes de navegar para outra página. Isso permite encadear etapas de automação entre solicitações.++- **Transforme qualquer página em Markdown limpo e pronto para LLMs com `Response.markdown()`** (confira a [documentação](ai/building-rag-systems.md)):++ ```python+ from scrapling.fetchers import Fetcher++ markdown = Fetcher.get("https://example.com").markdown(main_content_only=True)+ ```++ - Scripts, estilos e conteúdo oculto de injeção de prompts são sempre removidos primeiro, com a mesma limpeza que o servidor MCP faz.+ - Passe `css_selector` para converter apenas os elementos de que você precisa.+ - Disponível pelo novo extra `rag` (`pip install "scrapling[rag]"`), também incluído nos extras `ai`/`shell`/`all`.++- **Novo modelo `SiteToMarkdownSpider` para rastrear um site inteiro e criar uma coleção de documentos Markdown para pipelines de RAG** (confira a [documentação](ai/building-rag-systems.md)):++ ```python+ from scrapling.spiders import SiteToMarkdownSpider++ class DocsSpider(SiteToMarkdownSpider):+ name = "docs"+ start_urls = ["https://example.com/docs/"]+ allowed_domains = {"example.com"}+ output_dir = "docs_markdown"++ result = DocsSpider().start()+ result.items.to_jsonl("docs.jsonl")+ ```++ - Produz um item por página com `url`/`title`/`markdown`, e o parâmetro opcional `output_dir` grava um arquivo Markdown por página.+ - `max_pages` limita o rastreamento e, como o modelo se baseia em `CrawlSpider`, redefinir `rules()` dá a você controle total sobre quais links são seguidos.++- **O servidor MCP foi reformulado (mudança incompatível)** (confira as [mudanças incompatíveis](https://github.com/D4Vinci/Scrapling/blob/v0.4.15/docs/ai/mcp-server.md#breaking-changes) e a [documentação](ai/mcp-server.md)):+ - As 13 ferramentas agora se dividem em dois modos: ferramentas de execução única (`fetch`, `bulk_fetch`, `stealthy_fetch`, `bulk_stealthy_fetch`), que sempre iniciam seu próprio navegador e mostram seus valores padrão reais, e ferramentas de sessão, que usam uma sessão aberta uma única vez.+ - A nova ferramenta `session_fetch` busca páginas por uma sessão do navegador, enquanto `open_session` agora guarda apenas as configurações do navegador e retorna as configurações efetivas da sessão para o agente de IA.+ - A ferramenta `get` passou a se chamar `make_request` e agora aceita qualquer método HTTP.+ - As novas ferramentas `open_request_session` e `session_make_request` dão à IA sessões HTTP persistentes que mantêm cookies e a impressão digital do navegador entre solicitações.+ - Isso também impede que as buscas redefinam as configurações da sessão, um problema corrigido primeiro por @Yigtwxx em [#418](https://github.com/D4Vinci/Scrapling/pull/418).++- **O transporte HTTP do servidor MCP agora exige autenticação e escuta em localhost por padrão (mudança incompatível)**, por @yamantaka-singh em [#414](https://github.com/D4Vinci/Scrapling/pull/414) (corrige [#413](https://github.com/D4Vinci/Scrapling/issues/413); confira a [documentação](ai/mcp-server.md#authentication)):+ - Passe `--auth-token` (ou a variável de ambiente `SCRAPLING_MCP_AUTH_TOKEN`) para exigir um token bearer, ou `--no-auth` se quiser disponibilizar o servidor sem autenticação de forma explícita.+ - Passe `--host 0.0.0.0` para aceitar conexões da rede.++### 🐛 Correções de erros {#v0.4.15-bug-fixes}++- **A resolução de Cloudflare Turnstile/Interstitial agora funciona independentemente do idioma e da região do navegador e não entra mais em um loop infinito em desafios interativos no modo sem interface**. As páginas do navegador com recursos de ocultação também deixam de falhar durante a resolução, com contribuições de @subediparas5 em [#412](https://github.com/D4Vinci/Scrapling/pull/412). (Corrige [#411](https://github.com/D4Vinci/Scrapling/issues/411) e [#422](https://github.com/D4Vinci/Scrapling/issues/422))+- **Corrigido o problema em que `find`/`find_all` com `class_` ignoravam sem aviso elementos com várias classes**, por @yetval em [#410](https://github.com/D4Vinci/Scrapling/pull/410), **e os valores vazios de `class_` e as strings CSS sem escape**, por @yamantaka-singh em [#417](https://github.com/D4Vinci/Scrapling/pull/417).+- **Corrigida a perda dos metadados da solicitação ao reutilizar respostas em cache no `development_mode`**, por @Yigtwxx em [#419](https://github.com/D4Vinci/Scrapling/pull/419).+- **Corrigidas as solicitações HTTP com `retries` abaixo de 1 que falhavam sem enviar a solicitação**, por @Yigtwxx em [#420](https://github.com/D4Vinci/Scrapling/pull/420).++### Documentação {#v0.4.15-docs}++- **As seções do site foram reorganizadas**: a nova seção "Uso com IA" reúne o servidor MCP, a nova página de [skill para agentes](ai/agent-skill.md) e o guia para [criar sistemas RAG](ai/building-rag-systems.md). O guia de migração do BeautifulSoup foi movido para junto da integração com Scrapy em "Integrações e migrações".+- **Adicionado um [histórico de mudanças](changelog.md)** ao repositório com as notas de todas as versões lançadas até agora.++## [v0.4.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.14) - 2026-08-10 {#v0.4.14}++**Uma versão rápida de manutenção para corrigir a instalação com `uv` 🔧**++### 🐛 Correções de erros {#v0.4.14-bug-fixes}++- **Corrigido o problema em que `uv` se recusava a instalar v0.4.13 por padrão e usava uma versão antiga sem aviso**. A versão anterior exigia uma versão preliminar de `curl_cffi`, o que `uv` não permite sem ativação explícita.+Todas as dependências agora são resolvidas com versões estáveis. (Corrige [#407](https://github.com/D4Vinci/Scrapling/issues/407))++## [v0.4.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.13) - 2026-08-09 {#v0.4.13}++**Uma nova atualização com spiders para feeds e um servidor MCP mais inteligente 🎉**++### 🚀 Novidades e melhorias de uso {#v0.4.13-new-stuff-and-quality-of-life-changes}++- **Novos modelos de spiders para feeds**. `XMLFeedSpider` percorre os nós de qualquer feed XML (RSS, Atom, feeds de produtos etc.), e `CSVFeedSpider` percorre as linhas CSV como dicionários. Ambos descompactam automaticamente os feeds comprimidos com gzip. (Confira a [documentação](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import XMLFeedSpider++ class RSSSpider(XMLFeedSpider):+ name = "rss"+ start_urls = ["https://example.com/feed.xml"]++ async def parse_node(self, response, node):+ yield {"title": node.findtext("title"), "link": node.findtext("link")}++ result = RSSSpider().start()+ ```++- **O servidor MCP foi atualizado para MCP SDK v2 e ficou mais inteligente**. O servidor agora inclui instruções que ensinam seu agente de IA a usar as ferramentas de forma eficiente; cada ferramenta declara anotações para que clientes como Claude Code aprovem automaticamente as que apenas leem; as descrições das ferramentas estão mais curtas para economizar tokens; e o servidor informa sua versão e seu logotipo aos clientes MCP. (Confira a [documentação](ai/mcp-server.md))+- **Adicionado o comando `scrapling-mcp`**, que executa diretamente `scrapling mcp`, para registrar o Scrapling em clientes e registros MCP que esperam um único comando com apenas uma linha.+- **As versões do Playwright/Patchright e dos navegadores não são mais fixadas**. O User-Agent gerado agora sempre corresponde à versão exata do Chromium controlada pela instalação do Playwright/Patchright. Por isso, o Scrapling não fixa mais suas versões e você pode atualizá-las livremente. Execute `scrapling install --force` depois de atualizar para renovar os navegadores.++### 🐛 Correções de erros {#v0.4.13-bug-fixes}++- **Corrigida a falha ao importar o Scrapling com um ValueError do `browserforge`** quando o pacote de dados de impressões digitais fica atrás das versões dos navegadores. (Corrige [#394](https://github.com/D4Vinci/Scrapling/issues/394), [#396](https://github.com/D4Vinci/Scrapling/issues/396) e [#400](https://github.com/D4Vinci/Scrapling/issues/400))+- **Corrigido o tamanho incorreto dos pools de páginas nas ferramentas de navegador em lote do MCP**, que fazia `bulk_fetch` falhar com lotes de mais de 50 URLs e `bulk_stealthy_fetch` buscar todas as URLs em uma única aba, por @Yigtwxx em [#393](https://github.com/D4Vinci/Scrapling/pull/393).++### Projeto {#v0.4.13-project}++- **Nova [política de contribuições com IA](https://github.com/D4Vinci/Scrapling/blob/main/AI_POLICY.md)**: contribuições com ajuda de IA são bem-vindas, mas isso deve ser informado no PR ou na issue; envios que parecem gerados por IA sem informar isso recebem uma etiqueta e são fechados.++## [v0.4.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.12) - 2026-07-26 {#v0.4.12}++**Uma versão focada em tornar seus spiders mais inteligentes ao lidar com os sites que rastreiam**++### 🚀 Novidades e melhorias de uso {#v0.4.12-new-stuff-and-quality-of-life-changes}++- **Os spiders agora podem ajustar a própria velocidade com AutoThrottle.** Em vez de tentar adivinhar um `download_delay` que pode ser lento demais ou causar bloqueios, o spider mede a velocidade de resposta de cada site e ajusta a espera de cada domínio sozinho. Quando um site começa a bloquear você ou limitar suas solicitações, ele dobra a espera (ou aguarda exatamente o tempo indicado pelo cabeçalho `Retry-After`) até isso parar, e depois volta a acelerar. Seu `download_delay` e qualquer `Crawl-delay` de robots.txt continuam sendo o mínimo. (Confira a [documentação](spiders/advanced.md#autothrottle))++ ```python+ class MySpider(Spider):+ name = "adaptive"+ start_urls = ["https://example.com"]+ autothrottle_enabled = True+ autothrottle_start_delay = 2.0+ autothrottle_max_delay = 30.0+ autothrottle_block_backoff = True+ ```++- **Exporte seus resultados para CSV e XML**, além dos exportadores JSON/JSONL que você já tinha. Itens que não compartilham todas as chaves continuam sendo exportados sem perda de dados, e os valores aninhados são gravados como JSON. (Confira a [documentação](spiders/getting-started.md))++ ```python+ result = MySpider().start()+ result.items.to_csv("products.csv")+ result.items.to_xml("products.xml")+ ```++- **O servidor MCP agora pode exigir autenticação**, para que você possa disponibilizá-lo com segurança em vez de mantê-lo apenas no seu computador. Qualquer solicitação sem o token é rejeitada, e você também pode limitar os nomes de host aos quais o servidor responde. (Confira a [documentação](ai/mcp-server.md))++ ```bash+ scrapling mcp --http --auth-token "$(openssl rand -hex 32)"+ ```++- **Os navegadores agora aceitam URLs de CDP por HTTP**, além das de WebSocket. Assim, além dos endpoints `wss://` oferecidos pelos provedores de navegadores gerenciados, você pode conectar qualquer fetcher de navegador ou sessão MCP a um Chrome que iniciou com `--remote-debugging-port=9222`.++- **As imagens Docker publicadas agora recebem uma tag com sua versão**, em vez de apenas `latest`, para que você possa fixar a versão exata que quiser, por @JanRK em [#384](https://github.com/D4Vinci/Scrapling/pull/384).++### 🐛 Correções de erros {#v0.4.12-bug-fixes}++- **Corrigida a perda de todos os cookies nas respostas em cache** quando vinham de um motor de navegador, o que quebrava sem aviso a lógica de sessão ou autenticação que dependia deles no modo de desenvolvimento dos spiders, por @amitvijapur em [#379](https://github.com/D4Vinci/Scrapling/pull/379). (Corrige [#376](https://github.com/D4Vinci/Scrapling/issues/376))++- **Corrigido o problema em que `StealthyFetcher` impunha a configuração regional `en-US`** a todos os navegadores, em vez de seguir a do sistema. Isso fazia os sites perceberem uma diferença entre a configuração regional e o endereço IP e tratarem você como suspeito, como nas respostas 429 do Google. (Corrige [#381](https://github.com/D4Vinci/Scrapling/issues/381))++- **Corrigida uma mensagem de erro enganosa no sistema de armazenamento** e removida uma chamada sem uso que restava após as inserções, por @fix2015 em [#377](https://github.com/D4Vinci/Scrapling/pull/377).++### Desempenho {#v0.4.12-performance}++- **O tempo de execução de `get_all_text()` agora cresce em proporção ao número de nós, O(nodes)** em vez de percorrer os ancestrais de cada nó de texto, o que o torna cerca de 5-6 vezes mais rápido em páginas com muitos níveis aninhados, por @yetval em [#378](https://github.com/D4Vinci/Scrapling/pull/378).++## [v0.4.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.11) - 2026-07-12 {#v0.4.11}++**Uma atualização importante com o primeiro modelo de spider para uma plataforma, um parser mais rápido e correções importantes 🎉**++### 🚀 Novidades e melhorias de uso {#v0.4.11-new-stuff-and-quality-of-life-changes}++- **Adicionado `ShopifySpider`, o primeiro modelo de spider para uma plataforma!** Extraia todos os produtos de qualquer loja Shopify pela API JSON, sem usar o HTML do site. Crie uma subclasse, defina o domínio da loja e pronto (confira a [documentação](spiders/platform-templates.md))++ ```python+ from scrapling.spiders import ShopifySpider++ class MyStore(ShopifySpider):+ target_website = "example.com"++ result = MyStore().start()+ ```++- **Adicionado `--executable-path` aos comandos de navegador da CLI**. Tanto `scrapling extract fetch` quanto `scrapling extract stealthy-fetch` agora aceitam um executável de navegador personalizado compatível com Chromium e usam a variável de ambiente `SCRAPLING_EXECUTABLE_PATH` quando você não passa a opção. Assim, oferecem o mesmo recurso do servidor MCP (resolve [#371](https://github.com/D4Vinci/Scrapling/issues/371))++ ```bash+ scrapling extract fetch "https://example.com" page.html --executable-path "/path/to/chromium"+ ```++### 🤖 Melhorias de uso {#v0.4.11-quality-of-life-changes}+- **`find_by_text` e `find_by_regex` ficaram até cerca de 2 vezes mais rápidos** quando `first_match` está ativado (padrão), porque os elementos são convertidos em objetos apenas quando necessário, para que a busca pare na primeira correspondência, por @yetval em [#370](https://github.com/D4Vinci/Scrapling/pull/370)+- **Atualizados os benchmarks com os novos números em comparação com as versões mais recentes de todas as bibliotecas.**+- **Atualizadas as regras de contribuição**++### 🐛 Correções de erros {#v0.4.11-bug-fixes}++- **Corrigidas as falhas das ferramentas de obtenção de páginas do servidor MCP em páginas com caracteres de controle**, que causavam o erro `All strings must be XML compatible`, por @yetval em [#368](https://github.com/D4Vinci/Scrapling/pull/368) (corrige [#366](https://github.com/D4Vinci/Scrapling/issues/366))++## [v0.4.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.10) - 2026-07-04 {#v0.4.10}++**Uma nova atualização com uma nova integração com Scrapy e várias correções da comunidade 🎉**++### 🚀 Novidades e melhorias de uso {#v0.4.10-new-stuff-and-quality-of-life-changes}++- **Adicionada uma integração com Scrapy** para usar a API de parsing do Scrapling nos seus projetos Scrapy existentes sem reescrevê-los. Aplique o decorador `scrapling_response` a qualquer callback de um spider, e a resposta que ele recebe vira uma `Response` do Scrapling, enquanto o Scrapy continua cuidando do rastreamento (confira a [documentação](integrations/scrapy.md)):++ ```python+ import scrapy+ from scrapling.integrations.scrapy import scrapling_response++ class QuotesSpider(scrapy.Spider):+ name = "quotes"+ start_urls = ["https://quotes.toscrape.com"]++ @scrapling_response+ def parse(self, response): # `response` is now a Scrapling Response+ first_quote = response.find_by_text("The world as we have created it", partial=True)+ for quote in [first_quote, *first_quote.find_similar()]:+ yield {"text": quote.get_all_text(strip=True)}+ ```++- **O servidor MCP agora pode usar um navegador personalizado compatível com Chromium** em todas as ferramentas baseadas em navegador. Defina-o uma vez com `scrapling mcp --executable-path "/path/to/chromium"` ou com a variável de ambiente `SCRAPLING_EXECUTABLE_PATH`, ou por solicitação com o argumento `executable_path`, por @samrusani em [#360](https://github.com/D4Vinci/Scrapling/pull/360) (resolve [#347](https://github.com/D4Vinci/Scrapling/issues/347))+- **Atualizados todos os navegadores e impressões digitais**. Execute `scrapling install --force` depois de atualizar para renová-los.++### 🐛 Correções de erros {#v0.4.10-bug-fixes}++- **Corrigido o texto ilegível (mojibake) dos fetchers de navegador em sites que não usam UTF-8**, por @yehudalevy-collab em [#365](https://github.com/D4Vinci/Scrapling/pull/365) (corrige [#364](https://github.com/D4Vinci/Scrapling/issues/364)).+- **Corrigido o problema em que `LinkExtractor` não filtrava extensões de arquivo compostas, como `.tar.gz`**, por @renbkna em [#359](https://github.com/D4Vinci/Scrapling/pull/359) (corrige [#349](https://github.com/D4Vinci/Scrapling/issues/349)).+- **Corrigida a perda de solicitações em andamento nos checkpoints de rastreamentos pausados, para que não sejam mais ignoradas ao retomar**, por @yetval em [#358](https://github.com/D4Vinci/Scrapling/pull/358).+- **Corrigido o cálculo incorreto das esperas de rastreamento a partir das diretivas `Request-rate` de robots.txt** com a atualização do Protego e testes ajustados por @Disaster-Terminator em [#355](https://github.com/D4Vinci/Scrapling/pull/355).++### Documentação {#v0.4.10-docs}++- **Esclarecida a interação de `init_script` com o contexto de execução isolado do Patchright no modo de ocultação**, por @mturac em [#353](https://github.com/D4Vinci/Scrapling/pull/353) (resolve [#350](https://github.com/D4Vinci/Scrapling/issues/350)).+- **Adicionado o método de instalação da skill para agentes pelo [skills.sh](https://skills.sh/D4Vinci/Scrapling)**, por @ob-aion em [#363](https://github.com/D4Vinci/Scrapling/pull/363).++## [v0.4.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.9) - 2026-06-07 {#v0.4.9}++**Uma atualização de manutenção cheia de correções de problemas relatados pela comunidade 🛠️**++### 🚀 Novidades e melhorias de uso {#v0.4.9-new-stuff-and-quality-of-life-changes}++- **Atualizados todos os navegadores e impressões digitais**. Execute `scrapling install --force` depois de atualizar para renová-los.+- **Adicionada a opção `--version` à CLI**, por @ETM-Code em [#303](https://github.com/D4Vinci/Scrapling/pull/303) (resolve [#299](https://github.com/D4Vinci/Scrapling/issues/299))++### 🐛 Correções de erros {#v0.4.9-bug-fixes}++- **Corrigido o problema em que o argumento `proxy` da sessão era ignorado sem aviso nas sessões HTTP**, o que podia expor seu IP real (resolve [#295](https://github.com/D4Vinci/Scrapling/issues/295)). Combinar um `proxy` da sessão com um argumento `proxies` por solicitação (ou o contrário) agora gera um erro, em vez de ignorar um deles sem aviso.+- **Corrigidas as falhas de navegação ao combinar `init_script` com `user_data_dir`** (resolve [#294](https://github.com/D4Vinci/Scrapling/issues/294)).+- **Corrigida a detecção de codificação quando os sites colocam o valor charset entre aspas no cabeçalho `Content-Type`**, por @Bortlesboat em [#323](https://github.com/D4Vinci/Scrapling/pull/323).+- **Corrigido um `IndexError` na realocação adaptativa de elementos quando `auto_save` está ativado**, por @Mubashirrrr em [#340](https://github.com/D4Vinci/Scrapling/pull/340).+- **Corrigidas as falhas ao salvar checkpoints e o cache dos spiders no Windows**, por @MrStarkEG em [#344](https://github.com/D4Vinci/Scrapling/pull/344).+- **Corrigido o cálculo de similaridade em `find_similar` para elementos com quantidades diferentes de atributos** (resolve [#322](https://github.com/D4Vinci/Scrapling/issues/322)).++### Documentação {#v0.4.9-docs}++- **Esclarecido que a instalação padrão inclui apenas o motor de parsing**, e que os fetchers e spiders precisam dos extras (resolve [#343](https://github.com/D4Vinci/Scrapling/issues/343)).+- **Corrigido o nome da imagem Docker nos exemplos restantes**, por @evanclan em [#315](https://github.com/D4Vinci/Scrapling/pull/315).+- **Corrigido um link quebrado no guia de contribuição**, por @Bortlesboat em [#320](https://github.com/D4Vinci/Scrapling/pull/320).++## [v0.4.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.8) - 2026-05-11 {#v0.4.8}++**Uma grande atualização dos spiders que melhora o sistema de rastreamento 🕷️**++### 🚀 Novidades e melhorias de uso {#v0.4.8-new-stuff-and-quality-of-life-changes}++- **Adicionada a ferramenta `LinkExtractor`** em `scrapling.spiders.LinkExtractor` para extrair URLs de uma `Response`. Ela oferece muitos controles (confira a [documentação](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import LinkExtractor++ extractor = LinkExtractor(allow=r"/posts/", deny_domains=["ads.example.com"])+ ```++- **Adicionados os modelos genéricos de spider `CrawlSpider` e `CrawlRule`** para que você não precise escrever sempre o mesmo código de "seguir links que correspondem a este padrão". Redefina `rules()` para retornar uma lista de objetos `CrawlRule`, cada um associado a um `LinkExtractor`. (Confira a [documentação](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import CrawlSpider, CrawlRule, LinkExtractor++ class QuotesSpider(CrawlSpider):+ name = "blog"+ start_urls = ["https://quotes.toscrape.com/"]++ def rules(self):+ return [+ CrawlRule(LinkExtractor(allow=r"/author/"), callback=self.parse_author),+ CrawlRule(LinkExtractor(allow=r"/page/\d+/")), # pagination, no callback+ ]++ async def parse_author(self, response):+ yield {+ "name": response.css(".author-title::text").get(),+ "birthday": response.css(".author-born-date::text").get(),+ "url": response.url,+ }+ ```++- **Adicionado um modelo `SitemapSpider`** que inicia o rastreamento diretamente de um sitemap ou de URLs de `robots.txt`. Ele aceita sitemaps compactados com gzip e oferece muitos controles e opções. As URLs são encaminhadas pelas regras de rastreamento, como no exemplo de **CrawlSpider** acima. (Confira a [documentação](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import SitemapSpider, CrawlRule, LinkExtractor++ class NewsSitemap(SitemapSpider):+ name = "news"+ sitemap_urls = ["https://example.com/robots.txt"]++ def rules(self):+ return [+ CrawlRule(LinkExtractor(allow=r"/articles/"), callback=self.parse_article),+ ]++ async def parse_article(self, response):+ yield {"url": response.url, "title": response.css("h1::text").get()}+ ```++- **A realocação adaptativa agora usa um limite padrão de similaridade de 40%**, em vez de `0`, em todos os métodos. Isso melhora o funcionamento do recurso adaptativo. Quando nenhum elemento supera o limite, um aviso mostra a maior pontuação encontrada, para que você possa reduzir `percentage` de forma consciente, se necessário.++- **Atualizados todos os navegadores e impressões digitais**. Execute novamente `scrapling install --force` depois de atualizar para renovar os navegadores e impressões digitais.++### 🐛 Correções de erros {#v0.4.8-bug-fixes}++- **Corrigido o problema em que `Fetcher.configure(...)` não era aplicado às chamadas por solicitação**. A mesma correção foi aplicada a `AsyncFetcher`.+- **Corrigido o cálculo incorreto de impressões digitais das solicitações que causava solicitações duplicadas nos spiders**, por @yetval em [#255](https://github.com/D4Vinci/Scrapling/pull/255).+- **Corrigida a falta de aviso do motor de extração adaptativa em correspondências fracas.** Junto com a mudança de limite acima, agora você recebe um aviso em vez de um elemento enganoso como "melhor palpite" quando a realocação falha.++### Documentação {#v0.4.8-docs}++- **Atualizados os exemplos de código antigos** da documentação para corresponder à versão atual.+- **Melhorada a experiência de copiar e colar código** no site de documentação e reduzida a skill para agentes para usar menos tokens por chamada.++## [v0.4.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.7) - 2026-04-17 {#v0.4.7}++**Uma atualização focada em dar visão aos seus agentes de IA 📸**++### 🚀 Novidades e melhorias de uso {#v0.4.7-new-stuff-and-quality-of-life-changes}++- **Adicionada a ferramenta MCP `screenshot`**, que captura uma página e a retorna como um bloco MCP real de tipo `ImageContent`, para que o modelo possa vê-la. A ferramenta exige uma sessão de navegador aberta: chame `open_session` primeiro (com `dynamic` ou `stealthy`) e passe o `session_id` aqui. Aceita PNG e JPEG, capturas da página inteira, qualidade JPEG e os controles habituais de espera (`wait`, `wait_selector`, `network_idle`, `timeout`). (Implementa [#244](https://github.com/D4Vinci/Scrapling/issues/244))+- **Adicionado um parâmetro `session_id` personalizado a `open_session`** para dar nomes úteis às sessões (`"search"`, `"checkout"`), em vez do padrão hexadecimal aleatório de 12 caracteres. Por @hauntedhost em [#243](https://github.com/D4Vinci/Scrapling/pull/243)++### 🐛 Correções de erros {#v0.4.7-bug-fixes}++- **Corrigida a corrupção do estado de `FetcherSession` e uma falha ao fechar uma sessão com inicialização adiada**. Por @yetval em [#245](https://github.com/D4Vinci/Scrapling/pull/245)+- **Corrigido `TypeError: Session.request() got an unexpected keyword argument 'block_ads'`** ao usar a opção `--ai-targeted` da CLI com comandos HTTP. Por @voidborne-d em [#249](https://github.com/D4Vinci/Scrapling/pull/249) (corrige [#247](https://github.com/D4Vinci/Scrapling/issues/247))++### Traduções {#v0.4.7-translations}++- **Adicionada uma tradução do README para português brasileiro**, por @rgomids em [#250](https://github.com/D4Vinci/Scrapling/pull/250)++## [v0.4.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.6) - 2026-04-13 {#v0.4.6}++**Uma atualização focada no modo de ocultação do navegador, na privacidade e na experiência de desenvolvimento 🔒**++### 🚀 Novidades e melhorias de uso {#v0.4.6-new-stuff-and-quality-of-life-changes}++- **Adicionado bloqueio de anúncios integrado** para os fetchers de navegador. Passe `block_ads=True` para bloquear solicitações a cerca de 3.500 domínios conhecidos de anúncios e rastreadores ao interceptar a rota: sem DNS, sem TCP e com cancelamento imediato. Você pode combinar com `blocked_domains` para usar listas próprias. O servidor MCP e o modo `--ai-targeted` da CLI ativam isso automaticamente para economizar tokens e acelerar o carregamento das páginas.++ ```python+ page = StealthyFetcher.fetch('https://example.com', block_ads=True)+ ```++- **Adicionado suporte a DNS-over-HTTPS** para evitar vazamentos de DNS ao usar proxies. Passe `dns_over_https=True` para direcionar as consultas DNS ao serviço DoH da Cloudflare, evitando que a resolução DNS exponha sua localização real mesmo quando o tráfego HTTP passa por um proxy.++ ```python+ page = StealthyFetcher.fetch('https://example.com', proxy='http://proxy:8080', dns_over_https=True)+ ```++- **Adicionado o callback `page_setup`** para os fetchers de navegador. É uma função executada antes de `page.goto()`, que permite registrar listeners de eventos, rotas ou scripts que precisam ser preparados antes da navegação. Funciona junto com `page_action` (executado após a navegação). (Resolve [#237](https://github.com/D4Vinci/Scrapling/issues/237))++ ```python+ def capture_websockets(page):+ page.on("websocket", lambda ws: print(f"WS: {ws.url}"))++ page = DynamicFetcher.fetch('https://example.com', page_setup=capture_websockets)+ ```++- **Adicionadas as opções de CLI `--block-ads` e `--dns-over-https`** aos comandos `fetch` e `stealthy-fetch`.++### 🐛 Correções de erros {#v0.4.6-bug-fixes}++- **Corrigido o alias de tipo `Seconds`**, que rejeitava valores decimais. Passar `wait=1.5` ou `timeout=500.0` aos fetchers de navegador falhava com um erro de tipo porque o alias tratava `float` como metadados em vez de um tipo. Por @kuishou68 em [#240](https://github.com/D4Vinci/Scrapling/pull/240)+- **Corrigidos os segmentos ID duplicados na geração de seletores com caminho completo**. O seletor dos elementos com atributos `id` era adicionado duas vezes ao gerar caminhos CSS/XPath completos, produzindo seletores como `body > #main > #main > #target > #target`. Também foi corrigida a geração de condições `[@id='x']` isoladas (XPath inválido) em vez de `*[@id='x']` nos caminhos XPath completos. Por @sjhddh em [#241](https://github.com/D4Vinci/Scrapling/pull/241)+- **Corrigidos os parâmetros que faltavam nas assinaturas do shell**. As assinaturas das funções do shell interativo não incluíam `blocked_domains`, `block_ads`, `retries`, `retry_delay`, `capture_xhr`, `executable_path` e `dns_over_https`.++## [v0.4.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.5) - 2026-04-07 {#v0.4.5}++**Uma atualização com uma grande melhoria de uso para quem desenvolve spiders e algumas correções importantes 🎉**++### 🚀 Novidades e melhorias de uso {#v0.4.5-new-stuff-and-quality-of-life-changes}++- **Modo de desenvolvimento dos spiders**: testar mudanças na lógica de `parse()` de um spider antes exigia acessar os servidores do site de novo a cada execução. Isso é lento, gera tráfego e pode causar limites de solicitações enquanto você ainda ajusta os seletores. O novo modo de desenvolvimento salva cada resposta em disco na primeira execução e a reutiliza do disco nas seguintes. Assim, você pode ajustar os callbacks e executar quantas vezes quiser sem fazer nenhuma solicitação de rede. Ative com um atributo de classe:++ ```python+ class MySpider(Spider):+ name = "my_spider"+ start_urls = ["https://example.com"]+ development_mode = True++ async def parse(self, response):+ yield {"title": response.css("title::text").get("")}+ ```++ O cache fica em `.scrapling_cache/{spider.name}/` por padrão, e você pode mudar sua localização com `development_cache_dir`. Dois novos contadores, `cache_hits` e `cache_misses`, mostram o desempenho do cache. A reutilização do cache ignora `download_delay`, os limites de solicitações e o caminho de novas tentativas de solicitações bloqueadas, para que os testes sejam tão rápidos quanto o disco permitir. Não publique um spider com `development_mode = True`: é uma ferramenta de desenvolvimento, não um cache de produção. Confira a [documentação](spiders/advanced.md#development-mode) para todos os detalhes.++- **Redirecionamentos mais seguros por padrão**: o padrão de `follow_redirects` agora é `"safe"` em todos os fetchers HTTP, no servidor MCP e no shell. Os redirecionamentos continuam sendo seguidos, mas os que apontam para IPs internos ou privados (loopback, redes privadas e link-local) são rejeitados. Isso protege você contra SSRF ao extrair dados de URLs fornecidas por usuários. Passe `follow_redirects="all"` para recuperar o comportamento anterior, ou `False` para desativar todos os redirecionamentos.++### 🐛 Correções de erros {#v0.4.5-bug-fixes}++- **A parada forçada não perde mais seu checkpoint**: pressionar Ctrl+C duas vezes (parada forçada) em um spider com `crawldir` ativado podia coincidir com a gravação do checkpoint. O escopo de cancelamento encerrava a tarefa antes de terminar o pickle, deixava `paused=False` e acionava a limpeza que *exclui* o checkpoint anterior. Assim, interromper à força um rastreamento longo podia perder todo o progresso que você tentava salvar. O motor agora grava o checkpoint **antes** de chamar `cancel_scope.cancel()`, para que uma parada forçada sempre preserve o estado pendente mais recente. Por @voidborne-d em [#230](https://github.com/D4Vinci/Scrapling/pull/230).++## [v0.4.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.4) - 2026-04-05 {#v0.4.4}++**Uma nova atualização com melhorias importantes nos spiders e correções de erros 🎉**++### 🚀 Novidades e melhorias de uso {#v0.4.4-new-stuff-and-quality-of-life-changes}+- **Adicionado suporte ao cumprimento de robots.txt no sistema de spiders** com a nova opção `robots_txt_obey`. Quando ativada, o spider busca e respeita as regras de robots.txt automaticamente antes de rastrear, incluindo as diretivas `Disallow`, `Crawl-delay` e `Request-rate`. Os arquivos robots.txt são buscados de forma concorrente e mantidos em cache por domínio durante todo o rastreamento. Por @AbdullahY36 em [#226](https://github.com/D4Vinci/Scrapling/pull/226)+- **Adicionado o preenchimento prévio do cache de robots.txt**, para buscar e analisar os arquivos robots.txt de todos os domínios de start_urls antes de iniciar o loop de rastreamento, evitando atrasos na primeira solicitação a cada domínio.+- **Adicionada a nova estatística `robots_disallowed_count`** a `CrawlStats` para contar quantas solicitações foram bloqueadas pelas regras de robots.txt durante o rastreamento.++Confira no site [aqui](spiders/getting-started.md#robotstxt-compliance)++### 🐛 Correções de erros {#v0.4.4-bug-fixes}+- **Corrigido um problema importante de MRO com `ProxyRotator`**, no qual o método provisório `_build_context_with_proxy` ocultava a implementação real das classes filhas, fazendo a rotação de proxies sempre gerar `NotImplementedError` (corrige [#215](https://github.com/D4Vinci/Scrapling/issues/215)). Obrigado, @yetval+- **Corrigido um vazamento no pool de páginas** ao usar rotação de proxies por solicitação nas sessões do navegador. As páginas criadas em contextos temporários não eram removidas do pool na limpeza, acumulando referências antigas ao longo do tempo. Por @yetval em [#223](https://github.com/D4Vinci/Scrapling/pull/223)+- **Corrigida uma verificação de tipo ausente** no fetcher estático: `curl_cffi` podia retornar `None` de `session.request()`, causando erros depois.++### Outras mudanças {#v0.4.4-other}+- Atualizadas as dependências para incluir as impressões digitais mais recentes e outras novidades.+- Adicionado `protego` como nova dependência do grupo opcional `fetchers` para analisar robots.txt.++## [v0.4.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.3) - 2026-03-30 {#v0.4.3}++**Uma nova atualização com muitas mudanças importantes 🎉**++### 🚀 Novidades e melhorias de uso {#v0.4.3-new-stuff-and-quality-of-life-changes}+- **Adicionada uma nova ferramenta MCP** para abrir um navegador persistente, normal ou com recursos de ocultação, e continuar usando esse navegador com as outras ferramentas, além de outra ferramenta nova para fechá-lo. ([Exemplos](https://github.com/D4Vinci/Scrapling/blob/v0.4.3/docs/ai/mcp-server.md#examples))+- **Adicionada uma nova ferramenta MCP** para listar todas as sessões de navegador existentes, feita para usar com as novas ferramentas.+- **Adicionada uma nova opção às sessões do navegador** para coletar automaticamente todas as solicitações em segundo plano que ocorrem durante uma solicitação (resolve [#159](https://github.com/D4Vinci/Scrapling/pull/159)) [[Exemplos](https://github.com/D4Vinci/Scrapling/blob/v0.4.3/docs/fetching/dynamic.md#capturing-xhrfetch-requests)].+- **Adicionado um novo sanitizador** para proteger o servidor MCP de ataques comuns de injeção de prompts, removendo conteúdo oculto ou invisível.+- **Adicionada uma nova opção de linha de comando**, chamada `--ai-targeted`, aos comandos de extração web para preparar o conteúdo para IA e protegê-lo contra ataques comuns de injeção de prompts, como faz o servidor MCP.+- **Adicionada uma nova opção às sessões do navegador**, chamada `executable_path`, para definir um caminho de navegador personalizado (resolve [#202](https://github.com/D4Vinci/Scrapling/pull/202))+- **Reorganizado** o código do servidor MCP para facilitar a manutenção, e todas as ferramentas foram padronizadas como assíncronas.+- **Reorganizado** o código dos comandos da CLI para facilitar a manutenção e reduzi-lo em 210 linhas.++### 🐛 Correções de erros {#v0.4.3-bug-fixes}+- Correção para manter o método HTTP entre novas tentativas na sessão do spider, por @karesansui-u em [#201](https://github.com/D4Vinci/Scrapling/pull/201)+- Adicionado um limite máximo de tentativas de obter o conteúdo da página para evitar um loop infinito, por @haosenwang1018 e @D4Vinci em [#197](https://github.com/D4Vinci/Scrapling/pull/197)+- Substituído o `raise` sem argumento por `return False` em `_restore_from_checkpoint`, por @haosenwang1018 em [#196](https://github.com/D4Vinci/Scrapling/pull/196)+- Substituído `get_all` por `getall` em `Texthandler` para corresponder à classe Selector.++### Melhorias nos testes e na cobertura {#v0.4.3-coverage-tests-improvement}+- Adicionados testes de casos extremos de `_normalize_credentials`, por @Bortlesboat em [#192](https://github.com/D4Vinci/Scrapling/pull/192)+- Adicionados testes do ciclo de salvar e recuperar e do armazenamento principal, por @haosenwang1018 em [#193](https://github.com/D4Vinci/Scrapling/pull/193)+- Adicionada cobertura dos caminhos de regex de `TextHandler` e de `TextHandlers.re()`, por @haosenwang1018 em [#194](https://github.com/D4Vinci/Scrapling/pull/194)+- Adicionados testes de casos extremos de `filter`, `iterancestors` e `find_similar`, por @awanawana em [#200](https://github.com/D4Vinci/Scrapling/pull/200)++### Melhorias na skill para agentes {#v0.4.3-agent-skill-improvement}+- Corrigidos links Markdown quebrados nas referências da skill, por @yetval em [#204](https://github.com/D4Vinci/Scrapling/pull/204)+- Melhorada a estrutura da skill para passar melhor pela validação do [Clawhub](https://clawhub.ai/d4vinci/scrapling-official).+- A skill agora exige a opção de linha de comando `--ai-targeted` ao extrair dados por comandos.++### Melhorias na documentação {#v0.4.3-docs-improvement}+- Adicionada uma tradução do README para coreano, por @greatsk55 em [#187](https://github.com/D4Vinci/Scrapling/pull/187)+- Corrigidos os espaços entre caracteres CJK e latinos nos READMEs em chinês e japonês.+- Corrigidos links quebrados do design antigo do site.++## [v0.4.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.2) - 2026-03-08 {#v0.4.2}++**Uma nova atualização de manutenção com mudanças importantes**++#### Correções de erros {#v0.4.2-bug-fixes}+- A função `get_all_text()` agora também captura os nós de texto que vêm depois dos elementos. Assim, o servidor MCP e os comandos conseguem ler textos que antes eram ignorados ([#168](https://github.com/D4Vinci/Scrapling/pull/168)). Obrigado, @mhillebrand+- Referer agora retorna a URL base do Google em vez de uma URL de pesquisa do Google. A lógica anterior estava incorreta e podia gerar um sinal que ajudasse a identificar a impressão digital do navegador ([#179](https://github.com/D4Vinci/Scrapling/pull/179)). Obrigado, @Bortlesboat+- Corrigido um problema na junção de opções extras de inicialização em todos os navegadores. Obrigado, @rostchri+- Corrigido um problema nas anotações de tipos que causava falhas em versões do Python anteriores à 3.12. (Resolve [#163](https://github.com/D4Vinci/Scrapling/issues/163))++#### Outras mudanças {#v0.4.2-other}+- Adicionada uma Agent Skill para Claude Code / OpenClaw e outras ferramentas de agentes de IA.+- Adicionada a Agent Skill ao Clawhub.+- Todos os navegadores e o Playwright foram atualizados para as versões mais recentes.+- Adicionada uma tradução para francês do arquivo README principal.++## [v0.4.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.1) - 2026-02-27 {#v0.4.1}++**Uma nova atualização com muitas mudanças importantes**++### 🚀 Novidades e melhorias de uso {#v0.4.1-new-stuff-and-quality-of-life-changes}+- **Maior precisão das expressões regulares** na detecção de desafios do Cloudflare (Obrigado a @Rinz27 [#133](https://github.com/D4Vinci/Scrapling/pull/133))+- **Melhorias na velocidade e na eficiência** da resolução de desafios do Cloudflare. Agora ela é quase duas vezes mais rápida.+- **Melhorias na resolução de desafios do Cloudflare** para lidar com sites que às vezes mostram a página do Cloudflare duas vezes antes de redirecionar para o site principal.+- **Melhorias no modo de ocultação e na velocidade do navegador com recursos de ocultação** com a remoção dos arquivos JS injetados.+- **Melhorias no esquema MCP** para que seja aceito pelo OpenCode (Obrigado a @robin-ede [#137](https://github.com/D4Vinci/Scrapling/pull/137))+- **Maior compatibilidade do esquema MCP com o protocolo** para que seja aceito pelo VS Code Copilot e por outras ferramentas mais rigorosas. (Resolve #150 )+- **Grande redução no consumo de tokens do servidor MCP** com a remoção de tags HTML desnecessárias quando a opção `main_content_only` está ativada.+- Corrigida a página do PyPI e adicionados os arquivos necessários para cadastrar o servidor MCP no registro de servidores MCP.+- Adicionado um exemplo de código que mostra como instalar as dependências dos navegadores pelo código, em vez da linha de comando, para facilitar a automação.+- Todos os workflows foram melhorados com as versões mais recentes das actions (Obrigado a @salmanmkc [#143](https://github.com/D4Vinci/Scrapling/pull/143)/[#144](https://github.com/D4Vinci/Scrapling/pull/144))++## [v0.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4) - 2026-02-15 {#v0.4}++**A maior versão do Scrapling até agora: framework de spiders, rotação de proxies e grandes melhorias no parser**++Esta versão traz um framework de spiders e rastreamento totalmente assíncrono, gerenciamento inteligente de proxies e mudanças importantes na API que tornam o Scrapling mais poderoso e consistente. Leia com atenção a seção de mudanças incompatíveis antes de atualizar.++### 🕷️ Framework de spiders {#v0.4-spider-framework}++Um novo framework de rastreamento assíncrono baseado em `anyio` para extração de dados organizada e em grande escala:++```python+from scrapling.spiders import Spider, Response++class MySpider(Spider):+ name = "demo"+ start_urls = ["https://example.com/"]++ async def parse(self, response: Response):+ for item in response.css('.product'):+ yield {"title": item.css('h2::text').get()}++MySpider().start()+```++- **API de spiders semelhante à do Scrapy**: Defina spiders com `start_urls`, callbacks `parse` assíncronos, objetos `Request`/`Response` e uma fila de prioridades.+- **Rastreamento concorrente**: Limites de concorrência, controle da frequência por domínio e pausas entre downloads configuráveis.+- **Suporte a várias sessões**: Interface unificada para solicitações HTTP e navegadores sem interface gráfica com recursos de ocultação em um único spider. Direcione as solicitações para sessões diferentes pelo ID. Permite iniciar as sessões somente quando forem necessárias.+- **Pausar e retomar**: Salva o estado do rastreamento por meio de checkpoints. Pressione Ctrl+C para encerrar de forma organizada e reinicie para continuar de onde parou.+- **Modo streaming**: Receba os itens assim que forem extraídos por meio de `async for item in spider.stream()`, com estatísticas em tempo real. Ideal para interfaces, pipelines e rastreamentos longos.+- **Detecção de solicitações bloqueadas**: Detecta e repete automaticamente as solicitações bloqueadas, com lógica personalizável.+- **Exportação integrada**: Exporte os resultados por meio de hooks e do seu próprio pipeline, ou use a exportação integrada para JSON/JSONL com `result.items.to_json()` / `result.items.to_jsonl()`, respectivamente.+- **Hooks do ciclo de vida**: `on_start()`, `on_close()`, `on_error()`, `on_scraped_item()` e outros hooks para controlar todo o ciclo de vida do rastreamento.+- **Estatísticas detalhadas do rastreamento**: Acompanhe solicitações, respostas, bytes, códigos de status, proxies, detalhes por domínio e sessão, contagens por nível de log e muito mais.+- **Suporte a uvloop**: Passe `use_uvloop=True` para `spider.start()` para acelerar a execução assíncrona quando ele estiver disponível.++Uma nova seção foi adicionada ao site com todos os detalhes. Clique [aqui](spiders/architecture.md)++### 🔄 Rotação de proxies {#v0.4-proxy-rotation}++* Nova classe `ProxyRotator` com rotação segura entre threads. Funciona com todos os fetchers e sessões:++ ```python+ from scrapling import ProxyRotator+ rotator = ProxyRotator(["http://proxy1:8080", "http://proxy2:8080"])+ Fetcher.get(url, proxy_rotator=rotator)+ ```++* **Estratégias de rotação personalizadas**: Crie sua própria lógica de rotação de proxies+* **Troca de proxy por solicitação**: Passe `proxy=` para qualquer chamada individual a `get()`/`post()`/`fetch()` para substituir o proxy da sessão nessa solicitação.++### 🌐 Melhorias nos fetchers de navegador {#v0.4-browser-fetcher-improvements}++* **Bloqueio de domínios**: Novo parâmetro `blocked_domains` em `DynamicFetcher`/`StealthyFetcher` para bloquear solicitações a domínios específicos. Os subdomínios são incluídos automaticamente.+* **Novas tentativas automáticas**: Os fetchers de navegador agora repetem solicitações que falham com os parâmetros `retries` (padrão: 3) e `retry_delay` (padrão: 1s). Inclui detecção de erros relacionados a proxies.+* **Metadados da resposta**: O dicionário `Response.meta` salva automaticamente o proxy usado e incorpora os metadados da solicitação.+* **Response.follow()**: Crie objetos `Request` para solicitações seguintes com gerenciamento automático do referer, feitos para o sistema de spiders.+* **Sem reprodução automática**: As sessões de navegador agora bloqueiam conteúdo com reprodução automática, que antes causava problemas.+* **Velocidade**: Melhorias no modo de ocultação e na velocidade com ajustes nas opções de inicialização do navegador.++### 🔧 Correções de erros e melhorias {#v0.4-bug-fixes-improvements}+- **Otimização do parser**: O parser foi otimizado para operações repetidas, melhorando o desempenho.+- **Páginas com erros**: Corrigido um erro que impedia o fechamento do navegador quando as páginas retornavam erros.+- **Corpo vazio**: Tratamento de respostas com corpo vazio.+- **Loop do Playwright**: Resolvido um problema que deixava o loop do Playwright aberto quando a conexão CDP falhava+- **Segurança de tipos**: Corrigidos todos os erros do mypy e adicionadas anotações de tipos nos corpos de funções que não as tinham. Adicionados mypy e pyright ao workflow de CI.++### ⚠️ Mudanças incompatíveis {#v0.4-breaking-changes}++* **Remoção de `css_first`/`xpath_first`**: Use `css('.selector').first`, `css('.selector')[0]` ou `css('.selector').get()` no lugar deles.+* **Todas as seleções agora retornam `Selectors`**: `css('::text')`, `xpath('//text()')`, `css('::attr(href)')` e `xpath('//@href')` agora retornam `Selectors`, que envolve os nós de texto em objetos `Selector` com `tag="#text"`, em vez de `TextHandlers`. Isso torna a API consistente entre todos os métodos de seleção e as anotações de tipos.+* **`Response.body` é sempre `bytes`**: Antes podia ser `str` ou `bytes`; agora sempre retorna `bytes`.+* **Comportamento de `get()`/`getall()`**: Em `Selector`, `get()` retorna `TextHandler` (HTML serializado ou um valor de texto) e `getall()` retorna `TextHandlers`. Aliases: `extract_first = get`, `extract = getall`. O antigo `get_all()` de `Selectors` foi removido.+* **`Selectors.first`/`.last`**: Propriedades de acesso seguras que retornam `Selector | None` em vez de lançar `IndexError`.+* **Constantes internas renomeadas**: `DEFAULT_FLAGS` → `DEFAULT_ARGS`, `DEFAULT_STEALTH_FLAGS` → `STEALTH_ARGS`, `HARMFUL_DEFAULT_ARGS` → `HARMFUL_ARGS`, `DEFAULT_DISABLED_RESOURCES` → `EXTRA_RESOURCES`.++### 🔨 Outras mudanças {#v0.4-other-changes}++* **Mudanças nas dependências**: `tldextract` foi substituído por `tld`, o arquivo interno `_html_utils.py` foi removido em favor de `w3lib.html.replace_entities`, e `typing_extensions` passou a ser obrigatório.+* **Renovação da documentação**: Migração completa do MkDocs para o Zensical, nova seção sobre spiders, atualização de todas as páginas existentes e novas referências da API.++## [v0.3.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.14) - 2026-01-03 {#v0.3.14}++**Uma pequena atualização de manutenção para corrigir problemas que apareceram em alguns dispositivos na v0.3.13**++- O modo anônimo foi desativado em `StealthyFetcher` e suas classes de sessão porque impedia que os cookies fossem mantidos entre páginas no Windows. Isso não acontecia no MacOS nem no Linux (Corrige [#123](https://github.com/D4Vinci/Scrapling/issues/123); obrigado a @frugality4121 por relatar e a @gembleman por indicar a solução).+- A versão mais recente do browserforge foi fixada para resolver o problema com modelos de cabeçalhos antigos para quem já tinha uma versão antiga do browserforge.++## [v0.3.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.13) - 2026-01-01 {#v0.3.13}++**Uma grande atualização com melhorias em muitas partes, mas também com várias mudanças incompatíveis por bons motivos. Leia o texto abaixo antes de atualizar**++* Por vários motivos, decidimos parar completamente de usar o Camoufox a partir de agora. Podemos voltar a usá-lo no futuro se o desenvolvimento continuar. Se você prefere continuar usando o Camoufox como antes desta versão, veja as instruções nesta [seção](https://github.com/D4Vinci/Scrapling/blob/v0.3.13/docs/fetching/stealthy.md#using-camoufox-as-an-engine).++* Antes usávamos patchright no modo de ocultação de `DynamicFetcher` e suas classes de sessão. Agora removemos esse modo dessas classes e começamos a usar patchright em `StealthyFetcher` e suas classes de sessão, com MUITAS melhorias, como você verá, que reforçam o modo de ocultação além do que o patchright já oferece.++**Isso torna `StealthyFetcher` e suas classes de sessão 101% mais rápidos, com menor uso de memória e espaço e cerca de ~400 linhas de código a menos. O mais importante é que estão mais estáveis do que quando usávamos Camoufox.**++Isso também reduz o tempo de instalação do comando `scrapling install` e o tamanho da imagem Docker, melhora a execução dos testes no CI do GitHub e torna o scrapling menos confuso para novos usuários.++### Mudanças incompatíveis {#v0.3.13-breaking-changes}+1. O argumento `stealth` foi removido de `DynamicFetcher` e sua classe de sessão, enquanto `hide_canvas` foi movido para `StealthyFetcher` e suas classes de sessão.+2. O argumento `disable_webgl` foi movido de `DynamicFetcher` para a classe `StealthyFetcher` e renomeado para `allow_webgl`. O mesmo vale para todas as classes de sessão.+3. A classe `StealthyFetcher` agora é, basicamente, a nova versão com recursos de ocultação de `DynamicFetcher`. Por isso, foram removidos os argumentos `block_images`, `humanize`, `addons`, `os_randomize`, `disable_ads` e `geoip`. Tentei reproduzi-los no Chromium, mas cada um tinha seu próprio problema. Isso pode mudar nas próximas versões antes da v0.4.++Agora, as boas notícias: melhoramos e corrigimos muitas coisas :)++### Melhorias {#v0.3.13-improvements}+- Você já sabe que `StealthyFetcher` e suas classes de sessão estão 101% mais rápidos, mas `DynamicFetcher` e sua classe de sessão também estão 20% mais rápidos.+- O algoritmo de resolução de desafios do Cloudflare foi melhorado para terminar mais rápido e cobrir mais casos. Além disso, graças à reorganização do código, espere que ele resolva os captchas duas vezes mais rápido!+- Todos os fetchers agora usam menos memória.+- O servidor MCP agora usa menos tokens para economizar mais dinheiro!+- A imagem Docker agora é 60% menor.+- Todo o site de documentação foi atualizado com os novos recursos. As explicações também ficaram mais claras, muitas seções foram encurtadas, mais exemplos e argumentos que faltavam foram adicionados, a referência da API ganhou gráficos e várias outras melhorias foram feitas. O site agora carrega 130% mais rápido, usa menos dados e está melhor preparado para SEO.++### Correções {#v0.3.13-fixes}+- Adicionados os argumentos que faltavam nos atalhos do shell de web scraping, que também ficaram mais precisos.+- Corrigido um problema em que `google_search` criava um referer do Google mesmo quando a URL apontava para localhost ou um IP.++## [v0.3.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.12) - 2025-12-18 {#v0.3.12}++### O que mudou {#v0.3.12-what-s-changed}+- Adicionado às classes `DynamicSession`/`AsyncDynamicSession` um argumento chamado `timezone_id`. Ele permite configurar o fuso horário do navegador para corresponder ao do proxy ou VPN que você usa. Assim, os sites não conseguem detectar o proxy pela diferença de fuso horário.+- Melhorada a conversão automática de respostas para JSON.+- A função interna `__create__` foi renomeada para `start` nas classes de sessão dos fetchers, para facilitar seu uso fora do contexto `with`.+- `curl_cffi` e outras dependências foram atualizados para as versões mais recentes.++## [v0.3.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.11) - 2025-12-03 {#v0.3.11}++### O que mudou {#v0.3.11-what-s-changed}+- Melhorada a lógica para lidar com erros de tempo limite ao usar `network_idle` em sites instáveis, como sites com reprodução contínua de mídia.+- Corrigido o preenchimento automático do atalho `stealthy_fetch` no shell de web scraping++## [v0.3.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.10) - 2025-11-26 {#v0.3.10}++**Uma atualização de manutenção com muitas mudanças importantes e possíveis mudanças incompatíveis**++- **Resolvidos** todos os problemas de codificação com uma abordagem melhor, que lida com páginas que não declaram a codificação corretamente (Obrigado a @Kemsty2 pelo esforço de apontar isso em [#110](https://github.com/D4Vinci/Scrapling/issues/110) [#111](https://github.com/D4Vinci/Scrapling/pull/111) )+- **Resolvido** um problema de lógica ao substituir parâmetros da sessão por parâmetros da solicitação em todos os fetchers de navegador, presente desde a v0.3+- **Corrigidas** as assinaturas dos atalhos no shell interativo de web scraping, permitindo o preenchimento automático completo dos atalhos. Esse problema também existia desde a v0.3.+- **Atualizada** a versão do banco de dados Maxmind, o que melhora o argumento `geoip` de `StealthyFetcher` e suas classes de sessão.+- **Atualizados** todos os navegadores usados para as versões mais recentes disponíveis.+- **MUDANÇAS INCOMPATÍVEIS**: Todos os fetchers passaram por uma grande reorganização do código, com algumas mudanças interessantes que podem afetar seu código:+ 1. O código do Scrapling agora tem cerca de ~750 linhas a menos e várias mudanças que facilitam muito a manutenção futura e reduzem um pouco o uso de recursos.+ 2. A validação de todos os fetchers e suas classes de sessão ficou muito mais rápida, o que melhora a velocidade geral.+ 3. Para isso, os fetchers não aceitam mais argumentos posicionais além de `url`. Os demais devem ser passados pelo nome, então seu código deve usar `Fetcher.get('https://google.com', stealthy_headers=True)` e não `Fetcher.get('https://google.com', True)`, caso você fizesse isso por algum motivo!+ 4. Desde a v0.3, havia uma diferença incômoda entre os fetchers de navegador e suas classes de sessão: o argumento para passar configurações personalizadas do parser por solicitação era chamado `custom_config`, enquanto nas classes de sessão era `selector_config`. Essa reorganização permitiu unificar o nome como `selector_config` sem quebrar seu código. Agora o nome principal é `selector_config`, com compatibilidade para o antigo argumento `custom_config`. O preenchimento automático estará disponível somente para `selector_config`.+ 5. Além disso, para permitir todas essas mudanças, as anotações de tipos das funções dos fetchers passaram a ser geradas dinamicamente. Se o preenchimento automático não funcionar bem na sua IDE, confira se você está usando uma versão recente. Testamos quase todas as IDEs e editores conhecidos.++> Também atualizamos todas as tabelas de desempenho com os números atuais, comparados às versões mais recentes de todas as bibliotecas alternativas.++## [v0.3.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.9) - 2025-11-17 {#v0.3.9}++**Uma nova atualização com muitas mudanças importantes**++### 🚀 Novidades e melhorias de uso {#v0.3.9-new-stuff-and-quality-of-life-changes}+- O argumento `impersonate` de `Fetcher` e `FetcherSession` agora aceita uma lista de navegadores. A biblioteca escolhe um deles aleatoriamente a cada solicitação.++```python+from scrapling.fetchers import FetcherSession++with FetcherSession(impersonate=['chrome', 'firefox', 'safari']) as s:+ s.get('https://github.com/D4Vinci/Scrapling')+```++- Um novo argumento no método `clean` de `TextHandler` permite remover facilmente entidades HTML do texto atual.+- Grandes melhorias na documentação, com explicações mais precisas de várias partes e traduções automáticas do arquivo `README.md` principal.++### 🐛 Correções de erros {#v0.3.9-bug-fixes}+- Corrigido um problema importante ao obter respostas dos fetchers de navegador. Agora há detecção inteligente do tipo de conteúdo para garantir que `response.body` contenha o conteúdo renderizado pelo navegador somente quando ele for HTML. Nos demais casos, contém o conteúdo bruto da última solicitação. Isso permite baixar arquivos binários e de texto sem que eles fiquem envolvidos em tags HTML, mantendo a possibilidade de obter o conteúdo renderizado do site quando você precisar.++### 🔨 Outras mudanças {#v0.3.9-misc}+- O guia de contribuição foi atualizado para ficar mais claro e simples.+- Adicionado um workflow para exigir o uso das ferramentas de qualidade de código, as mesmas usadas como hooks de pre-commit.++## [v0.3.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.8) - 2025-10-27 {#v0.3.8}++**Uma nova atualização com muitas mudanças importantes**++### 🚀 Novidades e melhorias de uso {#v0.3.8-new-stuff-and-quality-of-life-changes}+- Em todos os fetchers de navegador, sites cujas solicitações nunca terminam de carregar não causam mais falhas no código quando você usa `network_idle`.+- A lógica para coletar e verificar o conteúdo das páginas nos fetchers de navegador foi alterada para que os navegadores no Windows sejam tão estáveis quanto no Linux/MacOS. Essa diferença de comportamento ocorre por causa da implementação do Playwright no Windows.+- Toda a lógica de validação foi reorganizada, tornando as solicitações de todos os fetchers de navegador 8-15% mais rápidas+- Adicionada a opção `extra_flags` a `DynamicFetcher` e sua sessão para permitir que você acrescente opções personalizadas do Chrome às opções existentes ao iniciar o navegador.+- Restaurada a lógica anterior de rotas para capturar respostas ao usar `page_action`, que havia mudado na última versão. Isso permite coletar a versão mais recente do conteúdo da página caso `page_action` o altere sem fazer uma solicitação. (Obrigado a @gembleman por apontar isso em [#100](https://github.com/D4Vinci/Scrapling/issues/100) e [#102](https://github.com/D4Vinci/Scrapling/pull/102) )++### 🐛 Correções de erros {#v0.3.8-bug-fixes}+- Corrigido um erro de digitação em `load_dom` no async_fetch de DynamicSession+- Corrigido um problema na resolução de desafios do Cloudflare que causava uma espera sem fim por captchas incorporados que não desaparecem após serem resolvidos. Agora a espera é de 30 segundos; depois disso, o captcha é tratado como um dos que não desaparecem (Corrige #100 )++### 🔨 Outras mudanças {#v0.3.8-misc}+- A imagem Docker agora é publicada automaticamente no Dockerhub e no registro de contêineres do GitHub para facilitar o uso.+- Adicionada uma [nova página de documentação](https://github.com/D4Vinci/Scrapling/blob/v0.3.8/docs/tutorials/external.md) que mostra como usar o navegador Scrapeless com o Scrapling.++## [v0.3.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.7) - 2025-10-12 {#v0.3.7}++**Uma nova atualização com muitas mudanças importantes**++### 🚀 Novidades e melhorias de uso {#v0.3.7-new-stuff-and-quality-of-life-changes}+- O argumento `solve_cloudflare` de `StealthyFetcher` foi reformulado para resolver todos os tipos de implementações personalizadas do Turnstile.+- Todo o código foi reorganizado para passar nas verificações do Pyright, melhorando o uso em todas as IDEs e corrigindo muitos erros.+- A lógica das solicitações foi reorganizada para ficar mais clara e rápida (Também resolve #97 )+- Adicionada a opção `user_data_dir` a todas as classes de sessão de navegador para reutilizar os dados de sessões anteriores, como cookies e armazenamento. Se você não informar essa opção, o Playwright usa um diretório aleatório a cada execução, como fazia antes.+- Adicionada a opção de personalização `additional_args` a `Dynamic fetcher` e sua classe de sessão para passar argumentos extras ao contexto do Playwright, como já era possível com `StealthyFetcher`.+- A lógica de rotas que coleta a última resposta de navegação em todos os navegadores foi melhorada. Isso permite passar as respostas brutas ao parser, em vez de passá-las após o processamento pelo navegador como antes. Isso é muito útil para respostas de texto e JSON.++### 🐛 Correções de erros {#v0.3.7-bug-fixes}+- A nova lógica de rotas resolveu um problema ao obter conteúdo de sites instáveis em alguns dispositivos Windows.+- As reorganizações de código desta versão corrigiram muitos erros difíceis de perceber e problemas estranhos de preenchimento automático em algumas IDEs.+- Várias correções no site de documentação++## [v0.3.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.6) - 2025-10-01 {#v0.3.6}++### 🚀 Novidades {#v0.3.6-new-stuff}+- Melhorado o argumento `solve_cloudflare` de `StealthyFetcher` e suas classes de sessão para resolver todos os tipos de desafios Turnstile e de páginas intermediárias do Cloudflare 🎉+- O servidor MCP agora permite usar `Streamable HTTP` para disponibilizar o servidor facilmente.+- Adicionado suporte a Docker. Uma imagem que inclui todos os navegadores é criada e publicada automaticamente no Docker Hub a cada versão++### 🐛 Correções de erros {#v0.3.6-bug-fixes}+- Corrigido um problema de codificação no parser que ocorria em alguns casos, o conhecido erro `invalid start byte`+- Várias partes da biblioteca foram reorganizadas para corrigir vazamentos de memória. Agora o uso de memória é bem menor, dependendo da sua configuração (Também resolve #92 )+- Melhoradas as anotações de tipos em várias partes do código para facilitar o trabalho na IDE (Também resolve #93 )++## [v0.3.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.5) - 2025-09-20 {#v0.3.5}++**Uma versão necessária que corrige vários problemas**++### 🚀 Novidades {#v0.3.5-new-stuff}+- Todos os fetchers de navegador (`DynamicFetcher`/`StealthyFetcher`/...) e suas classes de sessão agora obtêm páginas 15-20% mais rápido:+ 1. O gerenciamento de páginas ficou muito mais rápido graças à melhoria de lógica de @AbdullahY36 em #87+ 2. A lógica geral de validação foi otimizada e a criação de páginas em solicitações síncronas foi melhorada. Juntas, essas mudanças trouxeram grandes ganhos de velocidade++- Grandes melhorias no modo de ocultação de `DynamicFetcher` e suas classes de sessão com a troca de `rebrowser-playwright` por `PatchRight`:+ 1. Antes desta atualização, `rebrowser-playwright` era desativado quando você ativava `stealth` e `real_chrome`, pois eles não funcionavam bem juntos. Com `PatchRight`, esse problema não existe mais+ 2. Agora você pode interagir com Shadow Roots fechados, pois `PatchRight` consegue lidar com eles automaticamente.++### 🐛 Correções de erros {#v0.3.5-bug-fixes}+- Corrigido um erro ao usar o método `re` da classe `Selectors`.+- Corrigido um erro nos comandos `uncurl` e `curl2fetcher` do shell de web scraping que fazia a opção `--data-raw` do curl ser interpretada incorretamente.+- Corrigido um erro no comando `view` do shell de web scraping que ocorria dependendo da codificação do site.+- Corrigido um erro na conversão de conteúdo que afetava o modo `mcp` e os comandos `extract`.++### Novos colaboradores {#v0.3.5-new-contributors}+- @AbdullahY36 fez sua primeira contribuição em #87++## [v0.3.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.4) - 2025-09-16 {#v0.3.4}++**Uma versão necessária que corrige vários problemas**++### 🚀 Novidades {#v0.3.4-new-stuff}+- Todas as classes de sessão dos fetchers foram adicionadas ao shell interativo para uso imediato, sem importação.++### 🐛 Correções de erros {#v0.3.4-bug-fixes}+- Adicionada uma solução alternativa para um erro da API do Playwright no Windows ao obter conteúdo durante a resolução de desafios do Cloudflare.+- Corrigido um problema de codificação no comando `view` do shell interativo+- Corrigido um erro no argumento `max_pages` de `AsyncStealthySession` que causava falhas no código.+- Corrigido um problema das últimas atualizações que fazia as propriedades `html_content` e `prettify` de `Selector` retornarem bytes, dependendo da codificação. Ambas voltaram a retornar strings.++## [v0.3.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.3) - 2025-09-15 {#v0.3.3}++- Removida a lógica que fechava a aba padrão do navegador nos fetchers de navegador, porque causava uma falha. Isso não acontecia no Mac; só foi possível reproduzir no Windows e no Linux++## [v0.3.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.2) - 2025-09-15 {#v0.3.2}++Notas da versão v0.3.2++### 🚀 Novidades {#v0.3.2-new-stuff}++- **Dependências opcionais dos fetchers**: Todos os fetchers agora fazem parte de grupos de dependências opcionais, reduzindo o tamanho do pacote base. O módulo base `scrapling` contém apenas o parser. Para usar os fetchers ou as opções de linha de comando, execute `pip install "scrapling[fetchers]"`. Veja as instruções detalhadas de instalação [aqui](index.md#installation)+- **Configuração por página nas sessões**: As classes de sessão dos fetchers de navegador agora permitem configurar cada página separadamente. Todos os parâmetros das solicitações são validados como os das sessões. Mais detalhes no site de documentação [aqui](fetching/stealthy.md#full-list-of-arguments)+ <br>Exemplo:++ ```python+ with StealthySession(headless=True, solve_cloudflare=True) as session:+ page = session.fetch('https://nopecha.com/demo/cloudflare', google_search=False)+ ```++- **Melhorias nos fetchers de navegador**+ - Uma nova opção permite controlar se o navegador deve esperar a execução de JavaScript terminar nas páginas. Ela está ativada por padrão, como antes++ ```python+ with DynamicSession(headless=True, disable_resources=False, network_idle=True) as session:+ page = session.fetch('https://quotes.toscrape.com/', load_dom=False)+ ```++ - O modo de ocultação agora é mais confiável em `DynamicFetcher` e suas classes de sessão.+ - `DynamicFetcher` e `StealthyFetcher` agora usam menos recursos, ao encontrar e fechar automaticamente a aba padrão aberta pelos contextos persistentes da API do Playwright+ - Corrigido um erro importante de lógica na rotação de páginas dos fetchers de navegador. As páginas anteriores agora são substituídas por novas, pois as abas reutilizadas podiam manter configurações de usos anteriores+ - `StealthyFetcher` e suas classes de sessão agora estão um pouco mais rápidos (5%)++- **Melhorias na propriedade `.body`**: Agora retorna o conteúdo recebido como está, sem processamento. Isso permite baixar arquivos e lidar com solicitações que não retornam HTML. O exemplo abaixo mostra como baixar uma imagem:++ ```python+ from scrapling.fetchers import Fetcher++ page = Fetcher.get('https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/poster.png')+ with open(file='poster.png', mode='wb') as f:+ f.write(page.body)+ ```++### 🐛 Correções de erros {#v0.3.2-bug-fixes}++- **Problemas de codificação resolvidos**: Corrigidos vários problemas de codificação com alguns sites no parser, no modo mcp e nos comandos extract (Também resolve #80 e #81)+- **Análise mais rápida**: Graças a várias mudanças em diferentes partes, a biblioteca agora está mais rápida, como mostram os benchmarks atualizados++### 🔨 Outras mudanças {#v0.3.2-misc}++- **Benchmarks atualizados**: As medições foram atualizadas para comparar as melhorias atuais de velocidade com as versões mais recentes de bibliotecas semelhantes+- **Grande parte do código foi reorganizada e o código sem uso foi substituído por implementações melhores**: Menos código, mais claro e mais fácil de manter+- **Novo vídeo do YouTube**: Adicionado conteúdo em vídeo à documentação do MCP.+- **Novo modelo de issue**: Um modelo simples para quem não consegue usar os modelos atuais.+- **Otimização do workflow de CI**: O workflow de testes agora ignora execuções quando apenas a documentação ou outros arquivos sem código são alterados.+- **Dependências atualizadas**: Várias dependências foram atualizadas para as versões mais recentes.+- **Melhorias no estilo do código**: Novas regras do ruff foram aplicadas em todos os arquivos.+- **Hooks de pre-commit**: Atualizada a configuração do pre-commit.++### 🎯 Mudanças incompatíveis {#v0.3.2-breaking-changes}++- Removido o parâmetro `max_pages` da versão síncrona de `StealthySession` para corresponder a `DynamicSession`, pois ele não faz sentido na versão síncrona++## [v0.3.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.1) - 2025-09-02 {#v0.3.1}++1. Corrigido um problema ao instalar scrapling sem o extra `shell` (#76 )+2. Adicionado um argumento a todos os fetchers de navegador e suas classes de sessão para passar um arquivo JS que é executado na criação da página (#56) :++```python+from scrapling.fetchers import StealthyFetcher++StealthyFetcher.fetch('https://example.com', init_script="/absolute/path/to/js/script.js")+```++## [v0.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3) - 2025-09-01 {#v0.3}++🎉 **Versão principal - Renovação completa da arquitetura**++O Scrapling v0.3 é a maior atualização da história do projeto. Inclui uma reescrita completa da arquitetura, grandes melhorias de desempenho e novos recursos poderosos, como integração com IA e um shell interativo de web scraping.++Esta versão inclui várias mudanças incompatíveis. Leia as notas da versão com atenção.++### 🚀 Principais novidades {#v0.3-major-new-features}++#### Arquitetura baseada em sessões {#v0.3-session-based-architecture}+- **Novas classes de sessão**: Reescrita completa que adiciona suporte a sessões persistentes+ - `FetcherSession` - Solicitações HTTP com gerenciamento de estado persistente, tanto para código síncrono quanto assíncrono+ - `DynamicSession`/`AsyncDynamicSession` - Automação do navegador, que fica aberto até você terminar+ - `StealthySession`/`AsyncStealthySession` - Navegação com ocultação da automação, mantendo o navegador aberto até você terminar+- **Gerenciamento assíncrono de abas do navegador**: Novo grupo de abas pelo argumento `max_pages`, que alterna entre elas para fazer solicitações simultâneas com o navegador+- **Sessões simultâneas**: Execute várias sessões isoladas ao mesmo tempo++Consulte a seção `Fetching` do site para mais detalhes.++#### Muitos recursos novos para ocultar a automação e contornar sistemas antibot {#v0.3-a-lot-of-new-stealth-anti-bot-capabilities}+- **🤖 Resolução de desafios do Cloudflare**: [Resolução automática de desafios do Cloudflare Turnstile](fetching/stealthy.md#cloudflare-and-stealth-options) no `StealthyFetcher` e em suas classes de sessão+- **Simulação de impressões digitais do navegador**: Simule impressões digitais TLS de navegadores reais, use cabeçalhos compatíveis com a versão do navegador e aproveite o suporte a HTTP/3 e outros recursos da nova classe [Fetcher](fetching/static.md)+- **Modo de ocultação melhorado**: O modo de ocultação do `DynamicFetcher` e de suas classes de sessão agora é mais robusto e confiável (também conhecido como `PlayWrightFetcher`)++#### Integração com IA e servidor MCP {#v0.3-ai-integration-mcp-server}+- **Servidor MCP integrado**: Servidor Model Context Protocol para web scraping com ajuda de IA+- **6 ferramentas poderosas**: `get`, `bulk_get`, `fetch`, `bulk_fetch`, `stealthy_fetch`, `bulk_stealthy_fetch`+- **Extração inteligente de conteúdo**: Converta páginas ou elementos da web para Markdown ou HTML, ou extraia uma versão limpa do texto+- **Suporte a seletores CSS**: Use o motor do Scrapling para selecionar elementos específicos com precisão antes de enviar o conteúdo à IA+- **Contorno de sistemas antibot**: Lide com Cloudflare Turnstile e outras proteções+- **Suporte a proxies**: Use proxies para manter o anonimato e escolher a localização geográfica+- **Simulação de navegadores**: Simule navegadores reais com impressões digitais TLS, cabeçalhos reais compatíveis com a versão e mais+- **Processamento em paralelo**: Extraia dados de várias URLs ao mesmo tempo para ganhar eficiência+- [e mais...](ai/mcp-server.md)++#### Novo shell interativo de web scraping {#v0.3-new-interactive-web-scraping-shell}+- **Novo shell**: Shell IPython personalizado com vários atalhos inteligentes integrados, como `get`, `post`, `put`, `delete`, `fetch` e `stealthy_fetch`+- **Gerenciamento inteligente de páginas**: Novos comandos `page` e `pages` para guardar automaticamente a página atual e o histórico de todas as solicitações feitas pelo shell+- **Integração com Curl**: Use as funções `uncurl` e `curl2fetcher` para converter comandos curl das ferramentas de desenvolvedor do navegador em solicitações do `Fetcher`+- [e mais...](cli/interactive-shell.md)++#### Extraia dados pelo terminal sem programar {#v0.3-scrape-from-the-terminal-without-programming}+- **Novos comandos de extração**: Extraia dados pelo terminal sem programar+ - `scrapling extract get/post/put/delete` - Solicitações HTTP simples+ - `scrapling extract fetch` - Extração de conteúdo dinâmico+ - `scrapling extract stealthy-fetch` - Contorno de sistemas antibot+- **Baixa páginas da web** e salva seu conteúdo em arquivos.+- **Converte HTML para formatos legíveis**, como Markdown, mantém o conteúdo em HTML ou extrai apenas o texto da página.+- **Aceita seletores CSS personalizados** para extrair partes específicas da página.+- **Lida com solicitações HTTP e obtenção de páginas por navegadores.**+- **Muitas opções de personalização**, com cabeçalhos, cookies, proxies e outras configurações. Quase todas as opções disponíveis no código também estão disponíveis pelo terminal.+- [e mais...](cli/extract-commands.md)++### 🔧 Melhorias técnicas {#v0.3-technical-improvements}++#### Melhorias de desempenho {#v0.3-performance-enhancements}+- **Fetcher agora é 4 vezes mais rápido** - Sim, você leu certo!+- **DynamicFetcher agora é ~60% mais rápido** - Uma versão muito mais rápida conforme a sua configuração (principalmente o modo de ocultação)+- **StealthyFetcher agora é 20–30% mais rápido** - Graças à nova estrutura e ao uso da nossa implementação em vez da interface Python do `Camoufox`+- **Ganho combinado de velocidade de 50%+** nos principais métodos de seleção (`find_by_text`, `find_similar`, `find_by_regex`, `relocate` etc.) 🚀+- **Aumento de ~10% na velocidade dos métodos que obtêm a primeira correspondência CSS/XPath** - `css_first` e `xpath_first` agora são mais rápidos que `css` e `xpath`+- **O método `get_all_text()` está 40% mais rápido** na extração de conteúdo+- **Melhoria de velocidade de 20%** ao reencontrar elementos de forma adaptativa+- **Otimização das propriedades de navegação** - Propriedades como `next`, `previous`, `below_elements` e outras agora são bem mais rápidas+- **Limpeza de texto 5 vezes mais rápida**+- **Melhor uso de memória** com importações otimizadas e menos trabalho adicional+- **⚡ Importações muito rápidas**: Menor tempo de inicialização com o carregamento otimizado de módulos+- **Melhores resultados nos testes de desempenho**: Todas as melhorias de velocidade tornam o Scrapling muito mais rápido que antes em comparação com outras bibliotecas (1775 vezes mais rápido que BeautifulSoup e 5.1 vezes mais rápido que AutoScraper; veja os [testes de desempenho](benchmarks.md))++#### Arquitetura, qualidade do código e melhorias de uso {#v0.3-architecture-code-quality-and-quality-of-life}+- **Contexto persistente**: Todos os fetchers baseados em navegador agora usam um contexto persistente por padrão. (Também resolve #64)+- **Uso de msgspec para validar rapidamente a configuração de todos os fetchers baseados em navegador** antes de executar as solicitações, o que facilita encontrar erros.+- **Todos os cookies** retornados pelos fetchers agora têm o formato aceito pelo mesmo fetcher. Assim, você pode obter cookies e passá-los novamente a todos os fetchers e suas classes de sessão.+- **Verificação e formatação de código mais rápidas** após a migração para `ruff`+- **Sistema de build moderno**: Migração de setup.py para pyproject.toml 📦+- **Melhores ações e fluxos de trabalho do GitHub** para facilitar o desenvolvimento e os testes+- **🎨 Melhores anotações de tipos**: Cobertura completa de tipos com padrões modernos do Python para melhorar o suporte da IDE e a confiabilidade+- **Código mais limpo**: Remoção de código sem uso e otimização das funções principais 🧹+- **🚀 Compatibilidade com versões anteriores**: Novos atalhos para manter a compatibilidade com código antigo++### Mudanças incompatíveis {#v0.3-breaking-changes}++#### Versão mínima do Python {#v0.3-minimum-python-version}+- **Requer Python 3.10+**: Fim do suporte ao Python 3.9 e versões anteriores++#### Nomes de classes e métodos {#v0.3-class-and-method-naming}+Essas mudanças de nomes buscam dar mais clareza e consistência, principalmente para novos usuários.++- **`Adaptor` → `Selector`**: A classe principal de análise foi renomeada (ainda pode ser importada como `Adaptor` para manter a compatibilidade)+- **`Adaptors` → `Selectors`**: A classe de coleção foi renomeada (ainda pode ser importada como `Adaptors` para manter a compatibilidade)+- **`auto_match` → `adaptive`**: O parâmetro foi renomeado em todos os métodos+- **`adaptor_arguments` → `selector_config`**: O parâmetro de configuração foi renomeado+- **`automatch_domain` → `adaptive_domain`**: O parâmetro de domínio foi renomeado+- **`additional_arguments` → `additional_args`**: O nome do parâmetro foi encurtado+- **⚠️ `text/body` → `content`**: O parâmetro do construtor de Selector agora aceita tanto `str` quanto `bytes`+- **`PlayWrightFetcher` → `DynamicFetcher`**: A classe de automação do navegador foi renomeada (ainda pode ser importada como `PlayWrightFetcher` para manter a compatibilidade)+- **DynamicFetcher não inclui mais a lógica nem os argumentos do NSTBrowser**, pois não faz mais sentido mantê-los.+- **O argumento headless do StealthyFetcher não aceita mais 'virtual'** porque agora só usamos a biblioteca Camoufox para obter o caminho de instalação do navegador e as demais opções de inicialização++### 🐛 Correções de erros {#v0.3-bug-fixes}++- Corrigida a contagem de filhos aninhados em tags ignoradas por `get_all_text` (#61)+- Corrigido o problema de instalação causado por espaços no caminho do executável do Python (#57)+- Resolvidos problemas de threads no armazenamento, com tratamento da recursão quando o recurso adaptativo está ativado+- Corrigidos problemas de prioridade de argumentos com o padrão Sentinel em `FetcherSession`+- Corrigido o tratamento dos tipos de proxy em `StealthyFetcher`+- Corrigidos conflitos entre os argumentos `referer` e `google_search`+- Corrigidos problemas na injeção assíncrona de scripts de ocultação++## [v0.2.99](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.99) - 2025-04-08 {#v0.2.99}++**Esta é uma atualização importante para que todos aproveitem o Scrapling por completo, como ele foi pensado.**++### O que mudou {#v0.2.99-what-s-changed}+#### Novo site com toda a documentação {#v0.2.99-new-full-documentation-website}+- Sim, finalmente 😄 Confira [aqui](index.md)+#### Importação unificada dos fetchers {#v0.2.99-unified-import-logic-for-fetchers}+- Agora você pode importar todos os fetchers com `from scrapling.fetchers import Fetcher, AsyncFetcher, StealthyFetcher, PlayWrightFetcher` e usá-los diretamente, como em `page = Fetcher.get(...)`, sem criar uma instância.<br/> Isso substitui a importação antiga `from scrapling.defaults import Fetcher, AsyncFetcher, StealthyFetcher, PlayWrightFetcher`.+#### Mudança incompatível: automatch agora está desativado por padrão {#v0.2.99-breaking-change-automatch-is-now-turned-off-by-default}+- Agora existe uma nova forma de ativar automatch pelos fetchers ou pelas outras opções de análise. Veja a [documentação](fetching/choosing.md#parser-configuration-in-all-fetchers) para mais detalhes.+> As importações e a lógica antigas continuam disponíveis, com um aviso, para manter a compatibilidade.+#### Novas opções para os fetchers {#v0.2.99-new-options-added-to-fetchers}+- Agora `StealthyFetcher` e `PlayWrightFetcher` têm um novo argumento chamado `wait` ao obter páginas. Ele faz o fetcher esperar um tempo definido em milissegundos antes de fechar a página e retornar a resposta.+- Os métodos de `StealthyFetcher` chamados `fetch` e `async_fetch` agora têm o argumento `additional_arguments` para passar configurações extras ao Camoufox. Elas têm prioridade sobre as configurações do Scrapling (#54 )+#### Correções de erros {#v0.2.99-bugs-squashed}+- Corrigido um erro ao detectar redirecionamentos em `async_fetch` nas classes `StealthyFetcher` e `PlayWrightFetcher`.++**_Obrigado por todo o apoio e pelas doações!_**++## [v0.2.98](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.98) - 2025-03-17 {#v0.2.98}++**Esta é uma atualização importante para que todos aproveitem o Scrapling por completo, como ele foi pensado**++### O que mudou {#v0.2.98-what-s-changed}+#### Melhorias no uso de memória e na velocidade {#v0.2.98-various-memory-usage-and-speed-optimizations}+- O uso de memória de todos os métodos de seleção agora é ~40% do uso anterior, com um pequeno aumento de velocidade.+- Aplicado carregamento sob demanda a todos os submódulos da biblioteca: agora só é carregado o que você usa. Por exemplo:+Antes da atualização, a importação `from scrapling import Adaptor` usava `30-40mb` de RAM porque também carregava todos os fetchers e outros componentes. Agora usa `~1.2mb`.+- A última atualização fez a biblioteca usar ~32% da memória que usava antes com um grupo grande de solicitações. Agora ajustamos ainda mais o cache para usar menos memória.+- Pequeno aumento geral de velocidade do analisador, de 2-5%++**_Obrigado por todo o apoio e pelas doações!_**++## [v0.2.97](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.97) - 2025-03-15 {#v0.2.97}++**Esta é uma atualização importante para que todos aproveitem o Scrapling por completo, como ele foi pensado**++### O que mudou {#v0.2.97-what-s-changed}+#### Menor uso de memória e um pequeno aumento de velocidade em todos os fetchers {#v0.2.97-lower-memory-usage-and-small-speed-increase-across-all-fetchers}+- Os novos limites de tamanho do cache em toda a biblioteca reduzem bastante o uso de memória ao fazer muitas solicitações ou operações.+- Reorganizadas grandes partes dos fetchers para facilitar a manutenção e aumentar um pouco a velocidade.++#### Correções de erros {#v0.2.97-bugs-fixed}+- Corrigido um erro de `TextHandler` que convertia um valor não textual em uma string vazia quando ele era importado sozinho. Agora qualquer valor passado a `TextHandler` é convertido primeiro em string e depois em `TextHandler`. Isso vale para todos os valores: afinal, como o nome indica, `TextHandler` foi feito para trabalhar apenas com texto! (#45 )+- Corrigido um erro que fazia a maioria dos métodos de AsyncFetcher ignorar o argumento `retries`.++#### Outras mudanças {#v0.2.97-miscellaneous}+- Atualizadas as anotações de tipos da maioria dos argumentos em todos os fetchers para ficarem mais claras e precisas.++**_Obrigado por todo o apoio e pelas doações!_**++## [v0.2.96](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.96) - 2025-03-05 {#v0.2.96}++**Esta é uma atualização importante para que todos aproveitem o Scrapling por completo, como ele foi pensado**++### O que mudou {#v0.2.96-what-s-changed}+1. Adicionada a opção `-f` a `scrapling install` para forçar a reinstalação das dependências do navegador. Recomendo executar `scrapling install -f` agora para aproveitar o grande aumento de velocidade do `StealthyFetcher` com a nova versão do navegador Camoufox :)+2. Corrigido um erro de `TextHandler` que retornava `TextHandlers` em vez de `TextHandler` ao obter uma fatia do texto, e corrigida a anotação de tipo desse retorno (#41 )+3. Corrigido um problema que fazia `scrapling install` abrir um shell Python em alguns casos!++## [v0.2.95](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.95) - 2025-02-25 {#v0.2.95}++**Esta é uma atualização importante para que todos aproveitem o Scrapling por completo, como ele foi pensado**++### O que mudou {#v0.2.95-what-s-changed}+1. Corrigido um erro de `Fetcher` que fazia os cabeçalhos gerados pelo argumento `stealthy_headers` substituírem alguns cabeçalhos do usuário, como `Accept` (#39 )+2. Melhorada um pouco a lógica de geração de cabeçalhos, o que deve aumentar ligeiramente a velocidade.++## [v0.2.94](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.94) - 2025-02-22 {#v0.2.94}++**Esta é uma atualização importante para que todos aproveitem o Scrapling por completo, como ele foi pensado**++### O que mudou {#v0.2.94-what-s-changed}+1. Adicionada a propriedade `history` a todos os fetchers para mostrar os redirecionamentos (#32 )+2. Corrigida a lógica do argumento `case_sensitive` em todos os métodos `re`/`re_first`. Se você usava essa opção, os resultados do seu código podem mudar (mas talvez você mereça, já que percebeu que ela não funcionava direito e não abriu uma issue, hahaha)+3. Atualizadas as dependências e reativado `coop` no motor Camoufox (StealthyFetcher).++## [v0.2.93](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.93) - 2025-01-31 {#v0.2.93}++**Esta é uma atualização importante para que todos aproveitem o Scrapling por completo, como ele foi pensado**++### O que mudou {#v0.2.93-what-s-changed}+1. O tipo de retorno agora é consistente em todo o motor de análise. Você sempre recebe um destes tipos: `Adaptor`, `Adaptors`, `TextHandler`, `TextHandlers`, `None`, ou uma lista quando há resultados mistos, como com um seletor CSS combinado. Isso facilita a programação com menos verificações manuais de tipos, torna a biblioteca mais estável e permite encadear métodos em todos os casos.+2. Reorganizada a maior parte do motor de análise, principalmente a classe `Adaptor`, para deixá-lo mais limpo e, acima de tudo, mais rápido. Quase todos os métodos e propriedades, principalmente os de busca, ganharam entre 5-40% de velocidade. Alguns melhoraram ainda mais, como `find_by_regex`, que ganhou ~60%! O recurso automatch ganhou cerca de ~5%.+3. Corrigidos erros na lógica de `find_all`/`find` que aplicavam os filtros com OR em alguns casos e com AND em outros. Agora todos os elementos retornados precisam atender a todos os filtros que você passar.+4. Todos os métodos ligados a regex agora retornam `TextHandler`/`TextHandlers` para facilitar o encadeamento de métodos.+5. **Adicionada uma nova** propriedade `below_elements`, que retorna um objeto `Adaptors` com todos os elementos abaixo do elemento atual na árvore DOM.+6. Todos os métodos e propriedades que retornavam código HTML como string agora retornam `TextHandler`, para facilitar o uso de regex e outras operações...+7. StealthyFetcher agora é um pouco mais rápido e oculta melhor a automação. Também é possível clicar em CAPTCHAs dentro de iframes, como o **Cloudflare Turnstile**.+8. O preenchimento automático e as anotações de tipos melhoraram bastante em quase metade da biblioteca, principalmente em `Adaptor`, `TextHandler` e `TextHandlers`.+9. Ao obter uma fatia de `TextHandler`, acessar por índice ou usar o método `split`, você agora recebe outro `TextHandler` em vez de uma string padrão do Python. Quase todas as operações e métodos padrão de strings retornam outro `Texthandler` para que você sempre possa encadear métodos e funções.+10. Corrigidos alguns erros pequenos e de digitação. Por exemplo, async_put de Fetcher fazia uma solicitação post em vez de put 😶🌫️+11. Melhorado um pouco o README enquanto termino o site da documentação.++Era para ser uma pequena atualização antes da versão 0.3, mas decidi melhorá-la um pouco mais.++## [v0.2.92](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.92) - 2024-12-26 {#v0.2.92}++### O que mudou {#v0.2.92-what-s-changed}+- As respostas dos fetchers baseados em navegador agora usam fontes de dados mais confiáveis quando a página carregada contém muitos iframes.+- **Instalar `Scrapling` ficou ainda mais fácil: instale com pip, execute `scrapling install` no terminal e pronto!**+- Corrigida uma anotação de tipo imprecisa no analisador.++## [v0.2.91](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.91) - 2024-12-19 {#v0.2.91}++### O que mudou {#v0.2.91-what-s-changed}+- Corrigido um erro que fazia a mensagem de log da obtenção de páginas aparecer só na primeira solicitação.+- Por padrão, a API do Playwright retorna a primeira resposta que atende ao estado de carregamento passado ao método `goto`: `["load", "domcontentloaded", "networkidle"]`. Se um site tiver uma página de espera, como a do Cloudflare, que depois redireciona para o site real, o Playwright retorna o primeiro código de status, que pode ser 403. Esta atualização resolve o problema em `PlaywrightFetcher` e `StealthyFetcher`, já que ambos usam a API do Playwright. O resultado não depende mais desse comportamento padrão.+- Adicionado suporte a proxies SOCKS na classe `Fetcher`.+- Corrigida a anotação de tipo do argumento `wait_selector_state` para que o preenchimento automático mostre os valores corretos que você pode usar.++## [v0.2.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.9) - 2024-12-16 {#v0.2.9}++### O que mudou {#v0.2.9-what-s-changed}+##### Novos recursos {#v0.2.9-new-features}+1. Chegou o **tão esperado** suporte assíncrono ao Scrapling! Agora você tem `AsyncFetcher`, a versão assíncrona de `Fetcher`, e tanto `StealthyFetcher` quanto `PlayWrightFetcher` têm um novo método chamado `async_fetch` com as mesmas opções.++```python+>> from scrapling import StealthyFetcher+>> page = await StealthyFetcher().async_fetch('https://www.browserscan.net/bot-detection') # the async version of fetch+>> page.status == 200+True+```++2. A classe `StealthyFetcher` agora tem o argumento `geoip` nos métodos de obtenção de páginas. Quando ativado, usa automaticamente a longitude, latitude, fuso horário, país e configuração regional do IP, e altera o endereço IP exposto pelo WebRTC. Também calcula e simula o idioma do navegador conforme a distribuição dos falantes de cada idioma na região de destino.+3. Adicionado o argumento `retries` às classes `Fetcher`/`AsyncFetcher`, para você definir o número de novas tentativas de cada solicitação feita por `httpx`.+4. Adicionado o método `url_join` a `Adaptor` e aos fetchers. Ele recebe uma URL relativa e a combina com a URL atual para gerar uma URL absoluta completa!+5. Adicionado o método `keep_cdata` a `Adaptor` e aos fetchers para impedir que o analisador remova cdata quando você precisar mantê-lo.+6. Em `Adaptor`/`Response`, o método `body` agora retorna a resposta HTML original quando possível, sem processá-la na biblioteca.+7. Adicionado registro de logs à classe `Response`. Ao usar os fetchers, você agora recebe um log com informações sobre a resposta.+Exemplo:++ ```python+ >> from scrapling.defaults import Fetcher+ >> Fetcher.get('https://books.toscrape.com/index.html')+ [2024-12-16 13:33:36] INFO: Fetched (200) <GET https://books.toscrape.com/index.html> (referer: https://www.google.com/search?q=toscrape)+ >>+ ```++8. Ao usar métodos padrão de strings em um `TextHandler`, como `.replace()`, você agora recebe outro `TextHandler`. Antes eles retornavam uma string padrão.+9. Grandes melhorias de velocidade em toda a biblioteca e melhorias na ocultação da automação nas classes de fetchers em geral.+10. Adicionadas funções de compatibilidade como `extract_first`\`extract`, que retornam o mesmo resultado que o objeto original. Elas existem apenas para facilitar a cópia de código do Scrapy/Parsel para o Scrapling quando necessário, pois são usadas nessas bibliotecas!+11. As solicitações em lote agora são muito mais rápidas graças à reorganização de boa parte do código e ao uso de cache nos lugares certos.++##### Mudanças incompatíveis {#v0.2.9-breaking-changes}+- Removido o suporte ao Python 3.8. (Principalmente porque o Playwright deixou de dar suporte a ele, mas essa versão já era problemática)+- O argumento `debug` foi removido de toda a biblioteca. Para ativar a depuração, faça isto depois de importá-la:++ ```python+ >>> import logging+ >>> logging.getLogger("scrapling").setLevel(logging.DEBUG)+ ```++##### Correções de erros {#v0.2.9-bugs-squashed}+1. WebGL agora está ativado por padrão porque muitas proteções verificam se ele está habilitado.+2. Corrigidos alguns erros e erros de digitação na documentação e no README.++##### Melhorias de uso {#v0.2.9-quality-of-life-changes}+1. Todos os logs agora usam o logger chamado `scrapling` para facilitar o controle. Antes usávamos o logger raiz.+2. Reorganizada a pasta de testes para ficar mais clara e adicionados testes dos novos recursos. Todos os testes foram reescritos de forma mais limpa e novos testes foram adicionados para aumentar a cobertura.+3. Reorganizada boa parte do código para deixá-lo mais limpo e fácil de manter.++> Todas essas mudanças estavam previstas para a versão 0.3, mas decidi incluí-las aqui porque ainda vai levar um tempo até a próxima versão. O próximo passo é terminar o site da documentação detalhada e depois trabalhar na versão 0.3++## [v0.2.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.8) - 2024-11-30 {#v0.2.8}++### O que mudou {#v0.2.8-what-s-changed}+- Pequena atualização com melhorias de uso necessárias no código e a correção de um erro de digitação no README principal (#20)++## [v0.2.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.7) - 2024-11-26 {#v0.2.7}++### O que mudou {#v0.2.7-what-s-changed}+##### Novos recursos {#v0.2.7-new-features}+- Se você usar o argumento `wait_selector` com as classes `StealthyFetcher` e `PlayWrightFetcher`, o Scrapling espera novamente que o JS seja carregado e executado por completo, como de costume. Se usar `network_idle`, ele também espera esse estado novamente depois. Se todos os estados já tiverem sido atendidos, não há espera.+- Agora você pode ativar e desativar anúncios em `StealthyFetcher` com o argumento `disable_ads`. O bloqueio está ativado por padrão e instala a extensão `ublock origin`.+- Agora você pode definir a configuração regional usada por `PlayWrightFetcher` com o argumento `locale`. O valor padrão continua sendo `en-US`.+- As solicitações básicas feitas por `Fetcher` agora aceitam proxies no formato `http://username:password@localhost:8030`.+- Melhorado um pouco o modo de ocultação de `PlayWrightFetcher`.++##### Correções de erros e melhorias {#v0.2.7-bugs-squashed-improvements}+1. Ativar proxies na classe `PlayWrightFetcher` não depende mais de o modo `stealth` estar ativado ou desativado (obrigado a [@AbdullahY36](https://github.com/AbdullahY36) pelo aviso)+2. Agora `ResponseEncoding` verifica se a codificação retornada na resposta pode ser usada com a página. Se ela causar um erro, o Scrapling usa `utf-8` por padrão++## [v0.2.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.6) - 2024-11-24 {#v0.2.6}++### O que mudou {#v0.2.6-what-s-changed}+##### Novos recursos {#v0.2.6-new-features}+- Agora `PlayWrightFetcher` pode usar o navegador real diretamente se você passar `real_chrome` à função `PlayWrightFetcher.fetch`, mas é necessário ter o Chrome instalado. O Scrapling abre uma instância do seu Chrome e você pode usar a maioria das opções normalmente. (Antes só havia o argumento `cdp_url` para fazer isso)+- Atualizada a versão indicada nos cabeçalhos gerados para navegadores reais.++##### Correções de erros {#v0.2.6-bugs-squashed}+1. O formato dos cabeçalhos de navegador gerados por `BrowserForge` estava desatualizado, o que fazia algumas proteções detectarem o Scrapling. Agora `BrowserForge` só é usado para gerar um useragent real.+2. O argumento `hide_canvas` agora está desativado por padrão porque o ReCaptcha do Google o detecta.++## [v0.2.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.5) - 2024-11-23 {#v0.2.5}++### O que mudou {#v0.2.5-what-s-changed}++##### Correções de erros {#v0.2.5-bugs-squashed}+- Tratado um erro do argumento 'wait_selector' quando ele encontra mais de 1 elemento. Isso afeta as classes `StealthyFetcher` e `PlayWrightFetcher`.+- Corrigido o tipo de codificação quando o cabeçalho `content_type` recebe valores com parâmetros como `charset` (obrigado a @andyfcx por [#12](https://github.com/D4Vinci/Scrapling/issues/12) )++##### Melhorias de uso {#v0.2.5-quality-of-life}+- Adicionados testes para cobrir novas partes do código, e os testes passaram a rodar em threads.+- Atualizei os docstrings para que sejam exibidos corretamente no apidoc do Sphinx e em ferramentas semelhantes.++##### Novos colaboradores {#v0.2.5-new-contributors}+- @andyfcx fez sua primeira contribuição em [#13 ](https://github.com/D4Vinci/Scrapling/pull/13)++## [v0.2.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.4) - 2024-11-20 {#v0.2.4}++### O que mudou {#v0.2.4-what-s-changed}++##### Correções de erros {#v0.2.4-bugs-squashed}+- Corrigido um erro ao obter os bytes da resposta depois de usar `network_idle` nas classes `StealthyFetcher` e `PlayWrightFetcher`. <br/> Isso causava a seguinte mensagem de erro:++ ```+ Response.body: Protocol error (Network.getResponseBody): No resource with given identifier found+ ```++- A API do PlayWright às vezes retorna respostas com o texto de status vazio. Agora o `Scrapling` calcula esse texto por conta própria se isso acontecer. Isso afeta as classes `StealthyFetcher` e `PlayWrightFetcher`.++## [v0.2.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.3) - 2024-11-19 {#v0.2.3}++### O que mudou {#v0.2.3-what-s-changed}++##### Correções de erros {#v0.2.3-bugs-squashed}+- Corrigido um erro na instalação com pip que impedia por completo o funcionamento do modo de ocultação do PlayWright Fetcher.++## [v0.2.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.2) - 2024-11-16 {#v0.2.2}++### O que mudou {#v0.2.2-what-s-changed}+##### Novos recursos {#v0.2.2-new-features}+- Se você não quiser passar argumentos ao objeto `Adaptor` gerado e preferir usar os valores padrão, pode usar esta importação para deixar o código mais limpo++ ```python+ >> from scrapling.default import Fetcher, StealthyFetcher, PlayWrightFetcher+ >> page = Fetcher.get('https://example.com', stealthy_headers=True)+ ```++ Caso contrário++ ```python+ >> from scrapling import Fetcher, StealthyFetcher, PlayWrightFetcher+ >> page = Fetcher(auto_match=False).get('https://example.com', stealthy_headers=True)+ ```++##### Correções de erros {#v0.2.2-bugs-squashed}+1. Corrigido um erro no objeto `Response`, introduzido no patch v0.2.1 de ontem, que acontecia em alguns casos de seleção ou análise aninhadas.++## [v0.2.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.1) - 2024-11-15 {#v0.2.1}++### O que mudou {#v0.2.1-what-s-changed}+##### Novos recursos {#v0.2.1-new-features}+1. O objeto `Response` retornado por todos os fetchers agora é igual ao objeto `Adaptor`, mas com estes atributos adicionais: `status`, `reason`, `cookies`, `headers` e `request_headers`. Os atributos `cookies`, `headers` e `request_headers` sempre são do tipo `dictionary`. <br/>Assim, seu código agora pode ser:++ ```python+ >> from scrapling import Fetcher+ >> page = Fetcher().get('https://example.com', stealthy_headers=True)+ >> print(page.status)+ 200+ >> products = page.css('.product')+ ```++ Em vez do código anterior++ ```python+ >> from scrapling import Fetcher+ >> fetcher = Fetcher().get('https://example.com', stealthy_headers=True)+ >> print(fetcher.status)+ 200+ >> page = fetcher.adaptor+ >> products = page.css('.product')+ ```++ Mantive a propriedade `.adaptor` funcionando para preservar a compatibilidade com versões anteriores.++2. As classes `StealthyFetcher` e `PlayWrightFetcher` agora aceitam um argumento `proxy` no método de obtenção de páginas, que pode ser uma string ou um dicionário.+3. A classe `StealthyFetcher` agora tem o argumento `os_randomize` no método `fetch`. Se ativado, o Scrapling escolhe aleatoriamente as impressões digitais do sistema operacional. Por padrão, as impressões digitais correspondem ao sistema operacional atual.++##### Correções de erros {#v0.2.1-bugs-squashed}+1. Corrigido um erro ao passar cabeçalhos com a classe `Fetcher`.+2. Corrigido um erro ao analisar respostas JSON recebidas das classes de fetchers.++##### Melhorias de uso {#v0.2.1-quality-of-life-changes}+1. As funções de texto tentavam remover comentários HTML antes de retornar o texto, mas isso causava erros em alguns casos e complicava o código sem necessidade. Agora elas voltaram ao comportamento padrão do lxml: **você vai notar um pequeno aumento de velocidade nas operações que dependem do texto dos elementos, como os seletores**. Se quiser que o Scrapling remova comentários HTML antes de retornar o texto para evitar a divisão estranha de texto do lxml/parsel/scrapy, mantenha o argumento `keep_comments` como True, que é o padrão.++## [v0.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2) - 2024-11-11 {#v0.2}++### O que mudou {#v0.2-what-s-changed}+##### Novos recursos {#v0.2-new-features}+1. Chegou o recurso `Fetchers`, com 3 novos tipos principais para o Scrapling obter páginas para você com MUITAS opções!+ - A classe `Fetcher`, para solicitações HTTP básicas+ - A classe `StealthyFetcher`, um fetcher que oculta totalmente a automação usando uma [versão modificada do Firefox com recursos contra detecção](https://github.com/daijro/camoufox).+ - A classe `PlayWrightFetcher`, para fazer solicitações com navegador usando PlayWright sem modificações, PlayWright com um modo de ocultação feito por mim, navegadores reais via CDP e o [NSTBrowser](https://app.nstbrowser.io/r/1vO5e5) com seu [docker browserless](https://hub.docker.com/r/nstbrowser/browserless)!+2. Adicionados os métodos totalmente novos `find_all`/`find` para encontrar elementos na página com facilidade e um pouco de magia negra!+3. Adicionados os métodos `filter` e `search` à classe `Adaptors` para facilitar operações em lote com grupos de objetos `Adaptor`.+4. Adicionados os métodos `css_first` e `xpath_first` para facilitar o uso.+5. Adicionada a nova classe `TextHandlers`, usada em operações em lote com objetos `TextHandler`, assim como a classe `Adaptors`.+6. Adicionados os métodos `generate_full_css_selector` e `generate_full_xpath_selector`.++##### Correções de erros {#v0.2-bugs-squashed}+1. Na classe `Adaptors`, `re_first` agora retorna a primeira correspondência entre todos os objetos `Adaptor` que ela contém, em vez de retornar por engano os resultados de `re_first` de todos os objetos `Adaptor`.+2. Se você selecionar conteúdo de texto dos elementos (como com a função CSS `::text`) por um método como `.css` ou `.xpath`, o objeto `Adaptor` agora retorna a classe `TextHandlers` em vez de uma lista de strings. Assim, você pode usar `page.css('something::text').re_first(r'regex_pattern').json()` em vez de `page.css('something::text')[0].re_first(r'regex_pattern').json()`+3. Os argumentos re/re_first de `Adaptor`/`Adaptors` agora são consistentes com os de `TextHandler`. Agora você tem os argumentos `clean_match` e `case_sensitive`.+4. O argumento `auto_match` está ativado por padrão ao criar `Adaptor`, mas você ainda precisa ativá-lo ao selecionar elementos se quiser usá-lo. (Não é um erro, e sim uma decisão de projeto)+5. Corrigidas várias anotações de tipos para melhorar o preenchimento automático ao programar com Scrapling.++##### Melhorias de uso {#v0.2-quality-of-life-changes}+1. Os métodos `css_selector` e `xpath_selector` foram renomeados para `generate_css_selector` e `generate_xpath_selector` para dar mais clareza e não atrapalhar o preenchimento automático ao programar.+2. Reorganizada a maior parte do código antigo em um subpacote `core`, junto com outras decisões de projeto para facilitar a manutenção futura.+3. Reorganizada a pasta de testes e adicionados testes dos novos recursos. Agora os ambientes do tox ficam em cache no GitHub para acelerar os testes automáticos de cada commit.++## [v0.1.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.2) - 2024-10-16 {#v0.1.2}++**Histórico de mudanças**:++- Corrigido um erro que impedia o argumento `keep_comments` de funcionar como deveria.+- Ajustada a função de texto para remover automaticamente comentários HTML dos elementos antes de extrair seu texto e evitar o comportamento diferente do Lxml. Por exemplo:++ ```python+ >>> page = Adaptor('<span>CONDITION: <!-- -->Excellent</span>', keep_comments=True)+ >>> page.css('span::text')+ ['CONDITION: ', 'Excellent']+ ```++ Antes, esse era o resultado por causa do comportamento padrão do Lxml, mas agora ele retorna o texto completo 'CONDITION: Excellent'+ Esse comportamento também é conhecido no parsel\scrapy, então quis tratá-lo aqui.++- Corrigido um erro que impedia a remoção do arquivo de banco de dados SQLite criado pela biblioteca ao executar `pip uninstall scrapling` ou um comando semelhante.++## [v0.1.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.1) - 2024-10-14 {#v0.1.1}++Pequenas correções++## [v0.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1) - 2024-10-13 {#v0.1}++**Histórico completo de mudanças**: <https://github.com/D4Vinci/Scrapling/commits/v0.1>diff --git a/docs/locales/ru/changelog.md b/docs/locales/ru/changelog.mdnew file mode 100644index 0000000..127efa8--- /dev/null+++ b/docs/locales/ru/changelog.md@@ -0,0 +1,1279 @@+---+title: "История изменений Scrapling"+description: "Заметки о выпусках Scrapling: новые возможности, исправления и несовместимые изменения."+---++# История изменений {#changelog}++Все заметные изменения в Scrapling из [выпусков на GitHub](https://github.com/D4Vinci/Scrapling/releases).++## [v0.4.15](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.15) - 2026-08-23 {#v0.4.15}++**Один из крупнейших выпусков в этом году: переработанный MCP-сервер, Markdown для RAG одной строкой, улучшенное прохождение проверок Cloudflare и вкладки браузера, которые остаются открытыми для автоматизации 🚀**++!!! warning "Внимание"++ **Этот выпуск вносит несовместимые изменения в MCP-сервер. Перед обновлением прочитайте раздел [несовместимых изменений](https://github.com/D4Vinci/Scrapling/blob/v0.4.15/docs/ai/mcp-server.md#breaking-changes).**++### 🚀 Новые возможности и улучшения удобства {#v0.4.15-new-stuff-and-quality-of-life-changes}++- **Вкладки браузера теперь остаются открытыми и используются повторно между запросами** (см. [документацию](fetching/stealthy.md#session-management)):+ - Все браузерные сессии сохраняют вкладки после запроса. Следующий запрос использует свободную вкладку, а не открывает новую.+ - Каждый запрос заново применяет свои настройки к полученной вкладке: тайм-ауты, заголовки и блокировку ресурсов. Поэтому настройки не переходят из одного запроса в другой.+ - Вкладки с ошибками закрываются и заменяются новыми. Новый метод `close_pages()` закрывает все открытые вкладки.+ - Полученная страница остаётся загруженной, поэтому функция `page_setup` следующего запроса выполняется на ней до перехода на другой адрес. Это позволяет связывать автоматические действия между запросами.++- **Преобразуйте любую страницу в чистый Markdown для LLM с помощью `Response.markdown()`** (см. [документацию](ai/building-rag-systems.md)):++ ```python+ from scrapling.fetchers import Fetcher++ markdown = Fetcher.get("https://example.com").markdown(main_content_only=True)+ ```++ - Сначала всегда удаляются скрипты, стили и скрытое содержимое с внедрёнными инструкциями для модели. Такую же очистку выполняет MCP-сервер.+ - Передайте `css_selector`, чтобы преобразовать только нужные элементы.+ - Функция доступна в новой группе зависимостей `rag` (`pip install "scrapling[rag]"`), которая также входит в группы `ai`/`shell`/`all`.++- **Новый шаблон `SiteToMarkdownSpider` обходит весь сайт и создаёт набор Markdown-документов для RAG-конвейеров** (см. [документацию](ai/building-rag-systems.md)):++ ```python+ from scrapling.spiders import SiteToMarkdownSpider++ class DocsSpider(SiteToMarkdownSpider):+ name = "docs"+ start_urls = ["https://example.com/docs/"]+ allowed_domains = {"example.com"}+ output_dir = "docs_markdown"++ result = DocsSpider().start()+ result.items.to_jsonl("docs.jsonl")+ ```++ - Выдаёт один элемент на страницу с полями `url`/`title`/`markdown`. Необязательный параметр `output_dir` позволяет записывать каждую страницу в отдельный Markdown-файл.+ - `max_pages` ограничивает число страниц при обходе. Шаблон основан на `CrawlSpider`, поэтому, переопределив `rules()`, вы можете полностью управлять выбором ссылок для перехода.++- **MCP-сервер переработан (есть несовместимые изменения)** (см. [несовместимые изменения](https://github.com/D4Vinci/Scrapling/blob/v0.4.15/docs/ai/mcp-server.md#breaking-changes) и [документацию](ai/mcp-server.md)):+ - 13 инструментов теперь разделены на два режима: инструменты для разовых запросов (`fetch`, `bulk_fetch`, `stealthy_fetch`, `bulk_stealthy_fetch`), которые всегда запускают свой браузер и показывают реальные настройки по умолчанию, и инструменты сессий, которые используют однажды открытую сессию.+ - Новый инструмент `session_fetch` получает страницы через браузерную сессию. `open_session` теперь хранит только настройки уровня браузера и возвращает ИИ-агенту фактические настройки сессии.+ - Инструмент `get` переименован в `make_request` и теперь поддерживает любой HTTP-метод.+ - Новые инструменты `open_request_session` и `session_make_request` дают ИИ постоянные HTTP-сессии, которые сохраняют cookie и отпечаток браузера между запросами.+ - Это также устраняет сброс настроек сессии при получении страниц. Первое исправление этой проблемы внесено @Yigtwxx в [#418](https://github.com/D4Vinci/Scrapling/pull/418).++- **HTTP-транспорт MCP-сервера теперь требует аутентификации и по умолчанию привязан к localhost (несовместимое изменение)**. Изменение от @yamantaka-singh в [#414](https://github.com/D4Vinci/Scrapling/pull/414) (исправляет [#413](https://github.com/D4Vinci/Scrapling/issues/413), см. [документацию](ai/mcp-server.md#authentication)):+ - Передайте `--auth-token` (или переменную окружения `SCRAPLING_MCP_AUTH_TOKEN`), чтобы требовать Bearer-токен, либо `--no-auth`, чтобы явно запустить сервер без аутентификации.+ - Передайте `--host 0.0.0.0`, чтобы принимать подключения из сети.++### 🐛 Исправления ошибок {#v0.4.15-bug-fixes}++- **Проверки Cloudflare Turnstile/Interstitial теперь проходят независимо от локали браузера, а интерактивные проверки больше не вызывают бесконечный цикл в режиме без окна**. Страницы скрытного браузера также перестали падать во время проверки. Включены изменения от @subediparas5 в [#412](https://github.com/D4Vinci/Scrapling/pull/412). (Исправляет [#411](https://github.com/D4Vinci/Scrapling/issues/411) и [#422](https://github.com/D4Vinci/Scrapling/issues/422).)+- **Исправлен незаметный пропуск элементов с несколькими классами в `find`/`find_all` при использовании `class_`**. Изменение от @yetval в [#410](https://github.com/D4Vinci/Scrapling/pull/410). **Также исправлена обработка пустых значений `class_` и неэкранированных строковых значений CSS**. Изменение от @yamantaka-singh в [#417](https://github.com/D4Vinci/Scrapling/pull/417).+- **Исправлена потеря метаданных запроса при повторном использовании кешированных ответов в `development_mode`**. Изменение от @Yigtwxx в [#419](https://github.com/D4Vinci/Scrapling/pull/419).+- **Исправлена ошибка HTTP-запросов с `retries` меньше 1: запрос завершался с ошибкой ещё до отправки**. Изменение от @Yigtwxx в [#420](https://github.com/D4Vinci/Scrapling/pull/420).++### Документация {#v0.4.15-docs}++- **Разделы сайта перестроены**: новый раздел «Использование с ИИ» содержит MCP-сервер, новую страницу [Agent Skill](ai/agent-skill.md) и руководство [Создание RAG-систем](ai/building-rag-systems.md). Руководство по переходу с BeautifulSoup перенесено к интеграции со Scrapy в раздел «Интеграции и переход».+- **В репозиторий добавлена [история изменений](changelog.md)** с заметками обо всех выпусках.++## [v0.4.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.14) - 2026-08-10 {#v0.4.14}++**Небольшой технический выпуск для исправления установки через `uv` 🔧**++### 🐛 Исправления ошибок {#v0.4.14-bug-fixes}++- **Исправлена проблема, из-за которой `uv` по умолчанию отказывался устанавливать v0.4.13 и незаметно выбирал более старую версию**. Предыдущий выпуск требовал предварительную версию `curl_cffi`, а `uv` не разрешает такие версии без явного включения.+Теперь для всех зависимостей доступны стабильные версии. (Исправляет [#407](https://github.com/D4Vinci/Scrapling/issues/407).)++## [v0.4.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.13) - 2026-08-09 {#v0.4.13}++**Новое обновление с пауками для фидов и более умным MCP-сервером 🎉**++### 🚀 Новые возможности и улучшения удобства {#v0.4.13-new-stuff-and-quality-of-life-changes}++- **Новые шаблоны пауков для фидов**. `XMLFeedSpider` перебирает узлы любого XML-фида (RSS, Atom, товарные фиды и т. д.), а `CSVFeedSpider` перебирает строки CSV как словари. Оба автоматически распаковывают фиды, сжатые gzip. (См. [документацию](spiders/generic-templates.md).)++ ```python+ from scrapling.spiders import XMLFeedSpider++ class RSSSpider(XMLFeedSpider):+ name = "rss"+ start_urls = ["https://example.com/feed.xml"]++ async def parse_node(self, response, node):+ yield {"title": node.findtext("title"), "link": node.findtext("link")}++ result = RSSSpider().start()+ ```++- **MCP-сервер обновлён до MCP SDK v2 и стал умнее**. Теперь сервер содержит инструкции, которые учат ИИ-агента эффективно использовать инструменты. Каждый инструмент объявляет аннотации, чтобы клиенты вроде Claude Code могли автоматически разрешать действия только для чтения. Описания инструментов сокращены для экономии токенов. Сервер также сообщает MCP-клиентам свою версию и логотип. (См. [документацию](ai/mcp-server.md).)+- **Добавлена команда `scrapling-mcp`**, которая напрямую соответствует `scrapling mcp`. Теперь Scrapling можно зарегистрировать одной строкой в MCP-клиентах и реестрах, ожидающих одну команду.+- **Снята фиксация версий Playwright/Patchright и браузеров**. Создаваемый User-Agent браузера теперь всегда точно соответствует версии Chromium, которой управляет установленный Playwright/Patchright. Поэтому Scrapling больше не фиксирует их версии, и вы можете свободно их обновлять. После обновления выполните `scrapling install --force`, чтобы обновить браузеры.++### 🐛 Исправления ошибок {#v0.4.13-bug-fixes}++- **Исправлено падение при импорте Scrapling с ошибкой ValueError из `browserforge`**, когда пакет данных отпечатков отстаёт от версий браузеров. (Исправляет [#394](https://github.com/D4Vinci/Scrapling/issues/394), [#396](https://github.com/D4Vinci/Scrapling/issues/396) и [#400](https://github.com/D4Vinci/Scrapling/issues/400).)+- **Исправлен неверный размер пулов страниц в инструментах MCP для пакетной работы с браузером**. Из-за него `bulk_fetch` завершался ошибкой при обработке более 50 URL за раз, а `bulk_stealthy_fetch` получал все URL через одну вкладку. Изменение от @Yigtwxx в [#393](https://github.com/D4Vinci/Scrapling/pull/393).++### Проект {#v0.4.13-project}++- **Новая [политика участия с помощью ИИ](https://github.com/D4Vinci/Scrapling/blob/main/AI_POLICY.md)**: вклад с помощью ИИ приветствуется, но его использование нужно указывать в PR или Issue. Материалы, похожие на результат работы ИИ без такого указания, будут помечены и закрыты.++## [v0.4.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.12) - 2026-07-26 {#v0.4.12}++**Выпуск, который помогает паукам лучше учитывать особенности сайтов при обходе**++### 🚀 Новые возможности и улучшения удобства {#v0.4.12-new-stuff-and-quality-of-life-changes}++- **Пауки теперь могут сами регулировать скорость с помощью AutoThrottle.** Вместо подбора `download_delay`, который может быть слишком большим или приводить к блокировке, паук измеряет скорость ответа каждого сайта и сам меняет задержку для каждого домена. Если сайт начинает блокировать запросы или ограничивать их частоту, паук удваивает задержку (или ждёт ровно столько, сколько указано в заголовке `Retry-After`), пока ограничения не исчезнут, а затем снова ускоряется. Ваши `download_delay` и `Crawl-delay` из robots.txt по-прежнему задают минимальную задержку. (См. [документацию](spiders/advanced.md#autothrottle).)++ ```python+ class MySpider(Spider):+ name = "adaptive"+ start_urls = ["https://example.com"]+ autothrottle_enabled = True+ autothrottle_start_delay = 2.0+ autothrottle_max_delay = 30.0+ autothrottle_block_backoff = True+ ```++- **Результаты можно экспортировать в CSV и XML**, помимо уже доступных JSON/JSONL. Даже если у элементов разные ключи, они экспортируются без потери данных, а вложенные значения записываются как JSON. (См. [документацию](spiders/getting-started.md).)++ ```python+ result = MySpider().start()+ result.items.to_csv("products.csv")+ result.items.to_xml("products.xml")+ ```++- **MCP-сервер теперь может требовать аутентификации**, поэтому его можно безопасно открыть для внешних подключений, а не оставлять только на своём компьютере. Запросы без токена отклоняются. Также можно ограничить имена хостов, на которые отвечает сервер. (См. [документацию](ai/mcp-server.md).)++ ```bash+ scrapling mcp --http --auth-token "$(openssl rand -hex 32)"+ ```++- **Браузеры теперь принимают CDP URL по HTTP**, а не только по WebSocket. Помимо адресов `wss://` от браузерных сервисов, любой браузерный Fetcher или MCP-сессию можно подключить к Chrome, который вы сами запустили с `--remote-debugging-port=9222`.++- **Публикуемые Docker-образы теперь имеют тег версии выпуска**, а не только `latest`, чтобы вы могли выбрать точную версию. Изменение от @JanRK в [#384](https://github.com/D4Vinci/Scrapling/pull/384).++### 🐛 Исправления ошибок {#v0.4.12-bug-fixes}++- **Исправлена потеря всех cookie при кешировании ответов браузерного движка**. В режиме разработки пауков это незаметно нарушало работу сессий и аутентификации, которые зависели от cookie. Изменение от @amitvijapur в [#379](https://github.com/D4Vinci/Scrapling/pull/379). (Исправляет [#376](https://github.com/D4Vinci/Scrapling/issues/376).)++- **Исправлена проблема в `StealthyFetcher`, который принудительно задавал локаль `en-US`** для всех браузеров вместо локали системы. Из-за несовпадения локали и IP-адреса сайты считали запросы подозрительными, например Google отвечал кодом 429. (Исправляет [#381](https://github.com/D4Vinci/Scrapling/issues/381).)++- **Исправлено вводящее в заблуждение сообщение об ошибке в системе хранения** и удалён ненужный вызов после вставки данных. Изменение от @fix2015 в [#377](https://github.com/D4Vinci/Scrapling/pull/377).++### Производительность {#v0.4.12-performance}++- **Время работы `get_all_text()` теперь растёт пропорционально числу узлов, O(nodes)**. Метод больше не обходит предков каждого текстового узла, поэтому на страницах с глубокой вложенностью работает примерно в 5-6 раз быстрее. Изменение от @yetval в [#378](https://github.com/D4Vinci/Scrapling/pull/378).++## [v0.4.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.11) - 2026-07-12 {#v0.4.11}++**Большое обновление: первый шаблон паука для платформы, более быстрый парсер и важные исправления 🎉**++### 🚀 Новые возможности и улучшения удобства {#v0.4.11-new-stuff-and-quality-of-life-changes}++- **Добавлен `ShopifySpider`, первый шаблон паука для платформы!** Извлекайте все товары из любого магазина на Shopify через его JSON API, не работая с HTML сайта. Создайте подкласс, задайте домен магазина, и всё готово (см. [документацию](spiders/platform-templates.md)).++ ```python+ from scrapling.spiders import ShopifySpider++ class MyStore(ShopifySpider):+ target_website = "example.com"++ result = MyStore().start()+ ```++- **В браузерные команды CLI добавлен `--executable-path`**. И `scrapling extract fetch`, и `scrapling extract stealthy-fetch` теперь принимают путь к исполняемому файлу любого Chromium-совместимого браузера. Если параметр не передан, используется переменная окружения `SCRAPLING_EXECUTABLE_PATH`, как и в MCP-сервере (решает [#371](https://github.com/D4Vinci/Scrapling/issues/371)).++ ```bash+ scrapling extract fetch "https://example.com" page.html --executable-path "/path/to/chromium"+ ```++### 🤖 Улучшения удобства {#v0.4.11-quality-of-life-changes}+- **`find_by_text` и `find_by_regex` теперь работают до ~2 раз быстрее** при включённом `first_match` (по умолчанию). Объекты для элементов создаются только по мере необходимости, поэтому поиск останавливается на первом совпадении. Изменение от @yetval в [#370](https://github.com/D4Vinci/Scrapling/pull/370).+- **Бенчмарки обновлены: новые результаты сравниваются с последними версиями всех библиотек.**+- **Обновлены правила участия в проекте.**++### 🐛 Исправления ошибок {#v0.4.11-bug-fixes}++- **Исправлено падение инструментов получения страниц MCP-сервера на страницах с управляющими символами** с ошибкой `All strings must be XML compatible`. Изменение от @yetval в [#368](https://github.com/D4Vinci/Scrapling/pull/368) (исправляет [#366](https://github.com/D4Vinci/Scrapling/issues/366)).++## [v0.4.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.10) - 2026-07-04 {#v0.4.10}++**Новое обновление с интеграцией со Scrapy и набором исправлений от сообщества 🎉**++### 🚀 Новые возможности и улучшения удобства {#v0.4.10-new-stuff-and-quality-of-life-changes}++- **Добавлена интеграция со Scrapy**, чтобы использовать API парсинга Scrapling в существующих проектах Scrapy без переписывания. Добавьте декоратор `scrapling_response` к любому обработчику паука, и получаемый им ответ станет объектом `Response` из Scrapling. Сам обход по-прежнему выполняет Scrapy (см. [документацию](integrations/scrapy.md)):++ ```python+ import scrapy+ from scrapling.integrations.scrapy import scrapling_response++ class QuotesSpider(scrapy.Spider):+ name = "quotes"+ start_urls = ["https://quotes.toscrape.com"]++ @scrapling_response+ def parse(self, response): # `response` is now a Scrapling Response+ first_quote = response.find_by_text("The world as we have created it", partial=True)+ for quote in [first_quote, *first_quote.find_similar()]:+ yield {"text": quote.get_all_text(strip=True)}+ ```++- **MCP-сервер теперь поддерживает любой Chromium-совместимый браузер** во всех браузерных инструментах. Задайте его один раз через `scrapling mcp --executable-path "/path/to/chromium"` или переменную окружения `SCRAPLING_EXECUTABLE_PATH`, либо для отдельного запроса через аргумент `executable_path`. Изменение от @samrusani в [#360](https://github.com/D4Vinci/Scrapling/pull/360) (решает [#347](https://github.com/D4Vinci/Scrapling/issues/347)).+- **Обновлены все браузеры и отпечатки**. После обновления выполните `scrapling install --force`, чтобы применить изменения.++### 🐛 Исправления ошибок {#v0.4.10-bug-fixes}++- **Исправлён искажённый текст (mojibake) в ответах браузерных Fetcher на сайтах с кодировкой не UTF-8**. Изменение от @yehudalevy-collab в [#365](https://github.com/D4Vinci/Scrapling/pull/365) (исправляет [#364](https://github.com/D4Vinci/Scrapling/issues/364)).+- **Исправлена проблема в `LinkExtractor`, который не отфильтровывал составные расширения вроде `.tar.gz`**. Изменение от @renbkna в [#359](https://github.com/D4Vinci/Scrapling/pull/359) (исправляет [#349](https://github.com/D4Vinci/Scrapling/issues/349)).+- **Исправлена потеря выполняющихся запросов из контрольных точек при паузе обхода: теперь при возобновлении они не пропускаются**. Изменение от @yetval в [#358](https://github.com/D4Vinci/Scrapling/pull/358).+- **Исправлен неверный расчёт задержек обхода по директивам `Request-rate` из robots.txt** благодаря обновлению Protego. Соответствующее обновление тестов от @Disaster-Terminator внесено в [#355](https://github.com/D4Vinci/Scrapling/pull/355).++### Документация {#v0.4.10-docs}++- **Уточнено взаимодействие `init_script` с изолированным контекстом выполнения Patchright в скрытном режиме**. Изменение от @mturac в [#353](https://github.com/D4Vinci/Scrapling/pull/353) (решает [#350](https://github.com/D4Vinci/Scrapling/issues/350)).+- **Добавлен способ установки навыка через [skills.sh](https://skills.sh/D4Vinci/Scrapling)**. Изменение от @ob-aion в [#363](https://github.com/D4Vinci/Scrapling/pull/363).++## [v0.4.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.9) - 2026-06-07 {#v0.4.9}++**Техническое обновление с множеством исправлений по сообщениям сообщества 🛠️**++### 🚀 Новые возможности и улучшения удобства {#v0.4.9-new-stuff-and-quality-of-life-changes}++- **Обновлены все браузеры и отпечатки**. После обновления выполните `scrapling install --force`, чтобы применить изменения.+- **В CLI добавлен флаг `--version`**. Изменение от @ETM-Code в [#303](https://github.com/D4Vinci/Scrapling/pull/303) (решает [#299](https://github.com/D4Vinci/Scrapling/issues/299)).++### 🐛 Исправления ошибок {#v0.4.9-bug-fixes}++- **Исправлено незаметное игнорирование аргумента `proxy` уровня сессии в HTTP-сессиях**, которое могло раскрыть ваш настоящий IP (решает [#295](https://github.com/D4Vinci/Scrapling/issues/295)). Теперь смешивание `proxy` уровня сессии с `proxies` отдельного запроса (или наоборот) вызывает ошибку, а не незаметно отбрасывает один из аргументов.+- **Исправлены сбои переходов браузера при сочетании `init_script` с `user_data_dir`** (решает [#294](https://github.com/D4Vinci/Scrapling/issues/294)).+- **Исправлено определение кодировки, когда сайт заключает значение charset в кавычки в заголовке `Content-Type`**. Изменение от @Bortlesboat в [#323](https://github.com/D4Vinci/Scrapling/pull/323).+- **Исправлена ошибка `IndexError` при адаптивном поиске элементов с включённым `auto_save`**. Изменение от @Mubashirrrr в [#340](https://github.com/D4Vinci/Scrapling/pull/340).+- **Исправлено падение при сохранении контрольных точек и кеша пауков в Windows**. Изменение от @MrStarkEG в [#344](https://github.com/D4Vinci/Scrapling/pull/344).+- **Исправлена неверная оценка сходства в `find_similar` для элементов с разным количеством атрибутов** (решает [#322](https://github.com/D4Vinci/Scrapling/issues/322)).++### Документация {#v0.4.9-docs}++- **Уточнено, что установка по умолчанию включает только парсер**, а для Fetcher и пауков нужны дополнительные группы зависимостей (решает [#343](https://github.com/D4Vinci/Scrapling/issues/343)).+- **Исправлено имя Docker-образа в оставшихся примерах**. Изменение от @evanclan в [#315](https://github.com/D4Vinci/Scrapling/pull/315).+- **Исправлена неработающая ссылка в руководстве по участию**. Изменение от @Bortlesboat в [#320](https://github.com/D4Vinci/Scrapling/pull/320).++## [v0.4.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.8) - 2026-05-11 {#v0.4.8}++**Большое обновление пауков, которое расширяет возможности фреймворка для обхода сайтов 🕷️**++### 🚀 Новые возможности и улучшения удобства {#v0.4.8-new-stuff-and-quality-of-life-changes}++- **Добавлен инструмент `LinkExtractor`** в `scrapling.spiders.LinkExtractor` для извлечения URL из `Response`. Есть множество настроек (см. [документацию](spiders/generic-templates.md)).++ ```python+ from scrapling.spiders import LinkExtractor++ extractor = LinkExtractor(allow=r"/posts/", deny_domains=["ads.example.com"])+ ```++- **Добавлены универсальные шаблоны пауков `CrawlSpider` и `CrawlRule`**, чтобы не писать каждый раз один и тот же код для перехода по ссылкам, соответствующим шаблону. Переопределите `rules()`, чтобы вернуть список объектов `CrawlRule`, каждый из которых связан с `LinkExtractor`. (См. [документацию](spiders/generic-templates.md).)++ ```python+ from scrapling.spiders import CrawlSpider, CrawlRule, LinkExtractor++ class QuotesSpider(CrawlSpider):+ name = "blog"+ start_urls = ["https://quotes.toscrape.com/"]++ def rules(self):+ return [+ CrawlRule(LinkExtractor(allow=r"/author/"), callback=self.parse_author),+ CrawlRule(LinkExtractor(allow=r"/page/\d+/")), # pagination, no callback+ ]++ async def parse_author(self, response):+ yield {+ "name": response.css(".author-title::text").get(),+ "birthday": response.css(".author-born-date::text").get(),+ "url": response.url,+ }+ ```++- **Добавлен шаблон `SitemapSpider`**, который начинает обход прямо с URL карты сайта или `robots.txt`. Поддерживает карты сайта, сжатые gzip, и множество настроек. URL распределяются по правилам обхода, как в примере с **CrawlSpider** выше. (См. [документацию](spiders/generic-templates.md).)++ ```python+ from scrapling.spiders import SitemapSpider, CrawlRule, LinkExtractor++ class NewsSitemap(SitemapSpider):+ name = "news"+ sitemap_urls = ["https://example.com/robots.txt"]++ def rules(self):+ return [+ CrawlRule(LinkExtractor(allow=r"/articles/"), callback=self.parse_article),+ ]++ async def parse_article(self, response):+ yield {"url": response.url, "title": response.css("h1::text").get()}+ ```++- **Адаптивный поиск теперь использует порог сходства 40% по умолчанию** вместо `0` во всех методах. Это улучшает работу адаптивной функции. Если ни один элемент не превышает порог, предупреждение показывает максимальную найденную оценку, чтобы вы могли осознанно уменьшить `percentage`, если нужно.++- **Обновлены все браузеры и отпечатки**. После обновления снова выполните `scrapling install --force`, чтобы обновить браузеры и отпечатки.++### 🐛 Исправления ошибок {#v0.4.8-bug-fixes}++- **Исправлена ошибка: `Fetcher.configure(...)` не применялся к отдельным запросам**. Такое же исправление внесено в `AsyncFetcher`.+- **Исправлен неверный расчёт отпечатков запросов, из-за которого пауки отправляли повторяющиеся запросы**. Изменение от @yetval в [#255](https://github.com/D4Vinci/Scrapling/pull/255).+- **Исправлено отсутствие предупреждений при слабых совпадениях в движке адаптивного сбора данных.** Вместе с изменением порога выше это означает, что при неудачном поиске вы получите предупреждение, а не вводящий в заблуждение «наиболее подходящий» элемент.++### Документация {#v0.4.8-docs}++- **Обновлены старые примеры кода** во всей документации, чтобы они соответствовали текущей версии.+- **Улучшены копирование и вставка кода** на сайте документации. Навык агента сокращён, чтобы расходовать меньше токенов при каждом вызове.++## [v0.4.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.7) - 2026-04-17 {#v0.4.7}++**Обновление, которое даёт вашим ИИ-агентам возможность видеть страницы 📸**++### 🚀 Новые возможности и улучшения удобства {#v0.4.7-new-stuff-and-quality-of-life-changes}++- **Добавлен MCP-инструмент `screenshot`**, который делает снимок страницы и возвращает его как настоящий блок MCP `ImageContent`, чтобы модель могла его видеть. Нужна открытая браузерная сессия, поэтому сначала вызовите `open_session` (с типом `dynamic` или `stealthy`), а затем передайте сюда `session_id`. Поддерживаются PNG и JPEG, снимки всей страницы, настройка качества JPEG и обычные параметры ожидания (`wait`, `wait_selector`, `network_idle`, `timeout`). (Реализует [#244](https://github.com/D4Vinci/Scrapling/issues/244).)+- **Добавлен параметр для собственного `session_id` в `open_session`**, чтобы давать сессиям понятные имена (`"search"`, `"checkout"`) вместо случайной 12-символьной шестнадцатеричной строки по умолчанию. Изменение от @hauntedhost в [#243](https://github.com/D4Vinci/Scrapling/pull/243).++### 🐛 Исправления ошибок {#v0.4.7-bug-fixes}++- **Исправлены повреждение состояния `FetcherSession` и падение при закрытии сессии с отложенной инициализацией**. Изменение от @yetval в [#245](https://github.com/D4Vinci/Scrapling/pull/245).+- **Исправлена ошибка `TypeError: Session.request() got an unexpected keyword argument 'block_ads'`** при использовании флага CLI `--ai-targeted` с HTTP-командами. Изменение от @voidborne-d в [#249](https://github.com/D4Vinci/Scrapling/pull/249) (исправляет [#247](https://github.com/D4Vinci/Scrapling/issues/247)).++### Переводы {#v0.4.7-translations}++- **Добавлен перевод README на бразильский португальский** от @rgomids в [#250](https://github.com/D4Vinci/Scrapling/pull/250).++## [v0.4.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.6) - 2026-04-13 {#v0.4.6}++**Обновление скрытной работы браузера, конфиденциальности и удобства разработки 🔒**++### 🚀 Новые возможности и улучшения удобства {#v0.4.6-new-stuff-and-quality-of-life-changes}++- **Добавлена встроенная блокировка рекламы** для браузерных Fetcher. Передайте `block_ads=True`, чтобы блокировать запросы примерно к 3 500 известным рекламным и отслеживающим доменам при перехвате маршрута. Запрос сразу отменяется, без DNS и TCP. Можно сочетать с `blocked_domains` для собственных списков. MCP-сервер и режим CLI `--ai-targeted` включают это автоматически, чтобы экономить токены и ускорять загрузку страниц.++ ```python+ page = StealthyFetcher.fetch('https://example.com', block_ads=True)+ ```++- **Добавлена поддержка DNS-over-HTTPS** для предотвращения утечек DNS при использовании прокси. Передайте `dns_over_https=True`, чтобы отправлять DNS-запросы через DoH Cloudflare. Тогда определение адресов через DNS не раскроет ваше настоящее местоположение, даже если HTTP-трафик идёт через прокси.++ ```python+ page = StealthyFetcher.fetch('https://example.com', proxy='http://proxy:8080', dns_over_https=True)+ ```++- **Добавлен обработчик `page_setup`** для браузерных Fetcher. Эта функция запускается перед `page.goto()` и позволяет зарегистрировать обработчики событий, маршруты и скрипты, которые нужно настроить до перехода на страницу. Дополняет `page_action`, который запускается после перехода. (Решает [#237](https://github.com/D4Vinci/Scrapling/issues/237).)++ ```python+ def capture_websockets(page):+ page.on("websocket", lambda ws: print(f"WS: {ws.url}"))++ page = DynamicFetcher.fetch('https://example.com', page_setup=capture_websockets)+ ```++- **Добавлены параметры CLI `--block-ads` и `--dns-over-https`** для команд `fetch` и `stealthy-fetch`.++### 🐛 Исправления ошибок {#v0.4.6-bug-fixes}++- **Исправлен псевдоним типа `Seconds`**, который не принимал дробные значения. Передача `wait=1.5` или `timeout=500.0` в браузерные Fetcher вызывала ошибку типов, потому что псевдоним ошибочно считал `float` метаданными, а не типом. Изменение от @kuishou68 в [#240](https://github.com/D4Vinci/Scrapling/pull/240).+- **Исправлено дублирование частей с ID при генерации селектора полного пути**. При создании полных CSS/XPath-путей селекторы элементов с атрибутом `id` добавлялись дважды, что давало строки вроде `body > #main > #main > #target > #target`. Также исправлена генерация отдельного условия `[@id='x']` (недопустимый XPath) вместо `*[@id='x']` в полном пути XPath. Изменение от @sjhddh в [#241](https://github.com/D4Vinci/Scrapling/pull/241).+- **Добавлены недостающие параметры в сигнатуры функций оболочки**. В сигнатурах интерактивной оболочки отсутствовали `blocked_domains`, `block_ads`, `retries`, `retry_delay`, `capture_xhr`, `executable_path` и `dns_over_https`.++## [v0.4.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.5) - 2026-04-07 {#v0.4.5}++**Обновление с одной большой возможностью для удобства разработки пауков и несколькими важными исправлениями 🎉**++### 🚀 Новые возможности и улучшения удобства {#v0.4.5-new-stuff-and-quality-of-life-changes}++- **Режим разработки пауков**: раньше каждая проверка изменений в `parse()` требовала снова обращаться к целевым серверам. Это медленно, создаёт лишнюю нагрузку и может привести к ограничению запросов ещё во время подбора селекторов. Новый режим разработки кеширует каждый ответ на диск при первом запуске и читает ответы с диска при следующих запусках. Вы можете менять обработчики и запускать паука сколько угодно раз, не отправляя ни одного сетевого запроса. Для включения достаточно одного атрибута класса:++ ```python+ class MySpider(Spider):+ name = "my_spider"+ start_urls = ["https://example.com"]+ development_mode = True++ async def parse(self, response):+ yield {"title": response.css("title::text").get("")}+ ```++ По умолчанию кеш хранится в `.scrapling_cache/{spider.name}/`. Его можно перенести куда угодно с помощью `development_cache_dir`. Новые счётчики `cache_hits` и `cache_misses` показывают, как используется кеш. Чтение из кеша пропускает `download_delay`, ограничение частоты и повторы заблокированных запросов, поэтому скорость проверки изменений зависит только от диска. Не оставляйте `development_mode = True` у паука в рабочей среде: это инструмент разработки, а не рабочий кеш. Подробнее в [документации](spiders/advanced.md#development-mode).++- **Более безопасные перенаправления по умолчанию**: значение `follow_redirects` теперь равно `"safe"` во всех HTTP-Fetcher, MCP-сервере и оболочке. Перенаправления по-прежнему выполняются, но адреса с внутренними или частными IP (loopback, частные сети, link-local) отклоняются. Это защищает от SSRF при сборе данных по URL, полученным от пользователей. Передайте `follow_redirects="all"`, чтобы вернуть старое поведение, или `False`, чтобы полностью отключить перенаправления.++### 🐛 Исправления ошибок {#v0.4.5-bug-fixes}++- **При принудительной остановке больше не теряется контрольная точка**: двойное нажатие Ctrl+C (принудительная остановка) у паука с включённым `crawldir` могло совпасть с записью контрольной точки. Область отмены завершала задачу до окончания записи pickle, оставляя `paused=False` и запуская очистку, которая *удаляет* предыдущую контрольную точку. В результате принудительная остановка долгого обхода могла привести к потере всего прогресса, который вы хотели сохранить. Теперь движок записывает контрольную точку **до** вызова `cancel_scope.cancel()`, поэтому принудительная остановка всегда сохраняет последнее состояние ожидающих задач. Изменение от @voidborne-d в [#230](https://github.com/D4Vinci/Scrapling/pull/230).++## [v0.4.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.4) - 2026-04-05 {#v0.4.4}++**Новое обновление с важными улучшениями пауков и исправлениями ошибок 🎉**++### 🚀 Новые возможности и улучшения удобства {#v0.4.4-new-stuff-and-quality-of-life-changes}+- **Во фреймворк пауков добавлено соблюдение robots.txt** через новую настройку `robots_txt_obey`. При её включении паук сам получает robots.txt перед обходом и соблюдает правила, включая `Disallow`, `Crawl-delay` и `Request-rate`. Файлы robots.txt загружаются параллельно и кешируются для каждого домена на всё время обхода. Изменение от @AbdullahY36 в [#226](https://github.com/D4Vinci/Scrapling/pull/226).+- **Добавлена предварительная подготовка кеша robots.txt**: до начала цикла обхода файлы robots.txt загружаются и разбираются для всех доменов из start_urls. Это устраняет задержку при первом запросе к каждому домену.+- **Добавлен счётчик `robots_disallowed_count`** в `CrawlStats`, чтобы отслеживать число запросов, заблокированных правилами robots.txt во время обхода.++Подробнее на сайте по [этой ссылке](spiders/getting-started.md#robotstxt-compliance).++### 🐛 Исправления ошибок {#v0.4.4-bug-fixes}+- **Исправлена серьёзная проблема MRO в `ProxyRotator`**: заглушка `_build_context_with_proxy` перекрывала настоящую реализацию из дочерних классов, из-за чего смена прокси всегда вызывала `NotImplementedError` (исправляет [#215](https://github.com/D4Vinci/Scrapling/issues/215)). Спасибо @yetval.+- **Исправлена утечка в пуле страниц** при смене прокси для каждого запроса в браузерных сессиях. Страницы из временных контекстов не удалялись из пула при очистке, поэтому в нём накапливались устаревшие ссылки. Изменение от @yetval в [#223](https://github.com/D4Vinci/Scrapling/pull/223).+- **Добавлена недостающая проверка типа** в статическом Fetcher: `curl_cffi` мог вернуть `None` из `session.request()`, что вызывало ошибки в дальнейшей обработке.++### Другие изменения {#v0.4.4-other}+- Обновлены зависимости, включая свежие отпечатки и другие улучшения.+- Добавлена новая зависимость `protego` в необязательную группу `fetchers` для разбора robots.txt.++## [v0.4.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.3) - 2026-03-30 {#v0.4.3}++**Новое обновление с множеством важных изменений 🎉**++### 🚀 Новые возможности и улучшения удобства {#v0.4.3-new-stuff-and-quality-of-life-changes}+- **Добавлен новый MCP-инструмент**, который открывает обычный или скрытный браузер и оставляет его открытым для дальнейшей работы других инструментов. Ещё один новый инструмент закрывает его. ([Примеры](https://github.com/D4Vinci/Scrapling/blob/v0.4.3/docs/ai/mcp-server.md#examples).)+- **Добавлен новый MCP-инструмент** для просмотра списка всех открытых браузерных сессий. Предназначен для работы с новыми инструментами.+- **В браузерные сессии добавлена новая настройка**, которая автоматически собирает все фоновые запросы, возникающие во время запроса (решает [#159](https://github.com/D4Vinci/Scrapling/pull/159)) [[Примеры](https://github.com/D4Vinci/Scrapling/blob/v0.4.3/docs/fetching/dynamic.md#capturing-xhrfetch-requests)].+- **Добавлено новое средство очистки**, которое убирает скрытое и невидимое содержимое, защищая MCP-сервер от распространённых атак с внедрением инструкций в промпт.+- **В команды сбора данных добавлен новый параметр командной строки** `--ai-targeted`. Он подготавливает содержимое для ИИ и защищает от распространённых атак с внедрением инструкций в промпт, как MCP-сервер.+- **В браузерные сессии добавлена новая настройка** `executable_path`, которая позволяет задать собственный путь к браузеру (решает [#202](https://github.com/D4Vinci/Scrapling/pull/202)).+- **Переработан** код MCP-сервера для упрощения поддержки. Все инструменты стали асинхронными.+- **Переработан** код команд CLI для упрощения поддержки. Он стал короче на 210 строк.++### 🐛 Исправления ошибок {#v0.4.3-bug-fixes}+- Исправлено сохранение HTTP-метода при повторных попытках в сессии паука. Изменение от @karesansui-u в [#201](https://github.com/D4Vinci/Scrapling/pull/201).+- Добавлен предел числа повторных попыток получения содержимого страницы, чтобы избежать бесконечного цикла. Изменение от @haosenwang1018 и @D4Vinci в [#197](https://github.com/D4Vinci/Scrapling/pull/197).+- `raise` без аргумента заменён на `return False` в `_restore_from_checkpoint`. Изменение от @haosenwang1018 в [#196](https://github.com/D4Vinci/Scrapling/pull/196).+- `get_all` заменён на `getall` в `Texthandler`, чтобы соответствовать классу Selector.++### Улучшения тестов и покрытия {#v0.4.3-coverage-tests-improvement}+- Добавлены тесты пограничных случаев `_normalize_credentials`. Изменение от @Bortlesboat в [#192](https://github.com/D4Vinci/Scrapling/pull/192).+- Добавлены тесты сохранения с последующим получением тех же данных и тесты основного хранилища. Изменение от @haosenwang1018 в [#193](https://github.com/D4Vinci/Scrapling/pull/193).+- Добавлены тесты ветвей обработки регулярных выражений в `TextHandler` и метода `TextHandlers.re()`. Изменение от @haosenwang1018 в [#194](https://github.com/D4Vinci/Scrapling/pull/194).+- Добавлены тесты пограничных случаев для `filter`, `iterancestors` и `find_similar`. Изменение от @awanawana в [#200](https://github.com/D4Vinci/Scrapling/pull/200).++### Улучшения Agent Skill {#v0.4.3-agent-skill-improvement}+- Исправлены неработающие Markdown-ссылки в справочных материалах навыка. Изменение от @yetval в [#204](https://github.com/D4Vinci/Scrapling/pull/204).+- Улучшена структура навыка для прохождения проверки [Clawhub](https://clawhub.ai/d4vinci/scrapling-official).+- Навык теперь обязан использовать параметр `--ai-targeted` при сборе данных через командную строку.++### Улучшения документации {#v0.4.3-docs-improvement}+- Добавлен перевод README на корейский от @greatsk55 в [#187](https://github.com/D4Vinci/Scrapling/pull/187).+- Исправлены пробелы между символами CJK и латиницей в китайском и японском README.+- Исправлены неработающие ссылки, оставшиеся от старого дизайна сайта.++## [v0.4.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.2) - 2026-03-08 {#v0.4.2}++**Новое техническое обновление с важными изменениями**++#### Исправления ошибок {#v0.4.2-bug-fixes}+- Функция `get_all_text()` теперь получает и текстовые узлы после закрывающих тегов элементов. Благодаря этому MCP-сервер и команды видят текст, который раньше пропускали ([#168](https://github.com/D4Vinci/Scrapling/pull/168)). Спасибо @mhillebrand.+- Для Referer теперь используется URL главной страницы Google вместо URL поиска Google. Предыдущая логика была неверной и могла создавать признак для обнаружения по отпечатку ([#179](https://github.com/D4Vinci/Scrapling/pull/179)). Спасибо @Bortlesboat.+- Исправлена проблема с объединением дополнительных флагов во всех браузерах. Спасибо @rostchri.+- Исправлена проблема с подсказками типов, которая приводила к сбою в версиях Python ниже 3.12. (Решает [#163](https://github.com/D4Vinci/Scrapling/issues/163))++#### Прочее {#v0.4.2-other}+- Добавлен Agent Skill для Claude Code / OpenClaw и других инструментов с ИИ-агентами.+- Agent Skill добавлен в Clawhub.+- Все браузеры и Playwright обновлены до последних версий.+- Добавлен французский перевод основного файла README.++## [v0.4.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.1) - 2026-02-27 {#v0.4.1}++**Обновление со многими важными изменениями**++### 🚀 Новые возможности и улучшения удобства {#v0.4.1-new-stuff-and-quality-of-life-changes}+- **Повышена точность регулярных выражений** для обнаружения проверок Cloudflare (спасибо @Rinz27 [#133](https://github.com/D4Vinci/Scrapling/pull/133)).+- **Повышены скорость и эффективность** прохождения проверок Cloudflare. Теперь они проходят почти вдвое быстрее.+- **Улучшено прохождение проверок Cloudflare** для сайтов, которые иногда дважды показывают страницу Cloudflare, прежде чем перейти к основному сайту.+- **Скрытный браузер стал быстрее и менее заметным** благодаря удалению внедряемых JS-файлов.+- **Улучшена схема MCP**, чтобы её принимал OpenCode (спасибо @robin-ede [#137](https://github.com/D4Vinci/Scrapling/pull/137)).+- **Улучшена совместимость схемы MCP**, чтобы её принимали VS Code Copilot и другие инструменты со строгими требованиями. (Решает #150)+- **Значительно сокращён расход токенов MCP-сервером**: при включённом параметре `main_content_only` удаляются бесполезные HTML-теги.+- Исправлена страница PyPI и добавлены файлы для регистрации MCP-сервера в реестре MCP-серверов.+- Добавлен пример установки зависимостей браузеров из кода, а не из командной строки, чтобы упростить автоматизацию.+- Во всех рабочих процессах actions обновлены до последних версий (спасибо @salmanmkc [#143](https://github.com/D4Vinci/Scrapling/pull/143)/[#144](https://github.com/D4Vinci/Scrapling/pull/144)).++## [v0.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4) - 2026-02-15 {#v0.4}++**Крупнейший выпуск Scrapling: система пауков, ротация прокси и значительные улучшения парсера**++В этом выпуске появились полностью асинхронный фреймворк для обхода сайтов, умное управление прокси и важные изменения API. Они расширяют возможности Scrapling и делают его API единообразнее. Перед обновлением внимательно прочитайте раздел о несовместимых изменениях.++### 🕷️ Система пауков {#v0.4-spider-framework}++Новый асинхронный фреймворк на основе `anyio` для организованного сбора данных в больших объёмах:++```python+from scrapling.spiders import Spider, Response++class MySpider(Spider):+ name = "demo"+ start_urls = ["https://example.com/"]++ async def parse(self, response: Response):+ for item in response.css('.product'):+ yield {"title": item.css('h2::text').get()}++MySpider().start()+```++- **API пауков в стиле Scrapy**: создавайте пауков с `start_urls`, асинхронными обработчиками `parse`, объектами `Request`/`Response` и очередью с приоритетами.+- **Одновременный обход**: настраиваемые ограничения числа одновременных запросов, ограничение скорости для каждого домена и задержки загрузки.+- **Поддержка нескольких сессий**: общий интерфейс для HTTP-запросов и скрытных браузеров в режиме без окна в одном пауке. Запросы направляются в разные сессии по ID. Сессии можно инициализировать только при необходимости.+- **Пауза и возобновление**: состояние обхода сохраняется в контрольных точках. Нажмите Ctrl+C для корректной остановки, затем запустите паука снова, чтобы продолжить с места остановки.+- **Потоковый режим**: получайте собранные записи по мере их поступления через `async for item in spider.stream()`, со статистикой в реальном времени. Подходит для интерфейсов, конвейеров обработки данных и длительного обхода.+- **Обнаружение заблокированных запросов**: автоматическое обнаружение и повторение заблокированных запросов с настраиваемой логикой.+- **Встроенный экспорт**: выгружайте результаты через хуки и собственный конвейер либо используйте встроенный экспорт в JSON/JSONL через `result.items.to_json()` / `result.items.to_jsonl()` соответственно.+- **Хуки жизненного цикла**: `on_start()`, `on_close()`, `on_error()`, `on_scraped_item()` и другие хуки позволяют полностью управлять жизненным циклом обхода.+- **Подробная статистика обхода**: запросы, ответы, байты, коды состояния, прокси, данные по доменам и сессиям, число записей каждого уровня логирования и многое другое.+- **Поддержка uvloop**: передайте `use_uvloop=True` в `spider.start()`, чтобы ускорить асинхронное выполнение, если uvloop доступен.++На сайте появился новый раздел с полной информацией. Откройте его [здесь](spiders/architecture.md).++### 🔄 Ротация прокси {#v0.4-proxy-rotation}++* Новый класс `ProxyRotator` с потокобезопасной сменой прокси. Работает со всеми Fetcher и сессиями:++ ```python+ from scrapling import ProxyRotator+ rotator = ProxyRotator(["http://proxy1:8080", "http://proxy2:8080"])+ Fetcher.get(url, proxy_rotator=rotator)+ ```++* **Свои стратегии ротации**: задайте собственную логику смены прокси.+* **Прокси для отдельного запроса**: передайте `proxy=` в отдельный вызов `get()`/`post()`/`fetch()`, чтобы заменить прокси сессии только для этого запроса.++### 🌐 Улучшения браузерных Fetcher {#v0.4-browser-fetcher-improvements}++* **Блокировка доменов**: новый параметр `blocked_domains` в `DynamicFetcher`/`StealthyFetcher` блокирует запросы к указанным доменам. Поддомены учитываются автоматически.+* **Автоматические повторные попытки**: браузерные Fetcher теперь повторяют запросы при ошибке. Это настраивается параметрами `retries` (по умолчанию: 3) и `retry_delay` (по умолчанию: 1s). Поддерживается обнаружение ошибок, связанных с прокси.+* **Метаданные ответа**: словарь `Response.meta` автоматически сохраняет использованный прокси и объединяет метаданные запроса.+* **Response.follow()**: создаёт объекты `Request` для следующих запросов с автоматической передачей Referer. Разработан для системы пауков.+* **Без автовоспроизведения**: браузерные сессии теперь блокируют автоматическое воспроизведение контента, которое раньше вызывало проблемы.+* **Скорость**: настройки флагов браузера улучшили скрытность и скорость.++### 🔧 Исправления ошибок и улучшения {#v0.4-bug-fixes-improvements}+- **Оптимизация парсера**: ускорены повторяющиеся операции парсера.+- **Ошибки страниц**: исправлена ошибка, из-за которой браузер не закрывался при ошибке на странице.+- **Пустое тело ответа**: добавлена обработка ответов с пустым телом.+- **Цикл событий Playwright**: решена проблема с незакрытым циклом событий Playwright при сбое подключения по CDP.+- **Безопасность типов**: исправлены все ошибки mypy и добавлены подсказки типов в тела функций без аннотаций. В рабочий процесс CI добавлены mypy и pyright.++### ⚠️ Несовместимые изменения {#v0.4-breaking-changes}++* **Удалены `css_first`/`xpath_first`**: используйте `css('.selector').first`, `css('.selector')[0]` или `css('.selector').get()`.+* **Все операции выбора теперь возвращают `Selectors`**: `css('::text')`, `xpath('//text()')`, `css('::attr(href)')` и `xpath('//@href')` теперь возвращают `Selectors`. Текстовые узлы оборачиваются в объекты `Selector` с `tag="#text"`, а не возвращаются как `TextHandlers`. Это делает API и подсказки типов единообразными для всех методов выбора.+* **`Response.body` всегда имеет тип `bytes`**: раньше это мог быть `str` или `bytes`, теперь всегда возвращается `bytes`.+* **Поведение `get()`/`getall()`**: у `Selector` метод `get()` возвращает `TextHandler` (сериализованный HTML или текстовое значение), а `getall()` возвращает `TextHandlers`. Псевдонимы: `extract_first = get`, `extract = getall`. Старый метод `get_all()` удалён из `Selectors`.+* **`Selectors.first`/`.last`**: безопасный доступ к элементам с возвратом `Selector | None` вместо ошибки `IndexError`.+* **Переименованы внутренние константы**: `DEFAULT_FLAGS` → `DEFAULT_ARGS`, `DEFAULT_STEALTH_FLAGS` → `STEALTH_ARGS`, `HARMFUL_DEFAULT_ARGS` → `HARMFUL_ARGS`, `DEFAULT_DISABLED_RESOURCES` → `EXTRA_RESOURCES`.++### 🔨 Прочие изменения {#v0.4-other-changes}++* **Изменения зависимостей**: `tldextract` заменён на `tld`, внутренний модуль `_html_utils.py` удалён в пользу `w3lib.html.replace_entities`, а `typing_extensions` стал обязательной зависимостью.+* **Полное обновление документации**: полный переход с MkDocs на Zensical, новый раздел о пауках, обновление всех существующих страниц и новые справочники API.++## [v0.3.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.14) - 2026-01-03 {#v0.3.14}++**Небольшое техническое обновление для исправления проблем v0.3.13 на некоторых устройствах**++- Режим инкогнито отключён в `StealthyFetcher` и его классах сессий, так как из-за него cookie не сохранялись между страницами на устройствах Windows. На MacOS и Linux этой проблемы не было (исправляет [#123](https://github.com/D4Vinci/Scrapling/issues/123), спасибо @frugality4121 за сообщение и @gembleman за решение).+- Закреплена последняя версия browserforge, чтобы решить проблему со старыми моделями заголовков у пользователей, у которых уже установлена старая версия browserforge.++## [v0.3.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.13) - 2026-01-01 {#v0.3.13}++**Это крупное обновление с улучшениями во многих частях библиотеки. Оно также содержит много необходимых несовместимых изменений. Прочитайте информацию ниже перед обновлением**++* По ряду причин мы решили полностью отказаться от Camoufox. В будущем мы можем вернуться к нему, если его разработка продолжится. Если вы хотите и дальше использовать Camoufox, как до этого выпуска, инструкции есть в этом [разделе](https://github.com/D4Vinci/Scrapling/blob/v0.3.13/docs/fetching/stealthy.md#using-camoufox-as-an-engine).++* Раньше мы использовали patchright в скрытном режиме `DynamicFetcher` и его классов сессий. Теперь мы убрали из них скрытный режим и стали использовать patchright в `StealthyFetcher` и его классах сессий. Как вы увидите ниже, мы внесли МНОГО улучшений и повысили общую скрытность поверх возможностей patchright.++**Благодаря этому `StealthyFetcher` и его классы сессий стали на 101 % быстрее, используют меньше памяти и места на диске, а код сократился примерно на 400 строк. Главное, они стабильнее, чем раньше, когда мы использовали Camoufox.**++Это также сократит время установки командой `scrapling install`, уменьшит Docker-образ, упростит выполнение тестов в GitHub CI и сделает Scrapling понятнее для новых пользователей.++### Несовместимые изменения {#v0.3.13-breaking-changes}+1. Аргумент `stealth` удалён из класса `DynamicFetcher` и его класса сессий, а `hide_canvas` перенесён в `StealthyFetcher` и его классы сессий.+2. Аргумент `disable_webgl` перенесён из `DynamicFetcher` в класс `StealthyFetcher` и переименован в `allow_webgl`. Это касается и всех классов сессий.+3. Теперь класс `StealthyFetcher` по сути является новой скрытной версией `DynamicFetcher`, поэтому удалены аргументы `block_images`, `humanize`, `addons`, `os_randomize`, `disable_ads` и `geoip`. Я пытался воспроизвести их возможности в Chromium, но с каждой возникли свои проблемы. Это может измениться в следующих выпусках до v0.4.++Теперь о хорошем: мы многое улучшили и исправили :)++### Улучшения {#v0.3.13-improvements}+- Вы уже знаете, что класс `StealthyFetcher` и его классы сессий стали на 101 % быстрее. Теперь класс `DynamicFetcher` и его класс сессий тоже стали на 20 % быстрее.+- Алгоритм прохождения проверок Cloudflare улучшен: он быстрее завершает работу и обрабатывает больше ситуаций. Благодаря рефакторингу обработчик также проходит CAPTCHA вдвое быстрее!+- Все Fetcher теперь используют меньше памяти.+- MCP-сервер теперь использует меньше токенов и помогает экономить деньги!+- Docker-образ стал на 60 % меньше.+- Весь сайт документации обновлён с учётом новых возможностей. Объяснения стали яснее, многие разделы короче, добавлены примеры и недостающие аргументы, в справочнике API появились схемы. Есть и много других улучшений. Сайт загружается на 130 % быстрее, использует меньше трафика и лучше подходит для SEO.++### Исправления ошибок {#v0.3.13-fixes}+- В сокращённые команды оболочки для веб-скрейпинга добавлены недостающие аргументы, а сами команды стали точнее.+- Исправлена проблема, из-за которой `google_search` создавал Referer Google даже для URL с localhost или IP-адресом.++## [v0.3.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.12) - 2025-12-18 {#v0.3.12}++### Что изменилось {#v0.3.12-what-s-changed}+- В классы `DynamicSession`/`AsyncDynamicSession` добавлен аргумент `timezone_id`. Он позволяет настроить часовой пояс браузера под используемый прокси или VPN. Так сайты не смогут обнаружить прокси по несовпадению часовых поясов.+- Улучшено автоматическое преобразование ответа в JSON.+- В классах сессий Fetcher внутренняя функция `__create__` переименована в `start`, чтобы было проще использовать их вне контекста `with`.+- `curl_cffi` и другие зависимости обновлены до последних версий.++## [v0.3.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.11) - 2025-12-03 {#v0.3.11}++### Что изменилось {#v0.3.11-what-s-changed}+- Улучшена обработка тайм-аутов при использовании `network_idle` на нестабильном сайте, например на сайте с воспроизведением медиа.+- Исправлено автодополнение сокращённой команды `stealthy_fetch` в оболочке для веб-скрейпинга.++## [v0.3.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.10) - 2025-11-26 {#v0.3.10}++**Техническое обновление с важными и потенциально несовместимыми изменениями**++- **Решены** все проблемы с кодировками благодаря новому подходу, который обрабатывает страницы с неверно объявленной кодировкой (спасибо @Kemsty2 за сообщения в [#110](https://github.com/D4Vinci/Scrapling/issues/110) [#111](https://github.com/D4Vinci/Scrapling/pull/111)).+- **Решена** логическая проблема с переопределением параметров сессии параметрами отдельного запроса во всех браузерных Fetcher. Она существовала с v0.3.+- **Исправлены** сигнатуры сокращённых команд интерактивной оболочки для веб-скрейпинга. Теперь автодополнение этих команд работает правильно. Эта проблема тоже существовала с v0.3.+- **Обновлена** версия базы Maxmind, что улучшает работу аргумента `geoip` в `StealthyFetcher` и его классах сессий.+- **Обновлены** все используемые браузеры до последних доступных версий.+- **НЕСОВМЕСТИМЫЕ ИЗМЕНЕНИЯ**: все Fetcher прошли большой рефакторинг, который привёл к изменениям, способным нарушить работу вашего кода:+ 1. Код Scrapling сократился примерно на 750 строк. Многие изменения упростят дальнейшую поддержку и немного снизят расход ресурсов.+ 2. Проверка аргументов во всех Fetcher и их классах сессий стала намного быстрее, что ускорит и работу в целом.+ 3. Для этого теперь все Fetcher принимают как позиционный аргумент только `url`. Остальные аргументы должны быть именованными. Нужно писать `Fetcher.get('https://google.com', stealthy_headers=True)`, а не `Fetcher.get('https://google.com', True)`, если вы по какой-то причине делали это раньше!+ 4. С v0.3 у браузерных Fetcher и их классов сессий было неудобное различие: аргумент для передачи настроек парсера на уровне запроса назывался `custom_config`, а в классах сессий он назывался `selector_config`. Рефакторинг позволил привести название к `selector_config`, не нарушая работу вашего кода. Теперь основной аргумент называется `selector_config`, а `custom_config` всё ещё работает для обратной совместимости. Автодополнение будет доступно только для `selector_config`.+ 5. Для всех этих изменений пришлось сделать подсказки типов функций Fetcher динамическими. Если IDE не предлагает правильное автодополнение, убедитесь, что у вас современная версия. Мы проверили почти все известные IDE и редакторы.++> Мы также обновили все таблицы тестов производительности, сравнив текущие результаты с последними версиями всех аналогичных библиотек.++## [v0.3.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.9) - 2025-11-17 {#v0.3.9}++**Обновление со многими важными изменениями**++### 🚀 Новые возможности и улучшения удобства {#v0.3.9-new-stuff-and-quality-of-life-changes}+- Теперь аргумент `impersonate` в `Fetcher` и `FetcherSession` принимает список браузеров. Для каждого запроса библиотека случайным образом выбирает браузер из этого списка.++```python+from scrapling.fetchers import FetcherSession++with FetcherSession(impersonate=['chrome', 'firefox', 'safari']) as s:+ s.get('https://github.com/D4Vinci/Scrapling')+```++- В метод `clean` класса `TextHandler` добавлен аргумент, который позволяет легко удалять HTML-сущности из текущего текста.+- Значительно улучшена документация: многие части объяснены точнее, добавлены автоматические переводы основного файла `README.md`.++### 🐛 Исправления ошибок {#v0.3.9-bug-fixes}+- Исправлена серьёзная проблема с получением ответов из браузерных Fetcher. Теперь тип содержимого определяется автоматически: `response.body` содержит результат отрисовки браузером только для HTML. В остальных случаях возвращается исходное содержимое последнего запроса. Это позволяет скачивать двоичные и текстовые файлы без оборачивания в HTML-теги, а при загрузке сайта получать нужное содержимое после отрисовки.++### 🔨 Прочее {#v0.3.9-misc}+- Руководство для участников обновлено и стало понятнее и проще.+- Добавлен рабочий процесс, который обязательно запускает инструменты контроля качества кода (те же, что используются в хуках pre-commit).++## [v0.3.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.8) - 2025-10-27 {#v0.3.8}++**Обновление со многими важными изменениями**++### 🚀 Новые возможности и улучшения удобства {#v0.3.8-new-stuff-and-quality-of-life-changes}+- Во всех браузерных Fetcher использование `network_idle` больше не приводит к сбою кода на сайтах, запросы которых никогда не завершаются.+- Изменена логика получения и проверки содержимого страниц в браузерных Fetcher. Теперь браузеры стабильнее работают на Windows, как и на Linux/MacOS (разница в поведении вызвана отличиями реализации Playwright на Windows).+- Вся логика проверки аргументов переработана, что ускорило запросы во всех браузерных Fetcher на 8-15 %.+- Новый параметр `extra_flags` добавлен в `DynamicFetcher` и его сессию. Он позволяет при запуске браузера добавлять свои флаги Chrome к уже заданным.+- При использовании `page_action` восстановлена прежняя логика перехвата ответов, изменённая в прошлой версии. Это позволяет получить актуальное содержимое страницы, даже если `page_action` меняет его без отправки запроса (спасибо @gembleman за сообщения в [#100](https://github.com/D4Vinci/Scrapling/issues/100) и [#102](https://github.com/D4Vinci/Scrapling/pull/102)).++### 🐛 Исправления ошибок {#v0.3.8-bug-fixes}+- Исправлена опечатка в `load_dom` в методе async_fetch класса DynamicSession.+- Исправлена проблема с обработчиком Cloudflare, который бесконечно ждал исчезновения встроенных CAPTCHA, остающихся на странице после прохождения. Теперь ожидание длится 30 секунд, после чего обработчик считает, что это CAPTCHA, которая не исчезает (исправляет #100).++### 🔨 Прочее {#v0.3.8-misc}+- Для удобства пользователей Docker-образ теперь автоматически публикуется в Dockerhub и реестре контейнеров GitHub.+- Добавлена [новая страница документации](https://github.com/D4Vinci/Scrapling/blob/v0.3.8/docs/tutorials/external.md) о работе со Scrapeless Browser в Scrapling.++## [v0.3.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.7) - 2025-10-12 {#v0.3.7}++**Обновление со многими важными изменениями**++### 🚀 Новые возможности и улучшения удобства {#v0.3.7-new-stuff-and-quality-of-life-changes}+- Переработан аргумент `solve_cloudflare` в `StealthyFetcher`, чтобы проходить все виды нестандартных реализаций Turnstile.+- Весь код переработан для успешной проверки Pyright. Теперь работать во всех IDE стало удобнее. Также исправлено много ошибок.+- Логика запросов стала проще и быстрее (также решает #97).+- Во все браузерные классы сессий добавлен параметр `user_data_dir`, позволяющий повторно использовать данные браузера из прошлых сессий: cookie, хранилище и другое. Если его не задать, Playwright, как и прежде, будет использовать случайный каталог при каждом запуске.+- Новый параметр `additional_args` добавлен в `Dynamic fetcher` и его класс сессий. Он позволяет передавать дополнительные аргументы в контекст Playwright, как раньше можно было делать в `StealthyFetcher`.+- Улучшена логика получения последнего ответа при навигации во всех браузерах. Теперь исходный ответ передаётся в парсер до обработки браузером, а не после неё, как раньше. Это особенно полезно для текстовых и JSON-ответов.++### 🐛 Исправления ошибок {#v0.3.7-bug-fixes}+- Переработка логики перехвата ответов решила проблему с получением содержимого нестабильных сайтов на некоторых устройствах Windows.+- Рефакторинг в этой версии также исправил много ошибок, которые раньше было трудно заметить, и странные проблемы с автодополнением в некоторых IDE.+- Много исправлений на сайте документации.++## [v0.3.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.6) - 2025-10-01 {#v0.3.6}++### 🚀 Новые возможности {#v0.3.6-new-stuff}+- Улучшен аргумент `solve_cloudflare` в `StealthyFetcher` и его классах сессий. Теперь он позволяет проходить все виды Turnstile и промежуточных проверок Cloudflare 🎉+- MCP-сервер теперь поддерживает `Streamable HTTP`, что позволяет легко открыть к нему доступ извне.+- Добавлена поддержка Docker. При каждом выпуске образ автоматически собирается и публикуется в Docker Hub (содержит все браузеры).++### 🐛 Исправления ошибок {#v0.3.6-bug-fixes}+- Исправлена возникавшая в некоторых случаях проблема с кодировкой в парсере (известная ошибка `invalid start byte`).+- Переработано несколько частей библиотеки для исправления утечек памяти. Теперь расход памяти заметно ниже, в зависимости от настроек (также решает #92).+- Улучшены аннотации типов во многих частях кода для более удобной работы в IDE (также решает #93).++## [v0.3.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.5) - 2025-09-20 {#v0.3.5}++**Важный выпуск с исправлениями нескольких проблем**++### 🚀 Новые возможности {#v0.3.5-new-stuff}+- Все браузерные Fetcher (`DynamicFetcher`/`StealthyFetcher`/...) и их классы сессий теперь загружают сайты на 15-20 % быстрее:+ 1. Управление страницами стало намного быстрее благодаря улучшению логики от @AbdullahY36 в #87.+ 2. Оптимизирована проверка аргументов и улучшено создание страниц для синхронных запросов. Вместе это заметно повысило скорость.++- Значительно улучшен скрытный режим в `DynamicFetcher` и его классах сессий за счёт замены `rebrowser-playwright` на `PatchRight`:+ 1. До этого обновления `rebrowser-playwright` отключался при одновременном включении `stealth` и `real_chrome`, так как они плохо работали вместе. С `PatchRight` этой проблемы нет.+ 2. Теперь можно взаимодействовать с закрытыми Shadow Root, так как `PatchRight` обрабатывает их автоматически.++### 🐛 Исправления ошибок {#v0.3.5-bug-fixes}+- Исправлена ошибка при использовании метода `re` класса `Selectors`.+- Исправлена ошибка команд `uncurl` и `curl2fetcher` в оболочке для веб-скрейпинга, из-за которой флаг curl `--data-raw` разбирался неверно.+- Исправлена ошибка команды `view` в оболочке для веб-скрейпинга, которая возникала при определённой кодировке сайта.+- Исправлена ошибка преобразования содержимого, затрагивавшая режим `mcp` и команды `extract`.++### Новые участники {#v0.3.5-new-contributors}+- @AbdullahY36 впервые внёс вклад в проект в #87.++## [v0.3.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.4) - 2025-09-16 {#v0.3.4}++**Важный выпуск с исправлениями нескольких проблем**++### 🚀 Новые возможности {#v0.3.4-new-stuff}+- В интерактивную оболочку добавлены все классы сессий Fetcher. Их можно использовать сразу, без импорта.++### 🐛 Исправления ошибок {#v0.3.4-bug-fixes}+- Добавлен обход ошибки Playwright API на Windows, которая возникала при получении содержимого во время прохождения проверки Cloudflare.+- Исправлена проблема с кодировкой команды `view` в интерактивной оболочке.+- Исправлена ошибка аргумента `max_pages` в `AsyncStealthySession`, приводившая к сбою кода.+- Исправлена проблема последних обновлений: свойства `html_content` и `prettify` класса `Selector` могли возвращать байты в зависимости от кодировки. Теперь оба снова возвращают строки.++## [v0.3.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.3) - 2025-09-15 {#v0.3.3}++- Удалена логика закрытия стандартной вкладки в браузерных Fetcher, так как она приводила к сбою (на Mac сбоя не было, его удалось воспроизвести только на Windows и Linux).++## [v0.3.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.2) - 2025-09-15 {#v0.3.2}++Примечания к выпуску v0.3.2++### 🚀 Новые возможности {#v0.3.2-new-stuff}++- **Необязательные зависимости Fetcher**: все Fetcher теперь входят в группы дополнительных зависимостей, что уменьшает размер основного пакета. Базовый модуль `scrapling` содержит только парсер. Для Fetcher или командной строки выполните `pip install "scrapling[fetchers]"`. Подробные инструкции по установке доступны [здесь](index.md#installation).+- **Настройки для отдельных страниц в сессии**: классы сессий браузерных Fetcher теперь позволяют настраивать каждую страницу отдельно. Все параметры получения страницы проверяются так же, как параметры сессии. Подробнее на сайте документации [здесь](fetching/stealthy.md#full-list-of-arguments).+ <br>Пример:++ ```python+ with StealthySession(headless=True, solve_cloudflare=True) as session:+ page = session.fetch('https://nopecha.com/demo/cloudflare', google_search=False)+ ```++- **Улучшения браузерных Fetcher**+ - Новый параметр определяет, нужно ли ждать завершения JavaScript на странице (по умолчанию включён, как и раньше).++ ```python+ with DynamicSession(headless=True, disable_resources=False, network_idle=True) as session:+ page = session.fetch('https://quotes.toscrape.com/', load_dom=False)+ ```++ - Скрытный режим в `DynamicFetcher` и его классах сессий стал надёжнее.+ - `DynamicFetcher` и `StealthyFetcher` теперь используют меньше ресурсов (автоматически находят и закрывают стандартную вкладку, которую открывает постоянный контекст Playwright API).+ - Исправлена важная ошибка переключения страниц в браузерных Fetcher: старые страницы теперь заменяются новыми. (В повторно используемых вкладках могут оставаться прежние настройки.)+ - `StealthyFetcher` и его классы сессий стали немного быстрее (5 %).++- **Улучшено свойство `.body`**: теперь оно возвращает переданное содержимое как есть, без обработки. Это позволяет скачивать файлы и обрабатывать запросы с содержимым, отличным от HTML. Ниже показан пример скачивания фотографии:++ ```python+ from scrapling.fetchers import Fetcher++ page = Fetcher.get('https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/poster.png')+ with open(file='poster.png', mode='wb') as f:+ f.write(page.body)+ ```++### 🐛 Исправления ошибок {#v0.3.2-bug-fixes}++- **Решены проблемы с кодировками**: исправлено несколько проблем с кодировками на отдельных сайтах в парсере, режиме mcp и командах extract (также решает #80 и #81).+- **Ускорен разбор**: благодаря многочисленным изменениям библиотека стала быстрее, что видно в обновлённых тестах производительности.++### 🔨 Прочее {#v0.3.2-misc}++- **Обновлены тесты производительности**: текущие улучшения скорости сравниваются с последними версиями похожих библиотек.+- **Многие части кода переработаны, а неиспользуемый код заменён лучшими реализациями**: кода меньше, он понятнее и проще в поддержке.+- **Добавлено видео на YouTube**: в документацию MCP добавлено видео.+- **Новый шаблон обращений**: простой шаблон для пользователей, которые не могут использовать существующие.+- **Оптимизация рабочего процесса CI**: тесты теперь не запускаются, если изменились только документация или другие файлы, не содержащие код.+- **Обновлены зависимости**: различные зависимости обновлены до последних версий.+- **Улучшения стиля кода**: новые правила ruff применены ко всем файлам.+- **Хуки pre-commit**: обновлена конфигурация pre-commit.++### 🎯 Несовместимые изменения {#v0.3.2-breaking-changes}++- Параметр `max_pages` удалён из синхронной версии `StealthySession` для соответствия `DynamicSession` (в синхронной версии он не имеет смысла).++## [v0.3.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.1) - 2025-09-02 {#v0.3.1}++1. Исправлена проблема установки Scrapling без набора зависимостей `shell` (#76).+2. Во все браузерные Fetcher и их классы сессий добавлен аргумент для указания JS-файла, который выполняется при создании страницы (#56):++```python+from scrapling.fetchers import StealthyFetcher++StealthyFetcher.fetch('https://example.com', init_script="/absolute/path/to/js/script.js")+```++## [v0.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3) - 2025-09-01 {#v0.3}++🎉 **Крупный выпуск: полностью новая архитектура**++Scrapling v0.3 стал самым значительным обновлением за всю историю проекта. Архитектура полностью переписана, производительность заметно выросла, а среди новых возможностей появились интеграция с ИИ и интерактивная оболочка для сбора данных с сайтов.++Этот выпуск содержит несколько несовместимых изменений. Внимательно прочитайте примечания к выпуску.++### 🚀 Главные новые возможности {#v0.3-major-new-features}++#### Архитектура на основе сессий {#v0.3-session-based-architecture}+- **Новые классы сессий**: код полностью переписан, добавлена поддержка постоянных сессий.+ - `FetcherSession`: HTTP-запросы с сохранением состояния. Работает как с синхронным, так и с асинхронным кодом.+ - `DynamicSession`/`AsyncDynamicSession`: автоматизация браузера, который остаётся открытым до завершения вашей работы.+ - `StealthySession`/`AsyncStealthySession`: скрытная работа в браузере, который остаётся открытым до завершения вашей работы.+- **Асинхронное управление вкладками**: новый аргумент `max_pages` создаёт пул вкладок, которые используются по очереди для одновременной загрузки страниц через браузер.+- **Одновременные сессии**: запускайте несколько изолированных сессий одновременно.++Подробнее читайте в разделе `Fetching` на сайте.++#### Много новых возможностей скрытной работы и обхода защиты от ботов {#v0.3-a-lot-of-new-stealth-anti-bot-capabilities}+- **🤖 Прохождение проверок Cloudflare**: автоматическое [прохождение проверок Cloudflare Turnstile](fetching/stealthy.md#cloudflare-and-stealth-options) в `StealthyFetcher` и его классах сессий.+- **Имитация отпечатков браузера**: полностью обновлённый класс [Fetcher](fetching/static.md) имитирует TLS-отпечатки настоящих браузеров, создаёт заголовки для нужной версии браузера, поддерживает HTTP/3 и многое другое.+- **Улучшенный скрытный режим**: скрытный режим в `DynamicFetcher` и его классах сессий стал надёжнее и стабильнее (другое название класса: `PlayWrightFetcher`).++#### Интеграция с ИИ и MCP-сервер {#v0.3-ai-integration-mcp-server}+- **Встроенный MCP-сервер**: сервер Model Context Protocol для сбора данных с помощью ИИ.+- **6 мощных инструментов**: `get`, `bulk_get`, `fetch`, `bulk_fetch`, `stealthy_fetch`, `bulk_stealthy_fetch`.+- **Умное извлечение содержимого**: преобразуйте страницы и элементы в Markdown или HTML либо извлекайте очищенный текст.+- **Поддержка CSS-селекторов**: точно выбирайте нужные элементы с помощью движка Scrapling перед передачей содержимого ИИ.+- **Обход защиты от ботов**: проходите Cloudflare Turnstile и другие проверки.+- **Поддержка прокси**: используйте прокси для анонимности и запросов из нужных регионов.+- **Имитация браузера**: воспроизводите TLS-отпечатки, настоящие заголовки для нужной версии браузера и другие признаки.+- **Параллельная обработка**: собирайте данные с нескольких URL одновременно для большей эффективности.+- [И многое другое...](ai/mcp-server.md)++#### Новая интерактивная оболочка для сбора данных {#v0.3-new-interactive-web-scraping-shell}+- **Новая оболочка**: доработанная оболочка IPython со множеством удобных встроенных сокращений, таких как `get`, `post`, `put`, `delete`, `fetch` и `stealthy_fetch`.+- **Умное управление страницами**: новые команды `page` и `pages` автоматически сохраняют текущую страницу и историю всех запросов из оболочки.+- **Интеграция с curl**: функции `uncurl` и `curl2fetcher` преобразуют команды curl из DevTools браузера в запросы `Fetcher`.+- [И многое другое...](cli/interactive-shell.md)++#### Сбор данных из терминала без программирования {#v0.3-scrape-from-the-terminal-without-programming}+- **Новые команды извлечения**: собирайте данные из терминала без программирования.+ - `scrapling extract get/post/put/delete`: простые HTTP-запросы.+ - `scrapling extract fetch`: сбор динамического содержимого.+ - `scrapling extract stealthy-fetch`: обход защиты от ботов.+- **Загружает веб-страницы** и сохраняет их содержимое в файлы.+- **Преобразует HTML в удобные для чтения форматы**, например Markdown, сохраняет его как HTML или извлекает только текст страницы.+- **Поддерживает собственные CSS-селекторы** для извлечения отдельных частей страницы.+- **Выполняет HTTP-запросы и загружает страницы через браузер.**+- **Гибко настраивается**: можно задать заголовки, cookie, прокси и другие параметры. Почти все опции, доступные в коде, можно использовать и в терминале.+- [И многое другое...](cli/extract-commands.md)++### 🔧 Технические улучшения {#v0.3-technical-improvements}++#### Улучшения производительности {#v0.3-performance-enhancements}+- **Fetcher теперь в 4 раза быстрее**. Да, вы всё правильно прочитали!+- **DynamicFetcher теперь примерно на 60 % быстрее**. Прирост зависит от настроек, особенно от скрытного режима.+- **StealthyFetcher теперь на 20–30 % быстрее** благодаря новой структуре и началу перехода на нашу реализацию вместо Python-интерфейса `Camoufox`.+- **Общий прирост скорости основных методов выборки составляет 50 % и более** (`find_by_text`, `find_similar`, `find_by_regex`, `relocate` и других). 🚀+- **Методы CSS/XPath для первого совпадения стали примерно на 10 % быстрее**. `css_first` и `xpath_first` теперь быстрее, чем `css` и `xpath`.+- **Метод `get_all_text()` для извлечения содержимого стал на 40 % быстрее**.+- **Адаптивный повторный поиск элементов стал на 20 % быстрее**.+- **Оптимизированы свойства для перехода между элементами**. `next`, `previous`, `below_elements` и другие свойства теперь работают заметно быстрее.+- **Очистка текста стала в 5 раз быстрее**.+- **Улучшено использование памяти** за счёт оптимизации импорта и уменьшения накладных расходов.+- **⚡ Мгновенный импорт**: оптимизация загрузки модулей сократила время запуска.+- **Лучшие результаты тестов производительности**: все эти изменения сделали Scrapling ещё быстрее по сравнению с другими библиотеками. Он в 1775 раз быстрее BeautifulSoup и в 5,1 раза быстрее AutoScraper, см. [тесты производительности](benchmarks.md).++#### Архитектура, качество кода и удобство {#v0.3-architecture-code-quality-and-quality-of-life}+- **Постоянный контекст**: все браузерные Fetcher теперь по умолчанию используют постоянный контекст. (Это также решает #64.)+- **Быстрая проверка всех браузерных Fetcher через msgspec** перед выполнением запросов упрощает поиск ошибок.+- **Все cookie**, возвращаемые Fetcher, теперь имеют формат, который принимает этот же Fetcher. Их можно получать и снова передавать всем Fetcher и их классам сессий.+- **Более быстрые проверка и форматирование кода** благодаря переходу на `ruff`.+- **Современная система сборки**: переход с setup.py на pyproject.toml. 📦+- **Улучшенные GitHub Actions и рабочие процессы** упрощают разработку и тестирование.+- **🎨 Улучшенные подсказки типов**: полное покрытие типов по современным стандартам Python для лучшей поддержки в IDE и большей надёжности.+- **Более чистый код**: удалён неиспользуемый код и оптимизированы основные функции. 🧹+- **🚀 Обратная совместимость**: добавлены сокращения, чтобы старый код продолжал работать.++### Несовместимые изменения {#v0.3-breaking-changes}++#### Минимальная версия Python {#v0.3-minimum-python-version}+- **Требуется Python 3.10+**: поддержка Python 3.9 и более ранних версий прекращена.++#### Названия классов и методов {#v0.3-class-and-method-naming}+Эти переименования делают названия понятнее и единообразнее, особенно для новых пользователей.++- **`Adaptor` → `Selector`**: переименован основной класс парсера (для обратной совместимости его по-прежнему можно импортировать как `Adaptor`).+- **`Adaptors` → `Selectors`**: переименован класс коллекции (для обратной совместимости его по-прежнему можно импортировать как `Adaptors`).+- **`auto_match` → `adaptive`**: параметр переименован во всех методах.+- **`adaptor_arguments` → `selector_config`**: переименован параметр конфигурации.+- **`automatch_domain` → `adaptive_domain`**: переименован параметр домена.+- **`additional_arguments` → `additional_args`**: сокращено имя параметра.+- **⚠️ `text/body` → `content`**: параметр конструктора Selector теперь принимает и `str`, и `bytes`.+- **`PlayWrightFetcher` → `DynamicFetcher`**: переименован класс автоматизации браузера (для обратной совместимости его по-прежнему можно импортировать как `PlayWrightFetcher`).+- **Из DynamicFetcher удалены логика и аргументы NSTBrowser**, поскольку сохранять их больше нет смысла.+- **Аргумент headless в StealthyFetcher больше не принимает 'virtual'**, поскольку библиотека Camoufox теперь используется только для получения пути установки браузера и остальных параметров запуска.++### 🐛 Исправления ошибок {#v0.3-bug-fixes}++- Исправлен подсчёт вложенных дочерних элементов в игнорируемых тегах для `get_all_text` (#61).+- Исправлена проблема установки из-за пробелов в пути к исполняемому файлу Python (#57).+- Исправлены проблемы с потоками в хранилище при обработке рекурсии с включённой адаптивной функцией.+- Исправлены проблемы с приоритетом аргументов в `FetcherSession` с помощью шаблона Sentinel.+- Исправлена обработка типов прокси в `StealthyFetcher`.+- Исправлены конфликты аргументов `referer` и `google_search`.+- Исправлены проблемы с асинхронным внедрением скриптов для скрытной работы.++## [v0.2.99](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.99) - 2025-04-08 {#v0.2.99}++**Это важное обновление для всех, кто хочет использовать Scrapling в полной мере.**++### Что изменилось {#v0.2.99-what-s-changed}+#### Новый сайт с полной документацией {#v0.2.99-new-full-documentation-website}+- Да, наконец-то 😄 Посмотрите [здесь](index.md).+#### Единый способ импорта Fetcher {#v0.2.99-unified-import-logic-for-fetchers}+- Теперь все Fetcher можно импортировать через `from scrapling.fetchers import Fetcher, AsyncFetcher, StealthyFetcher, PlayWrightFetcher` и сразу использовать без инициализации, например `page = Fetcher.get(...)`.<br/> Это заменяет старый импорт `from scrapling.defaults import Fetcher, AsyncFetcher, StealthyFetcher, PlayWrightFetcher`.+#### Несовместимое изменение: automatch теперь выключен по умолчанию {#v0.2.99-breaking-change-automatch-is-now-turned-off-by-default}+- Появился новый способ включить automatch и задать другие параметры парсера через Fetcher. Подробности смотрите на [странице документации](fetching/choosing.md#parser-configuration-in-all-fetchers).+> Старые импорты и логика по-прежнему работают для обратной совместимости, но выдают предупреждение.+#### Новые опции Fetcher {#v0.2.99-new-options-added-to-fetchers}+- У `StealthyFetcher` и `PlayWrightFetcher` появился аргумент `wait` для загрузки страниц. Он заставляет Fetcher подождать указанное время в миллисекундах перед закрытием страницы и возвратом ответа.+- В `StealthyFetcher` методы `fetch` и `async_fetch` теперь принимают `additional_arguments` для передачи дополнительных настроек в Camoufox. Они имеют приоритет над настройками Scrapling (#54).+#### Исправления ошибок {#v0.2.99-bugs-squashed}+- Исправлена ошибка получения перенаправлений в `async_fetch` обоих классов: `StealthyFetcher` и `PlayWrightFetcher`.++**_Спасибо за всю вашу поддержку и пожертвования!_**++## [v0.2.98](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.98) - 2025-03-17 {#v0.2.98}++**Это важное обновление для всех, кто хочет использовать Scrapling в полной мере**++### Что изменилось {#v0.2.98-what-s-changed}+#### Разные улучшения использования памяти и скорости {#v0.2.98-various-memory-usage-and-speed-optimizations}+- Все методы выборки теперь используют около 40 % прежнего объёма памяти и работают немного быстрее.+- Для всех подмодулей библиотеки добавлена отложенная загрузка: загружается только то, что вы используете. Например:+До обновления импорт `from scrapling import Adaptor` занимал `30-40mb` оперативной памяти, поскольку вместе с ним загружались все Fetcher и другие модули. Теперь он занимает `~1.2mb`.+- В прошлом обновлении при большом пуле запросов библиотека стала использовать около 32 % прежнего объёма памяти. Теперь кеширование настроено ещё точнее, чтобы расходовать ещё меньше.+- Скорость парсера в целом выросла на 2-5 %.++**_Спасибо за всю вашу поддержку и пожертвования!_**++## [v0.2.97](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.97) - 2025-03-15 {#v0.2.97}++**Это важное обновление для всех, кто хочет использовать Scrapling в полной мере**++### Что изменилось {#v0.2.97-what-s-changed}+#### Меньше памяти и немного больше скорости у всех Fetcher {#v0.2.97-lower-memory-usage-and-small-speed-increase-across-all-fetchers}+- Новые ограничения размера кеша во всей библиотеке заметно снижают расход памяти при большом числе запросов или операций.+- Значительная часть кода Fetcher переработана, чтобы упростить поддержку и немного ускорить работу.++#### Исправления ошибок {#v0.2.97-bugs-fixed}+- Исправлена ошибка `TextHandler`: при отдельном импорте класса переданный нестроковый аргумент превращался в пустую строку. Теперь любое значение для `TextHandler` сначала преобразуется в строку и только потом в `TextHandler`. Это правило действует для всех значений. Как следует из названия, `TextHandler` предназначен именно для строк! (#45)+- Исправлена ошибка, из-за которой большинство методов AsyncFetcher не учитывало аргументы `retries`.++#### Прочее {#v0.2.97-miscellaneous}+- Подсказки типов для большинства аргументов всех Fetcher стали понятнее и точнее.++**_Спасибо за всю вашу поддержку и пожертвования!_**++## [v0.2.96](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.96) - 2025-03-05 {#v0.2.96}++**Это важное обновление для всех, кто хочет использовать Scrapling в полной мере**++### Что изменилось {#v0.2.96-what-s-changed}+1. Добавлена опция `-f` для `scrapling install`, которая принудительно переустанавливает зависимости браузера. Рекомендую выполнить `scrapling install -f`, чтобы оценить значительное ускорение `StealthyFetcher` с новой версией браузера Camoufox :)+2. Исправлена ошибка `TextHandler`, когда срез возвращал `TextHandlers` вместо `TextHandler`. Также исправлена подсказка типа (#41).+3. Исправлена проблема, из-за которой `scrapling install` в некоторых случаях открывал пользователю оболочку Python!++## [v0.2.95](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.95) - 2025-02-25 {#v0.2.95}++**Это важное обновление для всех, кто хочет использовать Scrapling в полной мере**++### Что изменилось {#v0.2.95-what-s-changed}+1. Исправлена ошибка `Fetcher`, при которой заголовки от аргумента `stealthy_headers` перезаписывали некоторые заголовки пользователя, например `Accept` (#39).+2. Немного улучшена генерация заголовков, что должно слегка повысить скорость.++## [v0.2.94](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.94) - 2025-02-22 {#v0.2.94}++**Это важное обновление для всех, кто хочет использовать Scrapling в полной мере**++### Что изменилось {#v0.2.94-what-s-changed}+1. Во все Fetcher добавлено свойство `history` для просмотра перенаправлений (#32).+2. Исправлена логика аргумента `case_sensitive` во всех `re`/`re_first`. Если вы его использовали, код может начать возвращать другие результаты (но, возможно, вы это заслужили, если заметили проблему и не сообщили о ней в issue, ха-ха).+3. Обновлены зависимости, а в движке Camoufox (StealthyFetcher) снова включён `coop`.++## [v0.2.93](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.93) - 2025-01-31 {#v0.2.93}++**Это важное обновление для всех, кто хочет использовать Scrapling в полной мере**++### Что изменилось {#v0.2.93-what-s-changed}+1. Типы возвращаемых значений теперь единообразны во всём парсере. Результат всегда имеет один из типов: `Adaptor`, `Adaptors`, `TextHandler`, `TextHandlers`, `None`, либо список при смешанных результатах, например при объединении CSS-селекторов. Это упрощает код, сокращает ручные проверки типов, повышает стабильность библиотеки и всегда позволяет объединять вызовы методов в цепочку.+2. Большая часть парсера, особенно класс `Adaptor`, переработана: код стал чище и, главное, быстрее. Почти все методы и свойства, особенно методы поиска, ускорились на 5-40 %. Некоторые стали ещё быстрее: например, `find_by_regex` ускорился примерно на 60 %! Функция automatch стала примерно на 5 % быстрее.+3. Исправлены ошибки логики `find_all`/`find`, из-за которых переданные фильтры иногда объединялись через ИЛИ, а иногда через И. Теперь каждый возвращаемый элемент должен соответствовать всем фильтрам.+4. Все методы, связанные с регулярными выражениями, теперь возвращают `TextHandler`/`TextHandlers`, чтобы вызовы было проще объединять в цепочки.+5. **Добавлено новое** свойство `below_elements`, которое возвращает объект `Adaptors` со всеми элементами ниже текущего в дереве DOM.+6. Все методы и свойства, которые возвращали исходный HTML в виде строки, теперь возвращают `TextHandler`. Это упрощает работу с регулярными выражениями и другими возможностями.+7. StealthyFetcher стал немного быстрее и менее заметным. Также теперь можно нажимать на CAPTCHA внутри iframe, например на **Cloudflare Turnstile**.+8. Автодополнение и подсказки типов заметно улучшены почти в половине библиотеки, особенно в `Adaptor`, `TextHandler` и `TextHandlers`.+9. Для объекта `TextHandler` срезы, обращение по индексу и метод `split` теперь возвращают другой `TextHandler`, а не обычную строку Python. Почти все стандартные строковые операции и методы теперь возвращают `Texthandler`, чтобы всегда можно было объединять вызовы методов и функций в цепочки.+10. Исправлены мелкие ошибки и опечатки. Например, Fetcher async_put отправлял POST-запрос вместо PUT 😶🌫️+11. Немного улучшен README, пока я заканчиваю сайт с документацией.++Это должно было быть небольшое обновление до версии 0.3, но я решил сделать его лучше.++## [v0.2.92](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.92) - 2024-12-26 {#v0.2.92}++### Что изменилось {#v0.2.92-what-s-changed}+- Ответы браузерных Fetcher теперь используют более надёжные источники данных, если загруженная страница содержит много iframe.+- **Устанавливать `Scrapling` стало ещё проще: установите его через pip, затем выполните `scrapling install` в терминале, и всё готово!**+- Исправлена неточная подсказка типа в парсере.++## [v0.2.91](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.91) - 2024-12-19 {#v0.2.91}++### Что изменилось {#v0.2.91-what-s-changed}+- Исправлена ошибка, из-за которой сообщение журнала о загрузке отображалось только для первого запроса.+- При переходе на страницу API Playwright по умолчанию возвращает первый ответ, который соответствует состоянию загрузки, переданному в `goto`: `["load", "domcontentloaded", "networkidle"]`. Поэтому если сайт сначала показывает страницу ожидания, как у Cloudflare, а затем перенаправляет на настоящий сайт, Playwright возвращает первый код состояния, например 403. Обновление решает эту проблему в `PlaywrightFetcher` и `StealthyFetcher`, поскольку оба используют API Playwright. Результат больше не зависит от этого стандартного поведения Playwright.+- В класс `Fetcher` добавлена поддержка SOCKS-прокси.+- Исправлена подсказка типа аргумента `wait_selector_state`: теперь автодополнение показывает правильные допустимые значения.++## [v0.2.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.9) - 2024-12-16 {#v0.2.9}++### Что изменилось {#v0.2.9-what-s-changed}+##### Новые возможности {#v0.2.9-new-features}+1. В Scrapling появилась **долгожданная** поддержка асинхронного кода! Добавлен `AsyncFetcher`, асинхронный вариант `Fetcher`, а у `StealthyFetcher` и `PlayWrightFetcher` появился метод `async_fetch` с теми же опциями.++```python+>> from scrapling import StealthyFetcher+>> page = await StealthyFetcher().async_fetch('https://www.browserscan.net/bot-detection') # the async version of fetch+>> page.status == 200+True+```++2. В методы загрузки класса `StealthyFetcher` добавлен аргумент `geoip`. При включении класс автоматически использует долготу, широту, часовой пояс, страну и локаль IP-адреса, а затем подменяет IP-адрес WebRTC. Он также выбирает и подменяет язык браузера с учётом распространённости языков в целевом регионе.+3. Добавлен аргумент `retries` в классы `Fetcher`/`AsyncFetcher`. Он позволяет задать число повторных попыток для каждого запроса через `httpx`.+4. Добавлен метод `url_join` в `Adaptor` и Fetcher. Он соединяет относительный URL с текущим и создаёт полный абсолютный URL!+5. Добавлен метод `keep_cdata` в `Adaptor` и Fetcher, чтобы при необходимости запретить парсеру удалять CDATA.+6. В `Adaptor`/`Response` метод `body` теперь по возможности возвращает исходный HTML-ответ без обработки в библиотеке.+7. Добавлено журналирование в класс `Response`: при использовании Fetcher теперь выводится сообщение с данными полученного ответа.+Пример:++ ```python+ >> from scrapling.defaults import Fetcher+ >> Fetcher.get('https://books.toscrape.com/index.html')+ [2024-12-16 13:33:36] INFO: Fetched (200) <GET https://books.toscrape.com/index.html> (referer: https://www.google.com/search?q=toscrape)+ >>+ ```++8. Все стандартные строковые методы объекта `TextHandler`, например `.replace()`, теперь возвращают другой `TextHandler`. Раньше они возвращали обычную строку.+9. Значительно повышена скорость всей библиотеки и улучшена скрытная работа классов Fetcher.+10. Добавлены простые функции вроде `extract_first`\`extract`, которые возвращают тот же результат, что и родительский объект. Они нужны только для удобного переноса кода из Scrapy/Parsel в Scrapling, поскольку используются в тех библиотеках!+11. Благодаря переработке большого объёма кода и кешированию в нужных местах массовые запросы теперь выполняются значительно быстрее.++##### Несовместимые изменения {#v0.2.9-breaking-changes}+- Прекращена поддержка Python 3.8. (Главным образом потому, что Playwright перестал его поддерживать, но эта версия и так была проблемной.)+- Аргумент `debug` удалён из всей библиотеки. Чтобы включить отладку, выполните это после импорта библиотеки:++ ```python+ >>> import logging+ >>> logging.getLogger("scrapling").setLevel(logging.DEBUG)+ ```++##### Исправления ошибок {#v0.2.9-bugs-squashed}+1. WebGL теперь включён по умолчанию, поскольку многие системы защиты проверяют, включён ли он.+2. Исправлены ошибки и опечатки в документации и README.++##### Улучшения удобства {#v0.2.9-quality-of-life-changes}+1. Все сообщения журнала теперь используют логгер с именем `scrapling`, чтобы ими было проще управлять. Раньше использовался корневой логгер.+2. Структура папки тестов стала понятнее, добавлены тесты новых возможностей. Все тесты переписаны в более понятном виде и дополнены для лучшего покрытия.+3. Большая часть кода переработана, чтобы он стал понятнее и проще в поддержке.++> Все эти изменения изначально планировались для 0.3. Я решил добавить их уже сейчас, поскольку до следующей версии ещё пройдёт время. Теперь нужно закончить сайт с подробной документацией, а затем приступить к версии 0.3.++## [v0.2.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.8) - 2024-11-30 {#v0.2.8}++### Что изменилось {#v0.2.8-what-s-changed}+- Небольшое обновление с несколькими важными улучшениями удобства работы с кодом и исправлением опечатки в основном README (#20).++## [v0.2.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.7) - 2024-11-26 {#v0.2.7}++### Что изменилось {#v0.2.7-what-s-changed}+##### Новые возможности {#v0.2.7-new-features}+- При использовании аргумента `wait_selector` с классами `StealthyFetcher` и `PlayWrightFetcher` Scrapling теперь снова ждёт полной загрузки и выполнения JavaScript, как обычно. Если указан `network_idle`, после всех этих ожиданий Scrapling также повторно ждёт отсутствия сетевой активности. Если все состояния уже достигнуты, ожидания, конечно, не будет.+- В `StealthyFetcher` теперь можно разрешать или блокировать рекламу аргументом `disable_ads`. По умолчанию он включён и устанавливает дополнение `ublock origin`.+- Локаль `PlayWrightFetcher` теперь можно задать аргументом `locale`. По умолчанию по-прежнему используется `en-US`.+- Простые запросы через `Fetcher` теперь принимают прокси в формате `http://username:password@localhost:8030`.+- Немного улучшен скрытный режим `PlayWrightFetcher`.++##### Исправления ошибок и улучшения {#v0.2.7-bugs-squashed-improvements}+1. Прокси в классе `PlayWrightFetcher` теперь можно включить независимо от того, включён ли режим `stealth` (спасибо [@AbdullahY36](https://github.com/AbdullahY36) за замечание).+2. `ResponseEncoding` теперь проверяет, можно ли использовать кодировку ответа для страницы. Если она вызывает ошибку, Scrapling использует `utf-8`.++## [v0.2.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.6) - 2024-11-24 {#v0.2.6}++### Что изменилось {#v0.2.6-what-s-changed}+##### Новые возможности {#v0.2.6-new-features}+- `PlayWrightFetcher` теперь может напрямую использовать настоящий браузер. Передайте `real_chrome` в `PlayWrightFetcher.fetch`. Для этого должен быть установлен Chrome. Scrapling запустит ваш Chrome, и большинство опций можно будет использовать как обычно. (Раньше для этого был только аргумент `cdp_url`.)+- Повышена версия в заголовках, создаваемых для настоящих браузеров.++##### Исправления ошибок {#v0.2.6-bugs-squashed}+1. Оказалось, что формат браузерных заголовков, создаваемых `BrowserForge`, устарел. Из-за этого некоторые системы защиты обнаруживали Scrapling. Теперь `BrowserForge` используется только для создания настоящего User-Agent.+2. Аргумент `hide_canvas` теперь выключен по умолчанию, поскольку его обнаруживает ReCaptcha от Google.++## [v0.2.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.5) - 2024-11-23 {#v0.2.5}++### Что изменилось {#v0.2.5-what-s-changed}++##### Исправления ошибок {#v0.2.5-bugs-squashed}+- Обработана ошибка аргумента 'wait_selector', если он находил более 1 элемента. Это касается классов `StealthyFetcher` и `PlayWrightFetcher`.+- Исправлена кодировка, когда значение заголовка `content_type` содержит параметры вроде `charset` (спасибо @andyfcx за [#12](https://github.com/D4Vinci/Scrapling/issues/12)).++##### Улучшения удобства {#v0.2.5-quality-of-life}+- Добавлены тесты новых частей кода, а сами тесты теперь выполняются в потоках.+- Я обновил строки документации, чтобы они правильно отображались в Sphinx apidoc и подобных инструментах.++##### Новые участники {#v0.2.5-new-contributors}+- @andyfcx впервые внёс вклад в проект в [#13 ](https://github.com/D4Vinci/Scrapling/pull/13).++## [v0.2.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.4) - 2024-11-20 {#v0.2.4}++### Что изменилось {#v0.2.4-what-s-changed}++##### Исправления ошибок {#v0.2.4-bugs-squashed}+- Исправлена ошибка получения байтов ответа после использования аргумента `network_idle` в классах `StealthyFetcher` и `PlayWrightFetcher`. <br/>Она вызывала следующее сообщение об ошибке:++ ```+ Response.body: Protocol error (Network.getResponseBody): No resource with given identifier found+ ```++- API PlayWright иногда возвращает пустое описание статуса ответа. Теперь `Scrapling` определяет его самостоятельно, если это происходит. Изменение касается классов `StealthyFetcher` и `PlayWrightFetcher`.++## [v0.2.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.3) - 2024-11-19 {#v0.2.3}++### Что изменилось {#v0.2.3-what-s-changed}++##### Исправления ошибок {#v0.2.3-bugs-squashed}+- Исправлена ошибка установки через pip, из-за которой скрытный режим PlayWright Fetcher совсем не работал.++## [v0.2.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.2) - 2024-11-16 {#v0.2.2}++### Что изменилось {#v0.2.2-what-s-changed}+##### Новые возможности {#v0.2.2-new-features}+- Если вы не хотите передавать аргументы создаваемому объекту `Adaptor` и используете значения по умолчанию, теперь можно сделать код короче с помощью такого импорта:++ ```python+ >> from scrapling.default import Fetcher, StealthyFetcher, PlayWrightFetcher+ >> page = Fetcher.get('https://example.com', stealthy_headers=True)+ ```++ Иначе++ ```python+ >> from scrapling import Fetcher, StealthyFetcher, PlayWrightFetcher+ >> page = Fetcher(auto_match=False).get('https://example.com', stealthy_headers=True)+ ```++##### Исправления ошибок {#v0.2.2-bugs-squashed}+1. Исправлена ошибка объекта `Response`, появившаяся во вчерашнем патче v0.2.1. Она возникала в некоторых случаях вложенной выборки или разбора.++## [v0.2.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.1) - 2024-11-15 {#v0.2.1}++### Что изменилось {#v0.2.1-what-s-changed}+##### Новые возможности {#v0.2.1-new-features}+1. Объект `Response`, возвращаемый всеми Fetcher, теперь работает как `Adaptor`, но имеет дополнительные атрибуты: `status`, `reason`, `cookies`, `headers` и `request_headers`. Атрибуты `cookies`, `headers` и `request_headers` всегда имеют тип `dictionary`. <br/>Теперь код можно записать так:++ ```python+ >> from scrapling import Fetcher+ >> page = Fetcher().get('https://example.com', stealthy_headers=True)+ >> print(page.status)+ 200+ >> products = page.css('.product')+ ```++ Вместо прежнего варианта++ ```python+ >> from scrapling import Fetcher+ >> fetcher = Fetcher().get('https://example.com', stealthy_headers=True)+ >> print(fetcher.status)+ 200+ >> page = fetcher.adaptor+ >> products = page.css('.product')+ ```++ Но свойство `.adaptor` по-прежнему работает для обратной совместимости.++2. Классы `StealthyFetcher` и `PlayWrightFetcher` теперь принимают аргумент `proxy` в методе загрузки. Значением может быть строка или словарь.+3. В классе `StealthyFetcher` появился аргумент `os_randomize` для метода `fetch`. При включении Scrapling случайно выбирает отпечатки ОС. По умолчанию отпечатки соответствуют текущей ОС.++##### Исправления ошибок {#v0.2.1-bugs-squashed}+1. Исправлена ошибка при передаче заголовков в классе `Fetcher`.+2. Исправлена ошибка разбора JSON-ответов, переданных классами Fetcher.++##### Улучшения удобства {#v0.2.1-quality-of-life-changes}+1. Функция работы с текстом пыталась удалить HTML-комментарии перед возвратом текста, но в некоторых случаях это вызывало ошибки и излишне усложняло код. Теперь восстановлено стандартное поведение lxml. **Все операции, которые используют текст элементов, например селекторы, станут немного быстрее**. Если вы хотите удалять HTML-комментарии перед возвратом текста, чтобы избежать странного разделения текста в lxml/parsel/scrapy, оставьте аргумент `keep_comments` равным True, как по умолчанию.++## [v0.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2) - 2024-11-11 {#v0.2}++### Что изменилось {#v0.2-what-s-changed}+##### Новые возможности {#v0.2-new-features}+1. Добавлена возможность `Fetchers` с 3 основными типами, чтобы Scrapling загружал страницы за вас с МНОЖЕСТВОМ настроек!+ - Класс `Fetcher` для простых HTTP-запросов.+ - Класс `StealthyFetcher` представляет собой полностью скрытный Fetcher и использует [изменённую версию Firefox для скрытной работы](https://github.com/daijro/camoufox).+ - Класс `PlayWrightFetcher` позволяет выполнять браузерные запросы через обычный PlayWright, PlayWright с моим скрытным режимом, настоящие браузеры через CDP, а также через [NSTBrowser](https://app.nstbrowser.io/r/1vO5e5) с его [docker browserless](https://hub.docker.com/r/nstbrowser/browserless)!+2. Добавлены совершенно новые методы `find_all`/`find`, чтобы легко находить элементы на странице словно по волшебству!+3. Добавлены методы `filter` и `search` в класс `Adaptors`, упрощающие массовые операции над группами объектов `Adaptor`.+4. Добавлены методы `css_first` и `xpath_first` для более удобной работы.+5. Добавлен новый класс `TextHandlers` для массовых операций над объектами `TextHandler`, как в классе `Adaptors`.+6. Добавлены методы `generate_full_css_selector` и `generate_full_xpath_selector`.++##### Исправления ошибок {#v0.2-bugs-squashed}+1. В классе `Adaptors` метод `re_first` теперь возвращает первое совпадение среди всех вложенных объектов `Adaptor`, а не результаты `re_first` для всех объектов `Adaptor`, как было раньше по ошибке.+2. Если вы выбираете текст из элементов, например с помощью CSS-функции `::text`, через такие методы, как `.css` или `.xpath`, объект `Adaptor` теперь возвращает `TextHandlers`, а не список строк. Поэтому можно написать `page.css('something::text').re_first(r'regex_pattern').json()` вместо `page.css('something::text')[0].re_first(r'regex_pattern').json()`.+3. Аргументы re/re_first у `Adaptor`/`Adaptors` теперь согласованы с `TextHandler`. Доступны аргументы `clean_match` и `case_sensitive`.+4. Аргумент `auto_match` теперь включён по умолчанию при инициализации `Adaptor`, но для использования функции его всё равно нужно включить при выборке элементов. (Это не ошибка, так задумано.)+5. Исправлено много аннотаций типов для лучшего автодополнения при написании кода со Scrapling.++##### Улучшения удобства {#v0.2-quality-of-life-changes}+1. Методы `css_selector` и `xpath_selector` переименованы в `generate_css_selector` и `generate_xpath_selector`, чтобы названия были понятнее и не мешали автодополнению при написании кода.+2. Большая часть старого кода перенесена в подпакет `core`, также пересмотрены другие решения по структуре, чтобы код стал чище и проще в дальнейшей поддержке.+3. Папка тестов получила более понятную структуру, добавлены тесты новых возможностей. Окружения tox теперь кешируются на GitHub, чтобы ускорить автоматические тесты при каждом коммите.++## [v0.1.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.2) - 2024-10-16 {#v0.1.2}++**История изменений**:++- Исправлена ошибка, из-за которой аргумент `keep_comments` работал не так, как ожидалось.+- Функция работы с текстом теперь автоматически удаляет HTML-комментарии из элементов перед извлечением текста, чтобы избежать особого поведения Lxml. Например:++ ```python+ >>> page = Adaptor('<span>CONDITION: <!-- -->Excellent</span>', keep_comments=True)+ >>> page.css('span::text')+ ['CONDITION: ', 'Excellent']+ ```++ Раньше стандартное поведение Lxml давало показанный выше результат, а теперь возвращается полный текст 'CONDITION: Excellent'.+ Такое поведение известно и в parsel\scrapy, поэтому я решил обработать его здесь.++- Исправлена ошибка, из-за которой файл базы SQLite, созданный библиотекой, не удалялся при выполнении `pip uninstall scrapling` и похожих команд.++## [v0.1.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.1) - 2024-10-14 {#v0.1.1}++Мелкие исправления++## [v0.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1) - 2024-10-13 {#v0.1}++**Полная история изменений**: <https://github.com/D4Vinci/Scrapling/commits/v0.1>diff --git a/docs/locales/zh/changelog.md b/docs/locales/zh/changelog.mdnew file mode 100644index 0000000..6f7e950--- /dev/null+++ b/docs/locales/zh/changelog.md@@ -0,0 +1,1279 @@+---+title: "Scrapling 更新日志"+description: "Scrapling 各版本的发布说明,包括新功能、问题修复和不兼容变更。"+---++# 更新日志 {#changelog}++Scrapling 的所有重要变更,整理自 [GitHub 发布记录](https://github.com/D4Vinci/Scrapling/releases)。++## [v0.4.15](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.15) - 2026-08-23 {#v0.4.15}++**今年规模最大的版本之一:重构 MCP 服务器,一行代码生成可用于 RAG 的 Markdown,改进 Cloudflare 挑战处理,并让浏览器标签页保持打开以便继续自动化操作 🚀**++!!! warning "警告"++ **此版本对 MCP 服务器进行了不兼容变更。更新前请查看[不兼容变更](https://github.com/D4Vinci/Scrapling/blob/v0.4.15/docs/ai/mcp-server.md#breaking-changes)部分。**++### 🚀 新功能与使用体验改进 {#v0.4.15-new-stuff-and-quality-of-life-changes}++- **浏览器标签页现在会保持打开,并在后续请求中复用**(参见[文档](fetching/stealthy.md#session-management)):+ - 所有浏览器会话都会在请求结束后保留标签页,下一个请求会复用空闲标签页,而不是新开一个。+ - 每次请求都会将自己的设置(超时、请求头、资源拦截)重新应用到分配的标签页,因此不同请求的设置不会互相影响。+ - 出错的标签页会关闭并被替换,新增的 `close_pages()` 方法可以关闭所有打开的标签页。+ - 已获取的页面会保持加载状态,因此下一个请求中的 `page_setup` 函数会先在该页面上运行,再导航到其他页面。这是跨请求串联自动化操作的基础。++- **使用 `Response.markdown()` 将任意页面转为干净、适合 LLM 使用的 Markdown**(参见[文档](ai/building-rag-systems.md)):++ ```python+ from scrapling.fetchers import Fetcher++ markdown = Fetcher.get("https://example.com").markdown(main_content_only=True)+ ```++ - 始终先移除脚本、样式和隐藏的提示词注入内容,清理方式与 MCP 服务器相同。+ - 传入 `css_selector`,只转换需要的元素。+ - 通过新增的 `rag` 扩展安装项提供(`pip install "scrapling[rag]"`),`ai`/`shell`/`all` 也包含该扩展。++- **新增 `SiteToMarkdownSpider` 模板,将整个网站抓取为 Markdown 语料,用于 RAG 流程**(参见[文档](ai/building-rag-systems.md)):++ ```python+ from scrapling.spiders import SiteToMarkdownSpider++ class DocsSpider(SiteToMarkdownSpider):+ name = "docs"+ start_urls = ["https://example.com/docs/"]+ allowed_domains = {"example.com"}+ output_dir = "docs_markdown"++ result = DocsSpider().start()+ result.items.to_jsonl("docs.jsonl")+ ```++ - 每个页面生成一个包含 `url`/`title`/`markdown` 的数据项;可选的 `output_dir` 会为每个页面写入一个 Markdown 文件。+ - `max_pages` 限制抓取页面数量。由于模板基于 `CrawlSpider`,重写 `rules()` 即可完全控制要跟随哪些链接。++- **重构 MCP 服务器(不兼容变更)**(参见[不兼容变更](https://github.com/D4Vinci/Scrapling/blob/v0.4.15/docs/ai/mcp-server.md#breaking-changes)和[文档](ai/mcp-server.md)):+ - 13 个工具现在分为两种模式:单次调用工具(`fetch`、`bulk_fetch`、`stealthy_fetch`、`bulk_stealthy_fetch`)始终启动自己的浏览器,并显示真实的默认设置;会话工具则使用只需打开一次的会话。+ - 新增的 `session_fetch` 工具通过浏览器会话获取页面,`open_session` 现在只保存浏览器级设置,并将会话实际生效的设置返回给 AI 智能体。+ - `get` 工具更名为 `make_request`,现在支持任意 HTTP 方法。+ - 新增的 `open_request_session` 和 `session_make_request` 工具为 AI 提供持久化 HTTP 会话,在请求之间保留 Cookie 和浏览器指纹。+ - 这也解决了获取页面时重置会话设置的问题,该问题最初由 @Yigtwxx 在 [#418](https://github.com/D4Vinci/Scrapling/pull/418) 中修复。++- **MCP 服务器的 HTTP 传输现在要求身份验证,并默认只监听 localhost(不兼容变更)**,由 @yamantaka-singh 在 [#414](https://github.com/D4Vinci/Scrapling/pull/414) 中贡献(修复 [#413](https://github.com/D4Vinci/Scrapling/issues/413),参见[文档](ai/mcp-server.md#authentication)):+ - 传入 `--auth-token`(或使用环境变量 `SCRAPLING_MCP_AUTH_TOKEN`)来要求 bearer token;如果确实要禁用身份验证,则传入 `--no-auth`。+ - 传入 `--host 0.0.0.0` 以接受来自网络的连接。++### 🐛 问题修复 {#v0.4.15-bug-fixes}++- **Cloudflare Turnstile/Interstitial 挑战处理现在不受浏览器语言和地区设置影响,在无头模式下处理交互式挑战时也不再陷入死循环**。隐身浏览器页面在处理挑战的过程中也不再崩溃,包含 @subediparas5 在 [#412](https://github.com/D4Vinci/Scrapling/pull/412) 中的贡献。(修复 [#411](https://github.com/D4Vinci/Scrapling/issues/411) 和 [#422](https://github.com/D4Vinci/Scrapling/issues/422))+- **修复 `find`/`find_all` 使用 `class_` 时无提示地漏掉含多个 class 的元素的问题**,由 @yetval 在 [#410](https://github.com/D4Vinci/Scrapling/pull/410) 中贡献;**修复空白 `class_` 值及 CSS 字符串值未转义的问题**,由 @yamantaka-singh 在 [#417](https://github.com/D4Vinci/Scrapling/pull/417) 中贡献。+- **修复 `development_mode` 中重放缓存响应时丢失请求元数据的问题**,由 @Yigtwxx 在 [#419](https://github.com/D4Vinci/Scrapling/pull/419) 中贡献。+- **修复 `retries` 小于 1 时 HTTP 请求尚未发出就失败的问题**,由 @Yigtwxx 在 [#420](https://github.com/D4Vinci/Scrapling/pull/420) 中贡献。++### 文档 {#v0.4.15-docs}++- **重新组织网站栏目**:新增“与 AI 配合使用”栏目,包含 MCP 服务器、新的 [Agent Skill](ai/agent-skill.md) 页面和[构建 RAG 系统](ai/building-rag-systems.md)指南。BeautifulSoup 迁移指南移至“集成与迁移”栏目,与 Scrapy 集成放在一起。+- **向仓库添加[更新日志](changelog.md)**,包含迄今为止所有版本的发布说明。++## [v0.4.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.14) - 2026-08-10 {#v0.4.14}++**快速维护版本,修复使用 `uv` 安装的问题 🔧**++### 🐛 问题修复 {#v0.4.14-bug-fixes}++- **修复 `uv` 默认拒绝安装 v0.4.13,并在没有提示的情况下回退到旧版本的问题**。前一版本要求安装 `curl_cffi` 的预发布版本,而 `uv` 只有在明确启用后才允许这样做。+所有依赖现在都可以使用稳定版本。(修复 [#407](https://github.com/D4Vinci/Scrapling/issues/407))++## [v0.4.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.13) - 2026-08-09 {#v0.4.13}++**新版本带来了 Feed Spider 和更智能的 MCP 服务器 🎉**++### 🚀 新功能与使用体验改进 {#v0.4.13-new-stuff-and-quality-of-life-changes}++- **新增 Feed Spider 模板**。`XMLFeedSpider` 遍历任意 XML Feed 的节点(RSS、Atom、商品 Feed 等),`CSVFeedSpider` 将 CSV 行作为字典逐行处理。两者都会自动解压 gzip 压缩的 Feed。(参见[文档](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import XMLFeedSpider++ class RSSSpider(XMLFeedSpider):+ name = "rss"+ start_urls = ["https://example.com/feed.xml"]++ async def parse_node(self, response, node):+ yield {"title": node.findtext("title"), "link": node.findtext("link")}++ result = RSSSpider().start()+ ```++- **将 MCP 服务器升级至 MCP SDK v2,并改进智能体使用体验**。服务器现在提供说明,指导 AI 智能体高效使用工具;每个工具都声明注解,让 Claude Code 等客户端能自动批准只读工具;工具描述更简洁,减少 token 消耗;服务器还会向 MCP 客户端提供版本和徽标信息。(参见[文档](ai/mcp-server.md))+- **新增 `scrapling-mcp` 命令**,直接对应 `scrapling mcp`。对于只接受单个命令的 MCP 客户端和注册服务,现在只需一行命令即可注册 Scrapling。+- **不再固定 Playwright/Patchright 和浏览器版本**。生成的浏览器 User-Agent 现在始终匹配已安装的 Playwright/Patchright 实际使用的 Chromium 版本,因此 Scrapling 不再固定它们的版本,可以自由升级。更新后运行 `scrapling install --force` 来更新浏览器。++### 🐛 问题修复 {#v0.4.13-bug-fixes}++- **修复指纹数据包落后于浏览器版本时,导入 Scrapling 会因 `browserforge` 的 ValueError 而崩溃的问题**。(修复 [#394](https://github.com/D4Vinci/Scrapling/issues/394)、[#396](https://github.com/D4Vinci/Scrapling/issues/396) 和 [#400](https://github.com/D4Vinci/Scrapling/issues/400))+- **修复 MCP 批量浏览器工具的页面池大小设置错误的问题**。此错误会导致 `bulk_fetch` 在一批超过 50 个 URL 时失败,并让 `bulk_stealthy_fetch` 通过同一个标签页获取所有 URL。由 @Yigtwxx 在 [#393](https://github.com/D4Vinci/Scrapling/pull/393) 中贡献。++### 项目 {#v0.4.13-project}++- **新增 [AI 贡献政策](https://github.com/D4Vinci/Scrapling/blob/main/AI_POLICY.md)**:欢迎借助 AI 做贡献,但必须在 PR 或 issue 中说明;看起来使用了 AI 却未说明的提交会被添加标签并关闭。++## [v0.4.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.12) - 2026-07-26 {#v0.4.12}++**本次版本专注于让 Spider 更智能地应对所抓取的网站**++### 🚀 新功能与使用体验改进 {#v0.4.12-new-stuff-and-quality-of-life-changes}++- **Spider 现在可以通过 AutoThrottle 自动调整速度。** 不必再猜测一个可能过慢或导致封锁的 `download_delay`:Spider 会测量各网站的响应速度,并单独调整每个域名的延迟。当网站开始封锁或限流时,它会将延迟翻倍(或严格按 `Retry-After` 响应头要求的时长等待),直到恢复正常,然后再恢复速度。你设置的 `download_delay` 和 robots.txt 中的 `Crawl-delay` 仍会作为最小值。(参见[文档](spiders/advanced.md#autothrottle))++ ```python+ class MySpider(Spider):+ name = "adaptive"+ start_urls = ["https://example.com"]+ autothrottle_enabled = True+ autothrottle_start_delay = 2.0+ autothrottle_max_delay = 30.0+ autothrottle_block_backoff = True+ ```++- **支持将结果导出为 CSV 和 XML**,此外仍可使用已有的 JSON/JSONL 导出功能。即使数据项的键不同,也能完整导出,嵌套值会写成 JSON。(参见[文档](spiders/getting-started.md))++ ```python+ result = MySpider().start()+ result.items.to_csv("products.csv")+ result.items.to_xml("products.xml")+ ```++- **MCP 服务器现在可以要求身份验证**,因此可以安全地对外提供服务,而不必仅限于本机。缺少 token 的请求会被拒绝,也可以限制服务器响应的主机名。(参见[文档](ai/mcp-server.md))++ ```bash+ scrapling mcp --http --auth-token "$(openssl rand -hex 32)"+ ```++- **浏览器现在接受 HTTP 形式的 CDP URL**,不再只支持 WebSocket。除了托管浏览器服务提供的 `wss://` 端点,现在还可以将任意浏览器 Fetcher 或 MCP 会话连接到通过 `--remote-debugging-port=9222` 自行启动的 Chrome。++- **发布的 Docker 镜像现在带有版本号标签**,而不只是 `latest`,这样就可以固定使用所需的具体版本。由 @JanRK 在 [#384](https://github.com/D4Vinci/Scrapling/pull/384) 中贡献。++### 🐛 问题修复 {#v0.4.12-bug-fixes}++- **修复浏览器引擎生成的响应在缓存后丢失全部 Cookie 的问题**。此问题会让 Spider 开发模式中依赖 Cookie 的会话或身份验证逻辑在没有提示的情况下失效。由 @amitvijapur 在 [#379](https://github.com/D4Vinci/Scrapling/pull/379) 中贡献。(修复 [#376](https://github.com/D4Vinci/Scrapling/issues/376))++- **修复 `StealthyFetcher` 强制所有浏览器使用 `en-US` 语言和地区设置,而不是跟随系统设置的问题**。这会让网站发现语言和地区设置与 IP 地址不一致,并将其视为可疑行为,例如 Google 返回 429。(修复 [#381](https://github.com/D4Vinci/Scrapling/issues/381))++- **修复存储系统中一条容易误导的错误信息**,并移除插入操作后遗留的无用调用。由 @fix2015 在 [#377](https://github.com/D4Vinci/Scrapling/pull/377) 中贡献。++### 性能 {#v0.4.12-performance}++- **`get_all_text()` 的耗时现在与节点数量成正比(O(nodes))**,不再逐个遍历每个文本节点的祖先元素,在深层嵌套页面上的速度约为原来的 5-6 倍。由 @yetval 在 [#378](https://github.com/D4Vinci/Scrapling/pull/378) 中贡献。++## [v0.4.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.11) - 2026-07-12 {#v0.4.11}++**一次重要更新,带来首个特定平台 Spider 模板、更快的解析器和重要修复 🎉**++### 🚀 新功能与使用体验改进 {#v0.4.11-new-stuff-and-quality-of-life-changes}++- **新增 `ShopifySpider`,首个特定平台 Spider 模板!** 通过 Shopify 商店的 JSON API 提取所有商品,无需处理网站 HTML。继承该类,设置商店域名,就可以使用(参见[文档](spiders/platform-templates.md))++ ```python+ from scrapling.spiders import ShopifySpider++ class MyStore(ShopifySpider):+ target_website = "example.com"++ result = MyStore().start()+ ```++- **为 CLI 浏览器命令添加 `--executable-path`**。`scrapling extract fetch` 和 `scrapling extract stealthy-fetch` 现在都接受自定义的 Chromium 兼容浏览器可执行文件;没有传入该选项时,会使用环境变量 `SCRAPLING_EXECUTABLE_PATH`,与 MCP 服务器的功能保持一致(解决 [#371](https://github.com/D4Vinci/Scrapling/issues/371))++ ```bash+ scrapling extract fetch "https://example.com" page.html --executable-path "/path/to/chromium"+ ```++### 🤖 使用体验改进 {#v0.4.11-quality-of-life-changes}+- **`find_by_text` 和 `find_by_regex` 的速度最高提升到原来的约 2 倍**,适用于启用 `first_match`(默认设置)的情况。元素只在需要时转换成对象,因此搜索会在首个匹配处停止。由 @yetval 在 [#370](https://github.com/D4Vinci/Scrapling/pull/370) 中贡献+- **使用新数据更新基准测试,并与所有库的最新版本进行比较。**+- **更新贡献规则**++### 🐛 问题修复 {#v0.4.11-bug-fixes}++- **修复 MCP 服务器的页面获取工具在含有控制字符的页面上崩溃的问题**,错误信息为 `All strings must be XML compatible`。由 @yetval 在 [#368](https://github.com/D4Vinci/Scrapling/pull/368) 中贡献(修复 [#366](https://github.com/D4Vinci/Scrapling/issues/366))++## [v0.4.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.10) - 2026-07-04 {#v0.4.10}++**新版本带来全新的 Scrapy 集成和一批社区贡献的修复 🎉**++### 🚀 新功能与使用体验改进 {#v0.4.10-new-stuff-and-quality-of-life-changes}++- **新增 Scrapy 集成**,可以在现有 Scrapy 项目中使用 Scrapling 的解析 API,无需重写项目。给任意 Spider 回调添加 `scrapling_response` 装饰器,回调收到的响应就会变成 Scrapling 的 `Response`,同时仍由 Scrapy 负责抓取调度(参见[文档](integrations/scrapy.md)):++ ```python+ import scrapy+ from scrapling.integrations.scrapy import scrapling_response++ class QuotesSpider(scrapy.Spider):+ name = "quotes"+ start_urls = ["https://quotes.toscrape.com"]++ @scrapling_response+ def parse(self, response): # `response` is now a Scrapling Response+ first_quote = response.find_by_text("The world as we have created it", partial=True)+ for quote in [first_quote, *first_quote.find_similar()]:+ yield {"text": quote.get_all_text(strip=True)}+ ```++- **MCP 服务器现在可以为所有浏览器工具使用自定义的 Chromium 兼容浏览器**。通过 `scrapling mcp --executable-path "/path/to/chromium"` 或环境变量 `SCRAPLING_EXECUTABLE_PATH` 统一设置,也可以用 `executable_path` 参数逐个请求指定。由 @samrusani 在 [#360](https://github.com/D4Vinci/Scrapling/pull/360) 中贡献(解决 [#347](https://github.com/D4Vinci/Scrapling/issues/347))+- **更新所有浏览器和指纹**。更新后运行 `scrapling install --force` 以刷新它们。++### 🐛 问题修复 {#v0.4.10-bug-fixes}++- **修复浏览器 Fetcher 在非 UTF-8 网站上返回乱码(mojibake)的问题**,由 @yehudalevy-collab 在 [#365](https://github.com/D4Vinci/Scrapling/pull/365) 中贡献(修复 [#364](https://github.com/D4Vinci/Scrapling/issues/364))。+- **修复 `LinkExtractor` 无法过滤 `.tar.gz` 等复合文件扩展名的问题**,由 @renbkna 在 [#359](https://github.com/D4Vinci/Scrapling/pull/359) 中贡献(修复 [#349](https://github.com/D4Vinci/Scrapling/issues/349))。+- **修复暂停抓取时,检查点丢失执行中请求的问题,恢复后不再跳过这些请求**,由 @yetval 在 [#358](https://github.com/D4Vinci/Scrapling/pull/358) 中贡献。+- **通过升级 Protego,修复 Spider 根据 robots.txt 的 `Request-rate` 指令计算出错误抓取延迟的问题**,由 @Disaster-Terminator 在 [#355](https://github.com/D4Vinci/Scrapling/pull/355) 中同步调整测试。++### 文档 {#v0.4.10-docs}++- **说明隐身模式下 `init_script` 与 Patchright 隔离执行上下文的交互方式**,由 @mturac 在 [#353](https://github.com/D4Vinci/Scrapling/pull/353) 中贡献(解决 [#350](https://github.com/D4Vinci/Scrapling/issues/350))。+- **为 Agent Skill 添加通过 [skills.sh](https://skills.sh/D4Vinci/Scrapling) 安装的方式**,由 @ob-aion 在 [#363](https://github.com/D4Vinci/Scrapling/pull/363) 中贡献。++## [v0.4.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.9) - 2026-06-07 {#v0.4.9}++**维护更新,包含许多针对社区反馈问题的修复 🛠️**++### 🚀 新功能与使用体验改进 {#v0.4.9-new-stuff-and-quality-of-life-changes}++- **更新所有浏览器和指纹**。更新后运行 `scrapling install --force` 以刷新它们。+- **为 CLI 添加 `--version` 选项**,由 @ETM-Code 在 [#303](https://github.com/D4Vinci/Scrapling/pull/303) 中贡献(解决 [#299](https://github.com/D4Vinci/Scrapling/issues/299))++### 🐛 问题修复 {#v0.4.9-bug-fixes}++- **修复 HTTP 会话中无提示地忽略会话级 `proxy` 参数的问题**,这可能泄露真实 IP(解决 [#295](https://github.com/D4Vinci/Scrapling/issues/295))。现在,如果将会话级 `proxy` 与单次请求的 `proxies` 参数混用(或反过来),会直接报错,不再静默丢弃其中一个。+- **修复同时使用 `init_script` 和 `user_data_dir` 时浏览器导航失败的问题**(解决 [#294](https://github.com/D4Vinci/Scrapling/issues/294))。+- **修复网站在 `Content-Type` 响应头中用引号包裹 charset 值时的编码检测问题**,由 @Bortlesboat 在 [#323](https://github.com/D4Vinci/Scrapling/pull/323) 中贡献。+- **修复自适应元素重定位时出现的 `IndexError`,该问题发生在启用 `auto_save` 时**,由 @Mubashirrrr 在 [#340](https://github.com/D4Vinci/Scrapling/pull/340) 中贡献。+- **修复 Windows 上保存 Spider 检查点和缓存时崩溃的问题**,由 @MrStarkEG 在 [#344](https://github.com/D4Vinci/Scrapling/pull/344) 中贡献。+- **修复 `find_similar` 对属性数量不同的元素计算相似度不准确的问题**(解决 [#322](https://github.com/D4Vinci/Scrapling/issues/322))。++### 文档 {#v0.4.9-docs}++- **明确说明默认安装仅包含解析器引擎**,Fetcher 和 Spider 需要安装额外扩展(解决 [#343](https://github.com/D4Vinci/Scrapling/issues/343))。+- **修复其余示例中的 Docker 镜像名称**,由 @evanclan 在 [#315](https://github.com/D4Vinci/Scrapling/pull/315) 中贡献。+- **修复贡献指南中的失效链接**,由 @Bortlesboat 在 [#320](https://github.com/D4Vinci/Scrapling/pull/320) 中贡献。++## [v0.4.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.8) - 2026-05-11 {#v0.4.8}++**Spider 大更新,进一步改进抓取框架 🕷️**++### 🚀 新功能与使用体验改进 {#v0.4.8-new-stuff-and-quality-of-life-changes}++- **新增 `LinkExtractor` 工具**,位于 `scrapling.spiders.LinkExtractor`,用于从 `Response` 提取 URL,提供丰富的控制选项(参见[文档](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import LinkExtractor++ extractor = LinkExtractor(allow=r"/posts/", deny_domains=["ads.example.com"])+ ```++- **新增通用 Spider 模板 `CrawlSpider` 和 `CrawlRule`**,无需再重复编写“跟随符合某个模式的链接”这一类代码。重写 `rules()` 来返回 `CrawlRule` 对象列表,每个对象关联一个 `LinkExtractor`。(参见[文档](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import CrawlSpider, CrawlRule, LinkExtractor++ class QuotesSpider(CrawlSpider):+ name = "blog"+ start_urls = ["https://quotes.toscrape.com/"]++ def rules(self):+ return [+ CrawlRule(LinkExtractor(allow=r"/author/"), callback=self.parse_author),+ CrawlRule(LinkExtractor(allow=r"/page/\d+/")), # pagination, no callback+ ]++ async def parse_author(self, response):+ yield {+ "name": response.css(".author-title::text").get(),+ "birthday": response.css(".author-born-date::text").get(),+ "url": response.url,+ }+ ```++- **新增 `SitemapSpider` 模板**,直接从 sitemap 或 `robots.txt` URL 开始抓取。支持 gzip 压缩的 sitemap,并提供丰富的控制选项。URL 通过抓取规则分发,方式与上面的 **CrawlSpider** 示例相同。(参见[文档](spiders/generic-templates.md))++ ```python+ from scrapling.spiders import SitemapSpider, CrawlRule, LinkExtractor++ class NewsSitemap(SitemapSpider):+ name = "news"+ sitemap_urls = ["https://example.com/robots.txt"]++ def rules(self):+ return [+ CrawlRule(LinkExtractor(allow=r"/articles/"), callback=self.parse_article),+ ]++ async def parse_article(self, response):+ yield {"url": response.url, "title": response.css("h1::text").get()}+ ```++- **自适应重定位的所有方法现在默认使用 40% 相似度阈值**,不再使用 `0`,让自适应功能表现更好。如果没有元素超过阈值,会用警告显示找到的最高相似度,便于按需主动降低 `percentage`。++- **更新所有浏览器和指纹**。更新后重新运行 `scrapling install --force` 以刷新浏览器和指纹。++### 🐛 问题修复 {#v0.4.8-bug-fixes}++- **修复 `Fetcher.configure(...)` 没有应用到单次请求调用的问题**,同样修复了 `AsyncFetcher`。+- **修复请求指纹计算错误导致 Spider 重复请求的问题**,由 @yetval 在 [#255](https://github.com/D4Vinci/Scrapling/pull/255) 中贡献。+- **修复自适应抓取引擎在匹配度低时不发出提示的问题。** 配合上面的阈值调整,现在重定位失败时会给出警告,而不是返回一个容易误导的“最佳猜测”元素。++### 文档 {#v0.4.8-docs}++- **更新文档中的旧代码示例**,使其与当前版本一致。+- **改进文档网站的代码复制粘贴体验**,并精简 Agent Skill,减少每次调用消耗的 token。++## [v0.4.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.7) - 2026-04-17 {#v0.4.7}++**本次更新让 AI 智能体能够看到页面 📸**++### 🚀 新功能与使用体验改进 {#v0.4.7-new-stuff-and-quality-of-life-changes}++- **新增 MCP 工具 `screenshot`**,截取页面并返回真正的 MCP `ImageContent` 内容块,让模型可以直接看到图片。该工具需要打开的浏览器会话,因此先调用 `open_session`(使用 `dynamic` 或 `stealthy`),再在这里传入 `session_id`。支持 PNG 和 JPEG、整页截图、JPEG 质量设置,以及常用的就绪等待选项(`wait`、`wait_selector`、`network_idle`、`timeout`)。(实现 [#244](https://github.com/D4Vinci/Scrapling/issues/244))+- **新增自定义 `session_id` 参数,供 `open_session` 使用**,可以为会话取有意义的名字(`"search"`、`"checkout"`),不再局限于默认的 12 位随机十六进制字符串。由 @hauntedhost 在 [#243](https://github.com/D4Vinci/Scrapling/pull/243) 中贡献++### 🐛 问题修复 {#v0.4.7-bug-fixes}++- **修复 `FetcherSession` 状态损坏和延迟初始化会话关闭时崩溃的问题**,由 @yetval 在 [#245](https://github.com/D4Vinci/Scrapling/pull/245) 中贡献。+- **修复 `TypeError: Session.request() got an unexpected keyword argument 'block_ads'` 错误**,该错误出现在 CLI 的 `--ai-targeted` 选项用于 HTTP 命令时。由 @voidborne-d 在 [#249](https://github.com/D4Vinci/Scrapling/pull/249) 中贡献(修复 [#247](https://github.com/D4Vinci/Scrapling/issues/247))++### 翻译 {#v0.4.7-translations}++- **新增巴西葡萄牙语 README 翻译**,由 @rgomids 在 [#250](https://github.com/D4Vinci/Scrapling/pull/250) 中贡献++## [v0.4.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.6) - 2026-04-13 {#v0.4.6}++**本次更新专注于浏览器隐身、隐私和开发体验 🔒**++### 🚀 新功能与使用体验改进 {#v0.4.6-new-stuff-and-quality-of-life-changes}++- **为浏览器 Fetcher 添加内置广告拦截**。传入 `block_ads=True`,即可在路由拦截阶段阻止对约 3,500 个已知广告和跟踪域名的请求:不发起 DNS 或 TCP,立即中止。可与 `blocked_domains` 配合使用自定义列表。MCP 服务器和 CLI 的 `--ai-targeted` 模式会自动启用该功能,以减少 token 消耗并加快页面加载。++ ```python+ page = StealthyFetcher.fetch('https://example.com', block_ads=True)+ ```++- **新增 DNS-over-HTTPS 支持**,防止使用代理时泄露 DNS。传入 `dns_over_https=True`,通过 Cloudflare 的 DoH 服务发送 DNS 查询,避免 HTTP 流量经过代理时,DNS 解析仍暴露真实位置。++ ```python+ page = StealthyFetcher.fetch('https://example.com', proxy='http://proxy:8080', dns_over_https=True)+ ```++- **为浏览器 Fetcher 添加 `page_setup` 回调**。该函数在 `page.goto()` 之前执行,可以注册必须在页面导航前设置好的事件监听器、路由或脚本。它与 `page_action` 配合使用,后者在导航后运行。(解决 [#237](https://github.com/D4Vinci/Scrapling/issues/237))++ ```python+ def capture_websockets(page):+ page.on("websocket", lambda ws: print(f"WS: {ws.url}"))++ page = DynamicFetcher.fetch('https://example.com', page_setup=capture_websockets)+ ```++- **新增 CLI 选项 `--block-ads` 和 `--dns-over-https`,用于 `fetch` 和 `stealthy-fetch` 命令**。++### 🐛 问题修复 {#v0.4.6-bug-fixes}++- **修复 `Seconds` 类型别名拒绝浮点数的问题**。向浏览器 Fetcher 传入 `wait=1.5` 或 `timeout=500.0` 时曾会出现类型错误,因为类型别名错误地将 `float` 当成元数据,而不是类型。由 @kuishou68 在 [#240](https://github.com/D4Vinci/Scrapling/pull/240) 中贡献+- **修复生成完整路径选择器时 ID 片段重复的问题**。生成完整 CSS/XPath 路径时,带有 `id` 属性的元素,其选择器会被重复添加,得到 `body > #main > #main > #target > #target` 之类的选择器。同时修复完整 XPath 路径生成单独的条件 `[@id='x']`(无效 XPath),而不是 `*[@id='x']` 的问题。由 @sjhddh 在 [#241](https://github.com/D4Vinci/Scrapling/pull/241) 中贡献+- **补全 Shell 函数签名中缺少的参数**。交互式 Shell 的函数签名原先缺少 `blocked_domains`、`block_ads`、`retries`、`retry_delay`、`capture_xhr`、`executable_path` 和 `dns_over_https`。++## [v0.4.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.5) - 2026-04-07 {#v0.4.5}++**本次更新为 Spider 开发者带来一个大幅改善使用体验的功能,以及几项重要修复 🎉**++### 🚀 新功能与使用体验改进 {#v0.4.5-new-stuff-and-quality-of-life-changes}++- **Spider 开发模式**:以前修改 Spider 的 `parse()` 逻辑,每次运行都要重新访问目标服务器,既慢又会产生额外流量,还可能在调整选择器时就触发限流。新的开发模式会在首次运行时将每个响应缓存到磁盘,以后的运行直接从磁盘重放。这样就能反复修改回调并运行,而不发出任何网络请求。设置一个类属性即可启用:++ ```python+ class MySpider(Spider):+ name = "my_spider"+ start_urls = ["https://example.com"]+ development_mode = True++ async def parse(self, response):+ yield {"title": response.css("title::text").get("")}+ ```++ 缓存默认保存在 `.scrapling_cache/{spider.name}/`,可用 `development_cache_dir` 改到其他位置。新增的 `cache_hits` 和 `cache_misses` 统计项用于查看缓存表现。重放缓存会跳过 `download_delay`、限流和被封锁请求的重试流程,让调试速度只受磁盘速度限制。不要在生产环境中启用 `development_mode = True`;它是开发工具,不是生产缓存。完整说明见[文档](spiders/advanced.md#development-mode)。++- **默认使用更安全的重定向**:所有 HTTP Fetcher、MCP 服务器和 Shell 中,`follow_redirects` 的默认值现在为 `"safe"`。仍会跟随重定向,但会拒绝指向内部或私有 IP 的地址(回环地址、私有网络、链路本地地址)。这能在抓取用户提供的 URL 时防范 SSRF。传入 `follow_redirects="all"` 可恢复旧行为,传入 `False` 则完全禁用重定向。++### 🐛 问题修复 {#v0.4.5-bug-fixes}++- **强制停止不再丢失检查点**:对于启用 `crawldir` 的 Spider,连续按两次 Ctrl+C(强制停止)以前可能与检查点写入发生竞争。取消作用域会在 pickle 写入完成前结束任务,留下 `paused=False`,进而触发会*删除*旧检查点的清理流程。因此,强制停止长时间抓取可能丢失原本想保存的所有进度。引擎现在会在调用 `cancel_scope.cancel()` **之前**写入检查点,确保强制停止时始终保留最新的待处理状态。由 @voidborne-d 在 [#230](https://github.com/D4Vinci/Scrapling/pull/230) 中贡献。++## [v0.4.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.4) - 2026-04-05 {#v0.4.4}++**新版本带来重要的 Spider 改进和问题修复 🎉**++### 🚀 新功能与使用体验改进 {#v0.4.4-new-stuff-and-quality-of-life-changes}+- **为 Spider 框架添加 robots.txt 支持**,通过新的 `robots_txt_obey` 选项启用。启用后,Spider 会在抓取前自动获取并遵守 robots.txt 规则,包括 `Disallow`、`Crawl-delay` 和 `Request-rate`。robots.txt 文件会并发获取,并按域名缓存到整个抓取任务结束。由 @AbdullahY36 在 [#226](https://github.com/D4Vinci/Scrapling/pull/226) 中贡献+- **新增 robots.txt 缓存预热**,在抓取循环开始前获取并解析所有 start_urls 域名的 robots.txt,避免首次请求各域名时等待。+- **新增 `robots_disallowed_count` 统计项,加入 `CrawlStats`**,用于记录抓取过程中有多少请求被 robots.txt 规则阻止。++点击[这里](spiders/getting-started.md#robotstxt-compliance)查看网站上的说明++### 🐛 问题修复 {#v0.4.4-bug-fixes}+- **修复 `ProxyRotator` 中一个严重的 MRO 问题**:占位方法 `_build_context_with_proxy` 遮蔽了子类的实际实现,导致代理轮换总是抛出 `NotImplementedError`(修复 [#215](https://github.com/D4Vinci/Scrapling/issues/215))。感谢 @yetval+- **修复浏览器会话按请求轮换代理时的页面池泄漏**。临时上下文中创建的页面在清理时没有从池中移除,导致失效引用不断积累。由 @yetval 在 [#223](https://github.com/D4Vinci/Scrapling/pull/223) 中贡献+- **补充静态 Fetcher 中缺少的类型断言**。此前 `curl_cffi` 可能返回 `None` 作为 `session.request()` 的结果,进而引发后续错误。++### 其他变更 {#v0.4.4-other}+- 更新依赖,包含最新指纹和其他更新。+- 新增依赖 `protego`,放入可选的 `fetchers` 依赖组,用于解析 robots.txt。++## [v0.4.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.3) - 2026-03-30 {#v0.4.3}++**新版本包含许多重要变更 🎉**++### 🚀 新功能与使用体验改进 {#v0.4.3-new-stuff-and-quality-of-life-changes}+- **新增 MCP 工具**,用于打开持久化的普通或隐身浏览器,供其他工具继续使用;同时新增另一个工具来关闭它。([示例](https://github.com/D4Vinci/Scrapling/blob/v0.4.3/docs/ai/mcp-server.md#examples))+- **新增 MCP 工具**,列出所有现有浏览器会话,配合新工具使用。+- **为浏览器会话添加新选项**,自动收集一次请求期间产生的所有后台请求(解决 [#159](https://github.com/D4Vinci/Scrapling/pull/159))[[示例](https://github.com/D4Vinci/Scrapling/blob/v0.4.3/docs/fetching/dynamic.md#capturing-xhrfetch-requests)]。+- **新增内容清理功能**,移除隐藏或不可见的内容,保护 MCP 服务器免受常见提示词注入攻击。+- **为网页抓取命令添加 `--ai-targeted` 命令行选项**,让内容适合 AI 使用,并像 MCP 服务器一样防范常见的提示词注入攻击。+- **为浏览器会话添加 `executable_path` 选项**,允许指定自定义浏览器路径(解决 [#202](https://github.com/D4Vinci/Scrapling/pull/202))+- **重构** MCP 服务器代码,让维护更方便,并统一将所有工具改为异步。+- **重构** CLI 命令代码,让维护更方便,并减少 210 行代码。++### 🐛 问题修复 {#v0.4.3-bug-fixes}+- 修复 Spider 会话重试时没有保留 HTTP 方法的问题,由 @karesansui-u 在 [#201](https://github.com/D4Vinci/Scrapling/pull/201) 中贡献+- 为获取页面内容添加最大重试次数,避免死循环,由 @haosenwang1018 和 @D4Vinci 在 [#197](https://github.com/D4Vinci/Scrapling/pull/197) 中贡献+- 将不带参数的 `raise` 替换为 `return False`,应用于 `_restore_from_checkpoint`,由 @haosenwang1018 在 [#196](https://github.com/D4Vinci/Scrapling/pull/196) 中贡献+- 将 `get_all` 替换为 `getall`,让 `Texthandler` 与 Selector 类保持一致。++### 测试与覆盖率改进 {#v0.4.3-coverage-tests-improvement}+- 添加 `_normalize_credentials` 的边界情况测试,由 @Bortlesboat 在 [#192](https://github.com/D4Vinci/Scrapling/pull/192) 中贡献+- 添加保存后再读取的往返测试,以及核心存储的覆盖测试,由 @haosenwang1018 在 [#193](https://github.com/D4Vinci/Scrapling/pull/193) 中贡献+- 添加对 `TextHandler` 正则处理路径和 `TextHandlers.re()` 的测试覆盖,由 @haosenwang1018 在 [#194](https://github.com/D4Vinci/Scrapling/pull/194) 中贡献+- 添加 `filter`、`iterancestors` 和 `find_similar` 的边界情况测试,由 @awanawana 在 [#200](https://github.com/D4Vinci/Scrapling/pull/200) 中贡献++### Agent Skill 改进 {#v0.4.3-agent-skill-improvement}+- 修复 Skill 参考资料中的失效 Markdown 链接,由 @yetval 在 [#204](https://github.com/D4Vinci/Scrapling/pull/204) 中贡献+- 改进 Skill 结构,使其更符合 [Clawhub](https://clawhub.ai/d4vinci/scrapling-official) 的验证要求。+- 要求 Skill 通过命令行抓取时使用 `--ai-targeted` 选项。++### 文档改进 {#v0.4.3-docs-improvement}+- 添加韩语 README 翻译,由 @greatsk55 在 [#187](https://github.com/D4Vinci/Scrapling/pull/187) 中贡献+- 修复中文和日文 README 中 CJK 字符与拉丁字符之间的空格。+- 修复旧网站设计中遗留的失效链接。++## [v0.4.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.2) - 2026-03-08 {#v0.4.2}++**一次包含重要变更的维护更新**++#### 问题修复 {#v0.4.2-bug-fixes}+- `get_all_text()` 函数现在会获取元素结束标签后的文本节点。这让 MCP 服务器和命令能够读取之前遗漏的文本([#168](https://github.com/D4Vinci/Scrapling/pull/168))。感谢 @mhillebrand+- Referer 现在使用 Google 首页 URL,而不是 Google 搜索 URL。之前的逻辑不正确,可能留下可用于指纹识别的特征([#179](https://github.com/D4Vinci/Scrapling/pull/179))。感谢 @Bortlesboat+- 修复了所有浏览器中额外启动参数的拼接问题。感谢 @rostchri+- 修复了在低于 3.12 的 Python 版本中导致程序崩溃的类型提示问题。(解决 [#163](https://github.com/D4Vinci/Scrapling/issues/163))++#### 其他 {#v0.4.2-other}+- 为 Claude Code / OpenClaw 和其他 AI 智能体工具添加了 Agent Skill。+- 将 Agent Skill 添加到了 Clawhub。+- 将所有浏览器和 Playwright 更新到最新版本。+- 为主 README 文件添加了法语翻译。++## [v0.4.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4.1) - 2026-02-27 {#v0.4.1}++**一次包含多项重要变更的新更新**++### 🚀 新功能与使用体验改进 {#v0.4.1-new-stuff-and-quality-of-life-changes}+- **提高了正则表达式的准确性**,使 Cloudflare 验证检测更准确(感谢 @Rinz27 [#133](https://github.com/D4Vinci/Scrapling/pull/133))+- **提高了 Cloudflare 验证处理的速度和效率**。现在的速度接近原来的两倍。+- **改进了 Cloudflare 验证处理逻辑**,能够应对某些网站在跳转到主站之前连续两次显示 Cloudflare 验证页面的情况。+- 通过移除注入的 JS 文件,**提高了隐身浏览器的隐蔽性和速度**。+- **改进了 MCP schema**,使 OpenCode 能够接受它(感谢 @robin-ede [#137](https://github.com/D4Vinci/Scrapling/pull/137))+- **进一步改进了 MCP schema 的兼容性**,使 VS Code Copilot 和其他要求严格的工具能够接受它。(解决 #150)+- 启用 `main_content_only` 选项时会移除无用的 HTML 标签,**大幅减少了 MCP 服务器的 token 用量**。+- 修复了 PyPI 页面,并添加了将 MCP 服务器注册到 MCP 服务器注册表所需的文件。+- 添加了新的代码示例,展示如何通过代码安装浏览器依赖,而不必使用命令行,让自动化更方便。+- 将所有工作流中的 actions 更新到最新版本(感谢 @salmanmkc [#143](https://github.com/D4Vinci/Scrapling/pull/143)/[#144](https://github.com/D4Vinci/Scrapling/pull/144))++## [v0.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.4) - 2026-02-15 {#v0.4}++**Scrapling 迄今为止最大的一次发布:推出 Spider 框架、代理轮换和重要的解析器改进**++这个版本带来了全异步爬虫框架、智能代理管理和重要的 API 变更,让 Scrapling 更强大、更一致。升级前请仔细阅读不兼容变更部分。++### 🕷️ Spider 框架 {#v0.4-spider-framework}++基于 `anyio` 的全新异步爬虫框架,适合有组织的大规模抓取:++```python+from scrapling.spiders import Spider, Response++class MySpider(Spider):+ name = "demo"+ start_urls = ["https://example.com/"]++ async def parse(self, response: Response):+ for item in response.css('.product'):+ yield {"title": item.css('h2::text').get()}++MySpider().start()+```++- **类似 Scrapy 的 Spider API**:通过 `start_urls`、异步 `parse` 回调、`Request`/`Response` 对象和优先队列定义爬虫。+- **并发抓取**:可设置并发上限、按域名限速和下载延迟。+- **多会话支持**:在同一个爬虫中,通过统一接口使用 HTTP 请求和隐身无头浏览器,按 ID 将请求分配给不同会话。支持按需初始化会话。+- **暂停与恢复**:通过检查点保存抓取进度。按 Ctrl+C 安全关闭,再次启动即可从停止的位置继续。+- **流式模式**:通过 `async for item in spider.stream()` 实时接收抓取到的数据,并查看实时统计,适合 UI、数据处理流程和长时间运行的抓取任务。+- **被拦截请求检测**:自动检测并重试被拦截的请求,支持自定义逻辑。+- **内置导出**:可通过钩子和自己的数据处理流程导出结果,也可以分别使用内置的 `result.items.to_json()` / `result.items.to_jsonl()` 导出 JSON/JSONL。+- **生命周期钩子**:通过 `on_start()`、`on_close()`、`on_error()`、`on_scraped_item()` 等钩子全面控制抓取过程。+- **详细抓取统计**:记录请求、响应、字节数、状态码、代理、按域名和会话分类的数据、各日志级别的数量等信息。+- **uvloop 支持**:将 `use_uvloop=True` 传给 `spider.start()`,可在 uvloop 可用时加快异步执行。++文档网站新增了介绍完整细节的章节。点击[这里](spiders/architecture.md)查看。++### 🔄 代理轮换 {#v0.4-proxy-rotation}++* 新增 `ProxyRotator` 类,支持线程安全的代理轮换。适用于所有 Fetcher 和会话:++ ```python+ from scrapling import ProxyRotator+ rotator = ProxyRotator(["http://proxy1:8080", "http://proxy2:8080"])+ Fetcher.get(url, proxy_rotator=rotator)+ ```++* **自定义轮换策略**:编写自己的代理轮换逻辑。+* **为单次请求指定代理**:将 `proxy=` 传给任意一次 `get()`/`post()`/`fetch()` 调用,即可为该请求覆盖会话代理。++### 🌐 浏览器 Fetcher 改进 {#v0.4-browser-fetcher-improvements}++* **域名拦截**:新增 `blocked_domains` 参数,可用于 `DynamicFetcher`/`StealthyFetcher`,阻止向指定域名发送请求(自动匹配子域名)。+* **自动重试**:浏览器 Fetcher 现在会在失败时重试,通过 `retries`(默认:3)和 `retry_delay`(默认:1s)参数控制,并能识别代理相关错误。+* **响应元数据**:`Response.meta` 字典会自动保存所用的代理,并合并请求元数据。+* **Response.follow()**:创建后续 `Request` 对象,自动传递 Referer,专为爬虫系统设计。+* **禁止自动播放**:浏览器会话现在会阻止内容自动播放,避免之前出现的问题。+* **速度**:通过调整浏览器启动参数,提高了隐蔽性和速度。++### 🔧 问题修复与改进 {#v0.4-bug-fixes-improvements}+- **解析器优化**:针对重复操作优化了解析器,提高了性能。+- **页面错误**:修复了页面报错时浏览器无法关闭的问题。+- **空响应体**:支持处理响应体为空的响应。+- **Playwright 事件循环**:解决了 CDP 连接失败时 Playwright 事件循环未关闭的问题。+- **类型安全**:修复了所有 mypy 错误,并为没有类型标注的函数体补充了类型提示。在 CI 工作流中添加了 mypy 和 pyright。++### ⚠️ 不兼容变更 {#v0.4-breaking-changes}++* **移除了 `css_first`/`xpath_first`**:请改用 `css('.selector').first`、`css('.selector')[0]` 或 `css('.selector').get()`。+* **所有选择操作现在都返回 `Selectors`**:`css('::text')`、`xpath('//text()')`、`css('::attr(href)')` 和 `xpath('//@href')` 现在返回 `Selectors`(文本节点被包装为 `Selector` 对象,并带有 `tag="#text"`),不再返回 `TextHandlers`。这样,所有选择方法及其类型提示都保持一致。+* **`Response.body` 始终为 `bytes`**:之前可能是 `str` 或 `bytes`,现在始终返回 `bytes`。+* **`get()`/`getall()` 的行为**:在 `Selector` 上,`get()` 返回 `TextHandler`(序列化后的 HTML 或文本值),`getall()` 返回 `TextHandlers`。别名为 `extract_first = get`、`extract = getall`。旧的 `get_all()` 已从 `Selectors` 中移除。+* **`Selectors.first`/`.last`**:可安全访问元素,返回 `Selector | None`,不会抛出 `IndexError`。+* **内部常量重命名**:`DEFAULT_FLAGS` → `DEFAULT_ARGS`、`DEFAULT_STEALTH_FLAGS` → `STEALTH_ARGS`、`HARMFUL_DEFAULT_ARGS` → `HARMFUL_ARGS`、`DEFAULT_DISABLED_RESOURCES` → `EXTRA_RESOURCES`。++### 🔨 其他变更 {#v0.4-other-changes}++* **依赖变更**:将 `tldextract` 替换为 `tld`,移除了内部的 `_html_utils.py`,改用 `w3lib.html.replace_entities`,并将 `typing_extensions` 加为必需依赖。+* **文档全面更新**:从 MkDocs 完全切换到 Zensical,新增爬虫文档章节,更新所有已有页面,并添加新的 API 参考。++## [v0.3.14](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.14) - 2026-01-03 {#v0.3.14}++**一次小型维护更新,修复 v0.3.13 在部分设备上出现的问题**++- 禁用了 `StealthyFetcher` 及其会话类的无痕模式,因为它会导致 Windows 设备上的 Cookie 无法在页面之间保留。MacOS 和 Linux 没有这个问题(修复 [#123](https://github.com/D4Vinci/Scrapling/issues/123),感谢 @frugality4121 提出问题,也感谢 @gembleman 指出解决方法)。+- 固定使用 browserforge 的最新版本,解决已有旧版 browserforge 的用户遇到的请求头模型过旧问题。++## [v0.3.13](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.13) - 2026-01-01 {#v0.3.13}++**这是一次大型更新,改进了多个方面,也出于必要原因引入了多项不兼容变更。更新前请阅读以下内容。**++* 出于多方面的原因,我们决定从现在起完全停止使用 Camoufox。如果它继续开发,我们以后可能会重新采用它。如果你想像这个版本之前一样继续使用 Camoufox,请参阅[这一节](https://github.com/D4Vinci/Scrapling/blob/v0.3.13/docs/fetching/stealthy.md#using-camoufox-as-an-engine)中的说明。++* 之前,我们在 `DynamicFetcher` 及其会话类的隐身模式中使用 patchright。现在移除了它们的隐身模式,改为在 `StealthyFetcher` 及其会话类中使用 patchright。我们还做了大量改进,进一步增强了 patchright 基础上的整体隐蔽性,具体见下文。++**这让 `StealthyFetcher` 及其会话类的速度提高了 101%,内存和空间用量更少,代码减少了约 400 行。更重要的是,它们比之前使用 Camoufox 时更稳定。**++这也会缩短 `scrapling install` 命令的安装时间,减小 Docker 镜像,让 GitHub CI 中的测试更顺畅,并让新用户更容易理解 Scrapling。++### 不兼容变更 {#v0.3.13-breaking-changes}+1. `stealth` 参数已从 `DynamicFetcher` 类及其会话类中移除,`hide_canvas` 参数则移到了 `StealthyFetcher` 及其会话类。+2. 将 `disable_webgl` 参数从 `DynamicFetcher` 移到了 `StealthyFetcher` 类,并重命名为 `allow_webgl`。所有会话类也做了相同调整。+3. `StealthyFetcher` 类现在基本上是 `DynamicFetcher` 的新版隐身版本,因此移除了以下参数:`block_images`、`humanize`、`addons`、`os_randomize`、`disable_ads` 和 `geoip`。我尝试在 Chromium 中实现这些功能,但每个都有自己的问题。这可能会在 v0.4 之前的后续版本中改变。++接下来是好消息,我们做了很多改进和修复 :)++### 改进 {#v0.3.13-improvements}+- 你已经知道,`StealthyFetcher` 类及其会话类的速度提高了 101%。现在,`DynamicFetcher` 类及其会话类的速度也提高了 20%。+- 改进了 Cloudflare 验证处理算法,使其更快完成,并能处理更多情况。由于这次重构,验证码处理速度也提高到原来的两倍!+- 所有 Fetcher 的内存用量都减少了。+- MCP 服务器现在使用更少的 token,帮你节省更多费用!+- Docker 镜像现在缩小了 60%。+- 整个文档网站都更新了新内容。同时,说明更清楚,多个章节更精简,新增了更多示例,补全了遗漏的参数,并为 API 参考添加了图表,还有许多其他改进。网站加载速度现在提高了 130%,流量更少,也更利于 SEO。++### 问题修复 {#v0.3.13-fixes}+- 为网页抓取 Shell 的快捷方法补全了之前遗漏的参数,并让它们更准确。+- 修复了即使 URL 为 localhost/IP,`google_search` 参数仍会创建 Google Referer 的问题。++## [v0.3.12](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.12) - 2025-12-18 {#v0.3.12}++### 更新内容 {#v0.3.12-what-s-changed}+- 为 `DynamicSession`/`AsyncDynamicSession` 类添加了 `timezone_id` 参数,可以设置浏览器时区,使其与使用的代理或 VPN 的时区一致。这样,网站就无法通过时区不一致来发现你使用了代理。+- 改进了将响应自动转换为 JSON 的处理方式。+- 将 Fetcher 会话类中的内部函数 `__create__` 重命名为 `start`,更方便在 `with` 上下文之外使用这些会话类。+- 将 `curl_cffi` 和其他依赖更新到最新版本。++## [v0.3.11](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.11) - 2025-12-03 {#v0.3.11}++### 更新内容 {#v0.3.11-what-s-changed}+- 改进了在不稳定的网站(如正在播放媒体的网站)上使用 `network_idle` 参数时的超时错误处理逻辑。+- 修复了网页抓取 Shell 中 `stealthy_fetch` 快捷方法的自动补全。++## [v0.3.10](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.10) - 2025-11-26 {#v0.3.10}++**一次包含多项重要变更和潜在不兼容变更的维护更新**++- **解决了**所有编码问题,采用更好的方法处理未正确声明编码的网页(感谢 @Kemsty2 在 [#110](https://github.com/D4Vinci/Scrapling/issues/110) [#111](https://github.com/D4Vinci/Scrapling/pull/111) 中指出这个问题)。+- **解决了**所有浏览器 Fetcher 中从 v0.3 起就存在的逻辑问题:请求级参数无法正确覆盖会话级参数。+- **修复了**交互式网页抓取 Shell 中快捷方法的函数签名,使快捷方法在 Shell 中能够准确自动补全。这个问题也从 v0.3 起就存在。+- **更新了** Maxmind 数据库版本,改善了 `geoip` 参数在 `StealthyFetcher` 及其会话类中的效果。+- **更新了**所有使用的浏览器,均升级到了最新版本。+- **不兼容变更**:所有 Fetcher 都经过了大规模重构,带来了一些可能影响现有代码的变化:+ 1. Scrapling 代码减少了约 750 行,还做了多项调整,让后续维护更简单,资源用量也略有减少。+ 2. 所有 Fetcher 及其会话类的参数校验都变得更快,从而提高了整体速度。+ 3. 为此,所有 Fetcher 现在只允许 `url` 使用位置参数,其余都必须使用关键字参数。因此,如果你之前写的是位置参数形式,现在必须写成 `Fetcher.get('https://google.com', stealthy_headers=True)`,不能写成 `Fetcher.get('https://google.com', True)`!+ 4. 从 v0.3 起,浏览器 Fetcher 及其会话类之间一直存在一个不便之处:为单次请求传入自定义解析器设置的参数在 Fetcher 中叫 `custom_config`,在会话类中却叫 `selector_config`。这次重构在不影响现有代码的情况下,将名称统一为 `selector_config`。现在主要使用 `selector_config`,同时向后兼容 `custom_config` 参数。只有 `selector_config` 参数支持自动补全。+ 5. 为了实现这些改进,我们还改为动态生成 Fetcher 函数的类型提示。如果 IDE 无法正确自动补全,请确保使用较新的版本。我们测试了几乎所有常见的 IDE 和编辑器。++> 我们还更新了所有基准测试表,使用当前结果与所有同类库的最新版本进行对比。++## [v0.3.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.9) - 2025-11-17 {#v0.3.9}++**一次包含多项重要变更的新更新**++### 🚀 新功能与使用体验改进 {#v0.3.9-new-stuff-and-quality-of-life-changes}+- `impersonate` 参数现在可以接收浏览器列表;`Fetcher` 和 `FetcherSession` 每次请求都会从中随机选择一个浏览器。++```python+from scrapling.fetchers import FetcherSession++with FetcherSession(impersonate=['chrome', 'firefox', 'safari']) as s:+ s.get('https://github.com/D4Vinci/Scrapling')+```++- 为 `clean` 方法添加了新参数,这个方法属于 `TextHandler`,可以方便地移除当前文本中的 HTML 实体。+- 大幅改进了文档,更准确地解释了多个部分,并为主 `README.md` 文件添加了自动翻译。++### 🐛 问题修复 {#v0.3.9-bug-fixes}+- 修复了从浏览器 Fetcher 获取响应时的一个重要问题。现在会智能检测内容类型,确保只有 HTML 内容才会让 `response.body` 包含浏览器渲染后的内容;其他类型则包含最后一次请求的原始内容。这样,下载二进制文件和文本文件时,内容不会被 HTML 标签包裹,同时获取网页时仍能得到所需的渲染后内容。++### 🔨 其他 {#v0.3.9-misc}+- 更新了贡献指南,让说明更清楚、更易懂。+- 添加了新的工作流,强制运行代码质量工具(与 pre-commit 钩子中使用的工具相同)。++## [v0.3.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.8) - 2025-10-27 {#v0.3.8}++**一次包含多项重要变更的新更新**++### 🚀 新功能与使用体验改进 {#v0.3.8-new-stuff-and-quality-of-life-changes}+- 对所有浏览器 Fetcher,使用 `network_idle` 时,即使网站的请求始终没有全部完成,也不再导致代码崩溃。+- 调整了浏览器 Fetcher 获取和检查页面内容的逻辑,让浏览器在 Windows 上也能像在 Linux/MacOS 上一样稳定(这种行为差异来自 Playwright 在 Windows 上的不同实现)。+- 重构了所有校验逻辑,让所有浏览器 Fetcher 的请求速度提高了 8-15%。+- 新增 `extra_flags` 选项,可用于 `DynamicFetcher` 及其会话,让用户在启动浏览器时可以在已有 Chrome 启动参数之外添加自定义参数。+- 调整了上一版本修改的响应捕获路由逻辑:使用 `page_action` 时恢复旧版路由方式。这样,即使 `page_action` 修改了页面却没有发送请求,也能获取最新的页面内容。(感谢 @gembleman 在 [#100](https://github.com/D4Vinci/Scrapling/issues/100) 和 [#102](https://github.com/D4Vinci/Scrapling/pull/102) 中指出问题。)++### 🐛 问题修复 {#v0.3.8-bug-fixes}+- 修复了 DynamicSession 的 async_fetch 中 `load_dom` 的拼写错误。+- 修复了 Cloudflare 验证处理逻辑的一个问题:某些嵌入式验证码在验证完成后不会消失,导致程序一直等待。现在最多等待验证码消失 30 秒,然后将其视为不会消失的类型(修复 #100)。++### 🔨 其他 {#v0.3.8-misc}+- 现在会自动将 Docker 镜像推送到 Dockerhub 和 GitHub 容器注册表,方便用户使用。+- 添加了[新文档页面](https://github.com/D4Vinci/Scrapling/blob/v0.3.8/docs/tutorials/external.md),介绍如何在 Scrapling 中使用 Scrapeless 浏览器。++## [v0.3.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.7) - 2025-10-12 {#v0.3.7}++**一次包含多项重要变更的新更新**++### 🚀 新功能与使用体验改进 {#v0.3.7-new-stuff-and-quality-of-life-changes}+- 重新设计了 `solve_cloudflare` 参数在 `StealthyFetcher` 中的处理逻辑,使其能够处理各种自定义 Turnstile 实现。+- 重构了整个代码库,使其通过 Pyright 检查。现在各类 IDE 中的使用体验都更完善,也修复了许多问题。+- 重构了请求逻辑,使其更清晰、更快(同时解决 #97)。+- 为所有浏览器会话类添加了 `user_data_dir` 选项,让用户可以复用之前会话的浏览器数据(Cookie、存储等)。不设置时,Playwright 仍会像以前一样在每次运行时使用随机目录。+- 新增 `additional_args` 自定义选项,可用于 `Dynamic fetcher` 及其会话类,让用户可以向 Playwright 上下文传入额外参数,就像之前的 `StealthyFetcher` 一样。+- 改进了所有浏览器中获取最后一次导航响应的路由逻辑。现在原始响应会在浏览器处理前传给解析器,而不是像以前那样先由浏览器处理。这对文本和 JSON 响应很有帮助。++### 🐛 问题修复 {#v0.3.7-bug-fixes}+- 路由逻辑的重写解决了在部分 Windows 设备上获取不稳定网站内容的问题。+- 这个版本中的多项重构同时解决了许多之前难以发现的问题,以及部分 IDE 中奇怪的自动补全问题。+- 修复了文档网站的多处问题。++## [v0.3.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.6) - 2025-10-01 {#v0.3.6}++### 🚀 新功能 {#v0.3.6-new-stuff}+- 改进了 `solve_cloudflare` 参数在 `StealthyFetcher` 及其会话类中的处理逻辑,使其能够处理所有类型的 Turnstile 和 Cloudflare 中间验证页面 🎉+- MCP 服务器现在可选择使用 `Streamable HTTP`,方便对外提供服务。+- 添加了 Docker 支持,每次发布时都会自动构建镜像并推送到 Docker Hub(包含所有浏览器)。++### 🐛 问题修复 {#v0.3.6-bug-fixes}+- 修复了解析器在某些情况下出现的编码问题(常见的 `invalid start byte` 错误)。+- 调整了库中多个部分的结构,修复了一些内存泄漏问题。根据配置不同,现在内存用量会明显减少(同时解决 #92)。+- 改进了多处代码的类型标注,让 IDE 使用体验更好(同时解决 #93)。++## [v0.3.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.5) - 2025-09-20 {#v0.3.5}++**修复多项问题的重要版本**++### 🚀 新功能 {#v0.3.5-new-stuff}+- 所有浏览器 Fetcher(`DynamicFetcher`/`StealthyFetcher`/...)及其会话类的网页获取速度现在提高了 15-20%:+ 1. 得益于 @AbdullahY36 在 #87 中对逻辑的改进,页面管理现在快了很多。+ 2. 整体优化了校验逻辑,并改进了同步获取时的页面创建,两者一起带来了明显的速度提升。++- 将 `DynamicFetcher` 及其会话类中的 `rebrowser-playwright` 替换为 `PatchRight`,大幅改进了隐身模式:+ 1. 之前,`rebrowser-playwright` 会在同时启用 `stealth` 和 `real_chrome` 时关闭,因为它们无法很好地配合。现在使用 `PatchRight` 后不再有这个问题。+ 2. 现在可以操作封闭的 Shadow Root,因为 `PatchRight` 会自动处理它们。++### 🐛 问题修复 {#v0.3.5-bug-fixes}+- 修复了使用 `re` 方法时出现的问题,该方法属于 `Selectors` 类。+- 修复了网页抓取 Shell 中 `uncurl` 和 `curl2fetcher` 命令错误解析 curl 的 `--data-raw` 参数的问题。+- 修复了网页抓取 Shell 中 `view` 命令在某些网站编码下出现的问题。+- 修复了影响 `mcp` 模式和 `extract` 命令的内容转换问题。++### 新贡献者 {#v0.3.5-new-contributors}+- @AbdullahY36 在 #87 中做出了首次贡献。++## [v0.3.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.4) - 2025-09-16 {#v0.3.4}++**修复多项问题的重要版本**++### 🚀 新功能 {#v0.3.4-new-stuff}+- 将所有 Fetcher 会话类添加到交互式 Shell 中,无需导入即可直接使用。++### 🐛 问题修复 {#v0.3.4-bug-fixes}+- 为 Windows 上 Playwright API 的一个问题添加了应对方法,该问题出现在处理 Cloudflare 验证时获取页面内容的过程中。+- 修复了交互式 Shell 中 `view` 命令的编码问题。+- 修复了 `max_pages` 参数在 `AsyncStealthySession` 中导致代码崩溃的问题。+- 修复了最近更新引入的问题:`html_content` 和 `prettify` 这两个 `Selector` 类的属性在某些编码下会返回 bytes。现在两者都和之前一样返回字符串。++## [v0.3.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.3) - 2025-09-15 {#v0.3.3}++- 移除了浏览器 Fetcher 中关闭默认标签页的逻辑,因为它会导致崩溃(Mac 上没有出现,只在 Windows 和 Linux 上复现)。++## [v0.3.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.2) - 2025-09-15 {#v0.3.2}++v0.3.2 发布说明++### 🚀 新功能 {#v0.3.2-new-stuff}++- **可选的 Fetcher 依赖**:所有 Fetcher 现在都属于可选依赖组,减小了核心包的体积。因此,基础 `scrapling` 模块现在只包含解析器。要使用 Fetcher 或命令行选项,需要运行:`pip install "scrapling[fetchers]"`。详细安装说明见[这里](index.md#installation)。+- **会话中的单页面配置**:浏览器 Fetcher 的会话类现在支持为会话内的每个页面单独配置。每次获取页面时传入的参数现在都会像会话级参数一样进行校验。更多说明见[文档网站](fetching/stealthy.md#full-list-of-arguments)。+ <br>示例:++ ```python+ with StealthySession(headless=True, solve_cloudflare=True) as session:+ page = session.fetch('https://nopecha.com/demo/cloudflare', google_search=False)+ ```++- **浏览器 Fetcher 改进**+ - 新增选项,可控制是否等待页面中的 JavaScript 执行完成(和之前一样,默认启用)。++ ```python+ with DynamicSession(headless=True, disable_resources=False, network_idle=True) as session:+ page = session.fetch('https://quotes.toscrape.com/', load_dom=False)+ ```++ - `DynamicFetcher` 及其会话类的隐身模式现在更可靠。+ - `DynamicFetcher` 和 `StealthyFetcher` 现在都使用更少的资源(自动查找并关闭 Playwright API 持久上下文打开的默认标签页)。+ - 修复了浏览器 Fetcher 页面轮换中的重要逻辑问题:现在会用新页面替换旧页面。(重复使用的标签页可能残留之前使用过的设置。)+ - `StealthyFetcher` 及其会话类现在略快一些(5%)。++- **增强了 `.body` 属性**:现在原样返回传入的内容,不做处理,支持下载文件和处理非 HTML 请求。下面是下载图片的示例:++ ```python+ from scrapling.fetchers import Fetcher++ page = Fetcher.get('https://raw.githubusercontent.com/D4Vinci/Scrapling/main/images/poster.png')+ with open(file='poster.png', mode='wb') as f:+ f.write(page.body)+ ```++### 🐛 问题修复 {#v0.3.2-bug-fixes}++- **解决编码问题**:修复了解析器、mcp 模式和 extract 命令在部分网站上出现的多个编码问题(同时解决 #80 和 #81)。+- **解析更快**:通过多处改进,库的运行速度更快了,更新后的基准测试也体现了这一点。++### 🔨 其他 {#v0.3.2-misc}++- **更新基准测试**:更新了性能基准测试,将当前的速度改进与同类库的最新版本进行对比。+- **重构了大量代码,并用更好的实现替换了无用代码**:代码更少、更清晰,也更容易维护。+- **添加 YouTube 视频**:为 MCP 文档添加了视频内容。+- **新的问题模板**:为无法使用现有模板的用户提供了简单的新模板。+- **CI 工作流优化**:仅修改文档或非代码文件时,测试工作流现在会跳过运行。+- **更新依赖**:将多项依赖升级到了最新版本。+- **代码风格改进**:对所有文件应用了新的 ruff 规则。+- **Pre-commit 钩子**:更新了 pre-commit 配置。++### 🎯 不兼容变更 {#v0.3.2-breaking-changes}++- 移除了 `max_pages` 参数在同步 `StealthySession` 中的支持,与 `DynamicSession` 保持一致(这个参数在同步版本中没有意义)。++## [v0.3.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3.1) - 2025-09-02 {#v0.3.1}++1. 修复了不安装 `shell` 扩展依赖时 Scrapling 安装出错的问题(#76)。+2. 为所有浏览器 Fetcher 及其会话类添加了新参数,可以指定一个在页面创建时执行的 JS 文件(#56):++```python+from scrapling.fetchers import StealthyFetcher++StealthyFetcher.fetch('https://example.com', init_script="/absolute/path/to/js/script.js")+```++## [v0.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.3) - 2025-09-01 {#v0.3}++🎉 **重大版本:全面重构架构**++Scrapling v0.3 是项目历史上规模最大的一次更新。它重写了整个架构,大幅提升性能,并加入多项强大的新功能,包括 AI 集成和用于网页抓取的交互式 Shell。++此版本包含多项不兼容变更,请仔细阅读版本说明。++### 🚀 主要新功能 {#v0.3-major-new-features}++#### 基于会话的架构 {#v0.3-session-based-architecture}+- **新的会话类**:全面重写,加入持久会话支持+ - `FetcherSession`:发送 HTTP 请求并保留状态,同时支持同步和异步代码+ - `DynamicSession`/`AsyncDynamicSession`:执行浏览器自动化,浏览器会一直保持打开,直到操作结束+ - `StealthySession`/`AsyncStealthySession`:使用隐身浏览器,浏览器会一直保持打开,直到操作结束+- **异步管理浏览器标签页**:新的 `max_pages` 参数提供标签页池,轮流使用标签页来并发获取页面+- **并发会话**:同时运行多个相互隔离的会话++更多信息请参阅网站的 `Fetching` 部分。++#### 多项新的隐身与反机器人应对功能 {#v0.3-a-lot-of-new-stealth-anti-bot-capabilities}+- **🤖 Cloudflare 挑战处理**:在 `StealthyFetcher` 及其会话类中自动[处理 Cloudflare Turnstile 挑战](fetching/stealthy.md#cloudflare-and-stealth-options)+- **模拟浏览器指纹**:全新的 [Fetcher](fetching/static.md) 类可以模拟真实浏览器的 TLS 指纹、生成与浏览器版本匹配的请求头,并支持 HTTP/3 等功能+- **改进隐身模式**:`DynamicFetcher` 及其会话类的隐身模式现在更稳定、更可靠(也称为 `PlayWrightFetcher`)++#### AI 集成与 MCP 服务器 {#v0.3-ai-integration-mcp-server}+- **内置 MCP 服务器**:通过 Model Context Protocol 服务器实现 AI 辅助网页抓取+- **6 个强大的工具**:`get`、`bulk_get`、`fetch`、`bulk_fetch`、`stealthy_fetch`、`bulk_stealthy_fetch`+- **智能内容提取**:将网页或元素转换为 Markdown、HTML,或提取经过清理的文本内容+- **支持 CSS 选择器**:将内容交给 AI 前,先用 Scrapling 引擎精确选择所需元素+- **绕过反机器人防护**:处理 Cloudflare Turnstile 和其他防护+- **支持代理**:使用代理隐藏身份,或从指定地区发送请求+- **模拟浏览器**:使用 TLS 指纹、与浏览器版本匹配的真实请求头等来模拟真实浏览器+- **并行处理**:同时抓取多个 URL,提高效率+- [还有更多...](ai/mcp-server.md)++#### 新的网页抓取交互式 Shell {#v0.3-new-interactive-web-scraping-shell}+- **新的 Shell**:定制的 IPython Shell,内置许多实用快捷方式,例如 `get`、`post`、`put`、`delete`、`fetch` 和 `stealthy_fetch`+- **智能页面管理**:新的 `page` 和 `pages` 命令会自动保存当前页面,以及所有通过 Shell 发出的请求的历史记录+- **Curl 集成**:使用 `uncurl` 和 `curl2fetcher` 函数,将浏览器开发者工具中的 curl 命令转换为 `Fetcher` 请求+- [还有更多...](cli/interactive-shell.md)++#### 无需编程,直接在终端抓取网页 {#v0.3-scrape-from-the-terminal-without-programming}+- **新的提取命令**:无需编程,在终端中抓取网页+ - `scrapling extract get/post/put/delete`:发送简单的 HTTP 请求+ - `scrapling extract fetch`:抓取动态内容+ - `scrapling extract stealthy-fetch`:绕过反机器人防护+- **下载网页**,并将内容保存到文件。+- **将 HTML 转换为易读的格式**,例如 Markdown,也可以保留 HTML,或只提取页面的文本内容。+- **支持自定义 CSS 选择器**,用于提取页面的指定部分。+- **支持 HTTP 请求和浏览器页面获取。**+- **可灵活配置**,包括自定义请求头、Cookie、代理及其他选项。代码中可用的选项几乎都能在终端中使用。+- [还有更多...](cli/extract-commands.md)++### 🔧 技术改进 {#v0.3-technical-improvements}++#### 性能提升 {#v0.3-performance-enhancements}+- **Fetcher 的速度现在是原来的 4 倍**:没错,你没有看错!+- **DynamicFetcher 的速度提高约 60%**:具体提升取决于配置,尤其是隐身模式+- **StealthyFetcher 的速度提高 20–30%**:采用新的结构,并开始使用我们自己的实现,替代 `Camoufox` 的 Python 接口+- **核心查询方法的综合速度提升至少 50%**,包括 `find_by_text`、`find_similar`、`find_by_regex`、`relocate` 等 🚀+- **CSS/XPath 的 first 方法速度提高约 10%**:`css_first` 和 `xpath_first` 现在比 `css` 和 `xpath` 更快+- **用于内容提取的 `get_all_text()` 方法速度提高 40%**+- **自适应元素重定位的速度提高 20%**+- **优化导航属性**:`next`、`previous`、`below_elements` 等属性现在明显更快+- **文本清理速度提高到原来的 5 倍**+- **减少内存占用**:优化导入并减少额外开销+- **⚡ 快速导入**:通过优化模块加载来缩短启动时间+- **更好的基准测试结果**:这些改进让 Scrapling 相比其他库的速度优势更大,是 BeautifulSoup 的 1775 倍、AutoScraper 的 5.1 倍,详见[基准测试](benchmarks.md)++#### 架构、代码质量与使用体验 {#v0.3-architecture-code-quality-and-quality-of-life}+- **持久化上下文**:所有浏览器 Fetcher 现在默认使用持久化上下文。(也解决了 #64)+- **使用 msgspec 快速验证所有浏览器 Fetcher**,在发送请求前完成检查,让错误更容易排查。+- **Fetcher 返回的所有 Cookie** 现在都符合该 Fetcher 接受的格式。你可以获取 Cookie,再传给所有 Fetcher 及其会话类。+- **代码检查和格式化更快**:迁移到 `ruff`+- **现代化的构建系统**:从 setup.py 迁移到 pyproject.toml 📦+- **改进 GitHub Actions 和工作流**,让开发和测试更顺畅+- **🎨 改进类型提示**:按照现代 Python 标准提供完整的类型标注,改善 IDE 支持和可靠性+- **更清晰的代码**:移除不再使用的代码,并优化核心函数 🧹+- **🚀 向后兼容**:添加快捷方式,让旧代码可以继续使用++### 不兼容变更 {#v0.3-breaking-changes}++#### 最低 Python 版本 {#v0.3-minimum-python-version}+- **需要 Python 3.10+**:不再支持 Python 3.9 及更早版本++#### 类和方法的命名 {#v0.3-class-and-method-naming}+这些更名让命名更加清晰、统一,尤其方便新用户理解。++- **`Adaptor` → `Selector`**:核心解析类更名(为保持向后兼容,仍可使用 `Adaptor` 导入)+- **`Adaptors` → `Selectors`**:集合类更名(为保持向后兼容,仍可使用 `Adaptors` 导入)+- **`auto_match` → `adaptive`**:在所有方法中更改参数名+- **`adaptor_arguments` → `selector_config`**:更改配置参数名+- **`automatch_domain` → `adaptive_domain`**:更改域名参数名+- **`additional_arguments` → `additional_args`**:缩短参数名+- **⚠️ `text/body` → `content`**:Selector 构造函数的这个参数现在同时接受 `str` 和 `bytes`+- **`PlayWrightFetcher` → `DynamicFetcher`**:浏览器自动化类更名(为保持向后兼容,仍可使用 `PlayWrightFetcher` 导入)+- **DynamicFetcher 不再包含 NSTBrowser 的逻辑和参数**,因为已经没有保留这些逻辑的必要。+- **StealthyFetcher 的 headless 参数不再接受 'virtual'**,因为目前只用 Camoufox 库获取浏览器安装路径和其他启动选项++### 🐛 问题修复 {#v0.3-bug-fixes}++- 修复 `get_all_text` 在忽略的标签中统计嵌套子元素的问题(#61)+- 修复 Python 可执行文件路径含有空格时出现的安装问题(#57)+- 修复启用自适应功能时,存储系统在处理递归过程中出现的线程问题+- 在 `FetcherSession` 中使用 Sentinel 模式,修复参数优先级问题+- 修复 `StealthyFetcher` 对代理类型的处理+- 修复 `referer` 与 `google_search` 参数冲突+- 修复异步注入隐身脚本的问题++## [v0.2.99](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.99) - 2025-04-08 {#v0.2.99}++**这是一次重要更新,建议所有用户更新,以充分使用 Scrapling。**++### 更新内容 {#v0.2.99-what-s-changed}+#### 新的完整文档网站 {#v0.2.99-new-full-documentation-website}+- 是的,终于来了 😄 点击[这里](index.md)查看+#### 统一 Fetcher 的导入方式 {#v0.2.99-unified-import-logic-for-fetchers}+- 现在可以用 `from scrapling.fetchers import Fetcher, AsyncFetcher, StealthyFetcher, PlayWrightFetcher` 导入所有 Fetcher,然后直接调用,例如 `page = Fetcher.get(...)`,无需初始化。<br/>这取代了旧的导入方式 `from scrapling.defaults import Fetcher, AsyncFetcher, StealthyFetcher, PlayWrightFetcher`。+#### 不兼容变更:automatch 现在默认关闭 {#v0.2.99-breaking-change-automatch-is-now-turned-off-by-default}+- 现在可以通过新的方式在 Fetcher 中启用 automatch 或设置其他解析选项,详情请看[文档页面](fetching/choosing.md#parser-configuration-in-all-fetchers)。+> 为保持向后兼容,旧的导入方式和逻辑仍然可用,但会发出警告。+#### 为 Fetcher 添加新选项 {#v0.2.99-new-options-added-to-fetchers}+- `StealthyFetcher` 和 `PlayWrightFetcher` 在获取页面时都新增了 `wait` 参数。它让 Fetcher 在关闭页面并返回响应前,等待指定时间,单位为毫秒。+- `StealthyFetcher` 的 `fetch` 和 `async_fetch` 方法现在接受 `additional_arguments` 参数,用于向 Camoufox 传入额外设置。这些设置的优先级高于 Scrapling 的设置(#54)+#### 问题修复 {#v0.2.99-bugs-squashed}+- 修复 `async_fetch` 中捕获重定向的问题,涉及 `StealthyFetcher` 和 `PlayWrightFetcher` 两个类。++**_感谢大家的支持和捐赠!_**++## [v0.2.98](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.98) - 2025-03-17 {#v0.2.98}++**这是一次重要更新,建议所有用户更新,以充分使用 Scrapling**++### 更新内容 {#v0.2.98-what-s-changed}+#### 多项内存与速度优化 {#v0.2.98-various-memory-usage-and-speed-optimizations}+- 所有查询方法的内存占用降至原来的约 40%,速度也略有提高。+- 所有子模块现在都延迟加载,只加载实际使用的部分。例如:+更新前,`from scrapling import Adaptor` 会占用 `30-40mb` 内存,因为它同时加载了所有 Fetcher 和其他模块。现在只占用 `~1.2mb`。+- 上次更新已经让库在使用大型请求池时,仅占用原来约 32% 的内存。此次进一步调整缓存,让内存占用更低。+- 解析器的整体速度提高 2-5%++**_感谢大家的支持和捐赠!_**++## [v0.2.97](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.97) - 2025-03-15 {#v0.2.97}++**这是一次重要更新,建议所有用户更新,以充分使用 Scrapling**++### 更新内容 {#v0.2.97-what-s-changed}+#### 降低所有 Fetcher 的内存占用,并略微提高速度 {#v0.2.97-lower-memory-usage-and-small-speed-increase-across-all-fetchers}+- 在整个库中为缓存大小设置新的限制。执行大量请求或操作时,内存占用会明显低于以前。+- 重构 Fetcher 的大部分代码,使其更易维护,并略微提高速度。++#### 问题修复 {#v0.2.97-bugs-fixed}+- 修复 `TextHandler` 的一个问题:单独导入它后,传入非字符串值会得到空字符串。现在传给 `TextHandler` 的任何值都会先转换为字符串,再转换为 `TextHandler`。这适用于所有传入的值,毕竟 `TextHandler` 顾名思义就是用来处理字符串的!(#45)+- 修复大多数 AsyncFetcher 方法未使用 `retries` 参数的问题。++#### 其他 {#v0.2.97-miscellaneous}+- 更新所有 Fetcher 中大部分参数的类型提示,使其更清晰、更准确。++**_感谢大家的支持和捐赠!_**++## [v0.2.96](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.96) - 2025-03-05 {#v0.2.96}++**这是一次重要更新,建议所有用户更新,以充分使用 Scrapling**++### 更新内容 {#v0.2.96-what-s-changed}+1. 新增 `-f` 选项,可用于 `scrapling install`,强制重新安装浏览器依赖。建议现在执行 `scrapling install -f`,体验新版 Camoufox 浏览器给 `StealthyFetcher` 带来的大幅速度提升 :)+2. 修复 `TextHandler` 切片返回 `TextHandlers` 而非 `TextHandler` 的问题,并修正相应的类型提示(#41)+3. 修复 `scrapling install` 在某些情况下意外进入 Python Shell 的问题!++## [v0.2.95](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.95) - 2025-02-25 {#v0.2.95}++**这是一次重要更新,建议所有用户更新,以充分使用 Scrapling**++### 更新内容 {#v0.2.95-what-s-changed}+1. 修复 `Fetcher` 的一个问题:由 `stealthy_headers` 参数生成的请求头会覆盖用户提供的部分请求头,例如 `Accept`(#39)+2. 略微改进请求头生成逻辑,预计速度会有小幅提升。++## [v0.2.94](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.94) - 2025-02-22 {#v0.2.94}++**这是一次重要更新,建议所有用户更新,以充分使用 Scrapling**++### 更新内容 {#v0.2.94-what-s-changed}+1. 为所有 Fetcher 添加 `history` 属性,用来显示重定向记录(#32)+2. 修复 `case_sensitive` 参数在所有 `re`/`re_first` 方法中的逻辑。如果使用了这个参数,代码现在可能会返回不同的结果(不过,如果你已经发现它有问题却没有提 issue,那这可能也是自找的,哈哈)。+3. 更新依赖,并在 Camoufox 引擎(StealthyFetcher)中重新启用 `coop`。++## [v0.2.93](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.93) - 2025-01-31 {#v0.2.93}++**这是一次重要更新,建议所有用户更新,以充分使用 Scrapling**++### 更新内容 {#v0.2.93-what-s-changed}+1. 整个解析引擎现在统一了返回类型,总会返回 `Adaptor`、`Adaptors`、`TextHandler`、`TextHandlers`、`None` 之一;若结果混合了多种类型,例如使用组合 CSS 选择器,则返回列表。这样能减少手动类型检查,让编程更方便、库更稳定,并让方法始终可以链式调用。+2. 重构了解析引擎的大部分代码,尤其是 `Adaptor` 类,使代码更清晰,最重要的是更快。几乎所有方法和属性,特别是搜索方法,速度都提高了 5-40%。某些方法提升更大,例如 `find_by_regex` 提速约 60%!automatch 功能也提速约 5%。+3. 修复 `find_all`/`find` 方法的逻辑问题:传入的筛选条件有时按“或”组合,有时按“与”组合。现在返回的元素必须满足所有传入的条件。+4. 所有正则表达式相关方法现在都返回 `TextHandler`/`TextHandlers`,更方便链式调用。+5. **新增** `below_elements` 属性,返回一个 `Adaptors` 对象,包含 DOM 树中当前元素下方的所有元素。+6. 之前将 HTML 源码作为字符串返回的方法和属性,现在都返回 `TextHandler`,方便在结果上使用正则表达式等功能。+7. StealthyFetcher 现在更快,隐身效果也更好。还可以点击 iframe 内的验证码,例如 **Cloudflare Turnstile**。+8. 改善了近一半库代码的自动补全和类型提示,尤其是 `Adaptor`、`TextHandler` 和 `TextHandlers`。+9. 对 `TextHandler` 进行切片、索引访问或调用 `split`,现在都会返回另一个 `TextHandler`,而不是普通 Python 字符串。几乎所有标准字符串操作和方法现在都返回 `Texthandler`,让方法和函数始终可以链式调用。+10. 修复一些小问题和拼写错误。例如,Fetcher 的 async_put 原来发送的是 POST 请求,而不是 PUT 请求 😶🌫️+11. 在文档网站完成前,先对 README 做了一些改进。++这本来只是 0.3 之前的一个小更新,但我还是想把它做得更好。++## [v0.2.92](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.92) - 2024-12-26 {#v0.2.92}++### 更新内容 {#v0.2.92-what-s-changed}+- 当页面包含许多 iframe 时,浏览器 Fetcher 返回的响应现在会使用更可靠的数据源。+- **安装 `Scrapling` 更简单了:用 pip 安装后,在终端运行 `scrapling install`,就可以开始使用!**+- 修正解析器中一处不准确的类型提示。++## [v0.2.91](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.91) - 2024-12-19 {#v0.2.91}++### 更新内容 {#v0.2.91-what-s-changed}+- 修复页面获取日志只在第一次请求时显示的问题。+- Playwright API 在浏览页面时,默认返回第一个达到 `goto` 所指定加载状态 `["load", "domcontentloaded", "networkidle"]` 的响应。如果网站先显示一个等待页面,例如 Cloudflare 的等待页面,然后再跳转到真实网站,Playwright 会返回第一个状态码,可能是 403。此次更新修复了 `PlaywrightFetcher` 和 `StealthyFetcher` 中的这个问题。它们都使用 Playwright API,但返回结果现在不再受这个默认行为影响。+- 为 `Fetcher` 类添加 SOCKS 代理支持。+- 修正 `wait_selector_state` 参数的类型提示,自动补全现在会显示正确的可用值。++## [v0.2.9](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.9) - 2024-12-16 {#v0.2.9}++### 更新内容 {#v0.2.9-what-s-changed}+##### 新功能 {#v0.2.9-new-features}+1. Scrapling **期待已久**的异步支持来了!现在有 `AsyncFetcher` 类,作为 `Fetcher` 的异步版本,而 `StealthyFetcher` 和 `PlayWrightFetcher` 也新增了 `async_fetch` 方法,选项与同步版本相同。++```python+>> from scrapling import StealthyFetcher+>> page = await StealthyFetcher().async_fetch('https://www.browserscan.net/bot-detection') # the async version of fetch+>> page.status == 200+True+```++2. `StealthyFetcher` 类的获取方法新增 `geoip` 参数。启用后,会自动使用 IP 对应的经度、纬度、时区、国家和区域设置,并伪装 WebRTC IP 地址。它还会根据目标地区使用各种语言的人口分布,确定并伪装浏览器语言。+3. 新增 `retries` 参数,适用于 `Fetcher`/`AsyncFetcher` 类,可以设置 `httpx` 发出的每次请求的重试次数。+4. 新增 `url_join` 方法,供 `Adaptor` 和 Fetcher 使用,将相对 URL 与当前 URL 合并,生成完整的绝对 URL!+5. 新增 `keep_cdata` 方法,供 `Adaptor` 和 Fetcher 使用,需要时可以阻止解析器移除 CDATA。+6. `Adaptor`/`Response` 的 `body` 方法现在会在可能的情况下返回原始 HTML 响应,不在库中进行处理。+7. 为 `Response` 类添加日志记录。使用 Fetcher 时,现在会输出包含响应信息的日志。+示例:++ ```python+ >> from scrapling.defaults import Fetcher+ >> Fetcher.get('https://books.toscrape.com/index.html')+ [2024-12-16 13:33:36] INFO: Fetched (200) <GET https://books.toscrape.com/index.html> (referer: https://www.google.com/search?q=toscrape)+ >>+ ```++8. 在 `TextHandler` 上调用标准字符串方法,例如 `.replace()`,现在会得到另一个 `TextHandler`,而不是之前的普通字符串。+9. 大幅提高整个库的速度,并整体改善 Fetcher 类的隐身效果。+10. 添加 `extract_first`\`extract` 等简单函数,返回与父对象相同的结果。这些函数仅用于方便将 Scrapy/Parsel 代码复制到 Scrapling,因为那些库会使用这些函数!+11. 重构了大量代码,并在适当的位置使用缓存,因此批量发送请求的速度大幅提高。++##### 不兼容变更 {#v0.2.9-breaking-changes}+- 不再支持 Python 3.8。(主要是因为 Playwright 已停止支持它,不过这个版本本来也有不少问题。)+- 从整个库中移除了 `debug` 参数。如果要启用调试,请在导入库后执行以下代码:++ ```python+ >>> import logging+ >>> logging.getLogger("scrapling").setLevel(logging.DEBUG)+ ```++##### 问题修复 {#v0.2.9-bugs-squashed}+1. WebGL 现在默认启用,因为许多防护系统会检查它是否开启。+2. 修复文档和 README 中的一些错误和拼写问题。++##### 使用体验改进 {#v0.2.9-quality-of-life-changes}+1. 所有日志现在统一使用名为 `scrapling` 的日志记录器,更容易管理。之前使用的是根日志记录器。+2. 重新整理测试目录,使结构更清晰,并为新功能添加测试。所有测试都经过重写,更易阅读,同时增加更多测试来提高覆盖率。+3. 重构大部分代码,使其更清晰、更易维护。++> 这些变更原本都计划放到 0.3 中,但距离下个版本还有一段时间,所以决定提前加入。下一步是完成详细的文档网站,然后继续开发 0.3 版本。++## [v0.2.8](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.8) - 2024-11-30 {#v0.2.8}++### 更新内容 {#v0.2.8-what-s-changed}+- 这是一次小更新,包含一些让代码更易用的必要改进,并修复主 README 文件中的一个拼写错误(#20)。++## [v0.2.7](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.7) - 2024-11-26 {#v0.2.7}++### 更新内容 {#v0.2.7-what-s-changed}+##### 新功能 {#v0.2.7-new-features}+- 使用 `wait_selector` 参数时,在 `StealthyFetcher` 和 `PlayWrightFetcher` 中,Scrapling 现在会再次等待 JavaScript 完全加载并执行。如果还使用了 `network_idle`,完成上述等待后也会再次等待网络空闲。当然,如果所有状态都已满足,就不会额外等待。+- 在 `StealthyFetcher` 中,现在可以用 `disable_ads` 参数允许或屏蔽广告。此选项默认启用,会安装 `ublock origin` 扩展。+- `PlayWrightFetcher` 现在支持通过 `locale` 参数指定区域设置。默认值仍是 `en-US`。+- `Fetcher` 发出的基本请求现在接受 `http://username:password@localhost:8030` 格式的代理。+- 略微改进 `PlayWrightFetcher` 的隐身模式。++##### 问题修复与改进 {#v0.2.7-bugs-squashed-improvements}+1. 在 `PlayWrightFetcher` 类中启用代理,现在不再依赖 `stealth` 模式是否开启(感谢 [@AbdullahY36](https://github.com/AbdullahY36) 指出这个问题)。+2. `ResponseEncoding` 现在会检查响应返回的编码是否适用于页面。如果使用该编码出错,Scrapling 会改用 `utf-8`。++## [v0.2.6](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.6) - 2024-11-24 {#v0.2.6}++### 更新内容 {#v0.2.6-what-s-changed}+##### 新功能 {#v0.2.6-new-features}+- `PlayWrightFetcher` 现在可以直接使用真实浏览器,只需将 `real_chrome` 参数传给 `PlayWrightFetcher.fetch`。这需要已安装 Chrome。Scrapling 会启动你的 Chrome 浏览器实例,大多数选项都可以照常使用。(之前只能通过 `cdp_url` 参数实现。)+- 更新为真实浏览器生成的请求头中的版本号。++##### 问题修复 {#v0.2.6-bugs-squashed}+1. 发现 `BrowserForge` 生成的浏览器请求头格式已经过时,导致 Scrapling 被某些防护系统识别。因此现在只用 `BrowserForge` 生成真实的 User-Agent。+2. `hide_canvas` 参数现在默认关闭,因为 Google 的 ReCaptcha 会检测到它。++## [v0.2.5](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.5) - 2024-11-23 {#v0.2.5}++### 更新内容 {#v0.2.5-what-s-changed}++##### 问题修复 {#v0.2.5-bugs-squashed}+- 修复 'wait_selector' 参数匹配到超过 1 个元素时的错误。这会影响 `StealthyFetcher` 和 `PlayWrightFetcher` 类。+- 修复 `content_type` 头字段的值包含 `charset` 等参数时的编码类型问题(感谢 @andyfcx 提交 [#12](https://github.com/D4Vinci/Scrapling/issues/12))。++##### 使用体验改进 {#v0.2.5-quality-of-life}+- 添加更多测试来覆盖新的代码部分,并让测试在线程中运行。+- 调整文档字符串,使 Sphinx apidoc 等工具可以正确显示。++##### 新贡献者 {#v0.2.5-new-contributors}+- @andyfcx 在 [#13 ](https://github.com/D4Vinci/Scrapling/pull/13) 中做出了首次贡献++## [v0.2.4](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.4) - 2024-11-20 {#v0.2.4}++### 更新内容 {#v0.2.4-what-s-changed}++##### 问题修复 {#v0.2.4-bugs-squashed}+- 修复使用 `network_idle` 参数后获取响应字节时的问题,涉及 `StealthyFetcher` 和 `PlayWrightFetcher` 两个类。<br/>它会导致以下错误:++ ```+ Response.body: Protocol error (Network.getResponseBody): No resource with given identifier found+ ```++- PlayWright API 有时会返回空的响应状态文本。现在出现这种情况时,`Scrapling` 会自行计算状态文本。这会影响 `StealthyFetcher` 和 `PlayWrightFetcher` 类。++## [v0.2.3](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.3) - 2024-11-19 {#v0.2.3}++### 更新内容 {#v0.2.3-what-s-changed}++##### 问题修复 {#v0.2.3-bugs-squashed}+- 修复 pip 安装时的一个问题,该问题会导致 PlayWright Fetcher 的隐身模式完全无法使用。++## [v0.2.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.2) - 2024-11-16 {#v0.2.2}++### 更新内容 {#v0.2.2-what-s-changed}+##### 新功能 {#v0.2.2-new-features}+- 如果不需要向生成的 `Adaptor` 对象传入参数,而是使用默认值,现在可以改用以下导入方式,让代码更简洁++ ```python+ >> from scrapling.default import Fetcher, StealthyFetcher, PlayWrightFetcher+ >> page = Fetcher.get('https://example.com', stealthy_headers=True)+ ```++ 否则++ ```python+ >> from scrapling import Fetcher, StealthyFetcher, PlayWrightFetcher+ >> page = Fetcher(auto_match=False).get('https://example.com', stealthy_headers=True)+ ```++##### 问题修复 {#v0.2.2-bugs-squashed}+1. 修复昨天的 v0.2.1 补丁引入的 `Response` 对象问题。它会在某些嵌套查询或解析情况下发生。++## [v0.2.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2.1) - 2024-11-15 {#v0.2.1}++### 更新内容 {#v0.2.1-what-s-changed}+##### 新功能 {#v0.2.1-new-features}+1. 所有 Fetcher 返回的 `Response` 对象现在与 `Adaptor` 对象相同,但额外包含 `status`、`reason`、`cookies`、`headers` 和 `request_headers` 属性。其中 `cookies`、`headers` 和 `request_headers` 始终是 `dictionary` 类型。<br/>因此,代码现在可以写成:++ ```python+ >> from scrapling import Fetcher+ >> page = Fetcher().get('https://example.com', stealthy_headers=True)+ >> print(page.status)+ 200+ >> products = page.css('.product')+ ```++ 而不是以前这样++ ```python+ >> from scrapling import Fetcher+ >> fetcher = Fetcher().get('https://example.com', stealthy_headers=True)+ >> print(fetcher.status)+ 200+ >> page = fetcher.adaptor+ >> products = page.css('.product')+ ```++ 为了向后兼容,`.adaptor` 属性仍然可用。++2. `StealthyFetcher` 和 `PlayWrightFetcher` 类现在都可以在获取方法中接受 `proxy` 参数,值可以是字符串或字典。+3. `StealthyFetcher` 类新增 `os_randomize` 参数,用于 `fetch` 方法。启用后,Scrapling 会随机选择所用的操作系统指纹。默认情况下,指纹与当前操作系统匹配。++##### 问题修复 {#v0.2.1-bugs-squashed}+1. 修复使用 `Fetcher` 类传入请求头时的问题。+2. 修复解析 Fetcher 类传来的 JSON 响应时的问题。++##### 使用体验改进 {#v0.2.1-quality-of-life-changes}+1. 文本功能之前会尝试先删除 HTML 注释,再返回文本,但这在某些情况下会导致错误,也让代码变得不必要地复杂。现在已恢复 lxml 的默认行为,**所有依赖元素文本的操作,例如选择器,速度都会略有提高**。如果希望 Scrapling 在返回文本前删除元素中的 HTML 注释,以避免 lxml/parsel/scrapy 中不直观的文本拆分行为,只需让 `keep_comments` 参数保持默认的 True。++## [v0.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.2) - 2024-11-11 {#v0.2}++### 更新内容 {#v0.2-what-s-changed}+##### 新功能 {#v0.2-new-features}+1. 推出 `Fetchers` 功能,提供 3 种主要类型,让 Scrapling 为你获取页面,并提供丰富的选项!+ - `Fetcher` 类用于基本 HTTP 请求+ - `StealthyFetcher` 类是一个完全隐身的 Fetcher,使用[经过隐身改造的 Firefox](https://github.com/daijro/camoufox)。+ - `PlayWrightFetcher` 类支持多种基于浏览器的请求方式:原版 PlayWright、使用我编写的隐身模式的 PlayWright、通过 CDP 连接的真实浏览器,以及 [NSTBrowser](https://app.nstbrowser.io/r/1vO5e5) 的 [docker browserless](https://hub.docker.com/r/nstbrowser/browserless)!+2. 添加全新的 `find_all`/`find` 方法,像施魔法一样轻松查找页面元素!+3. 新增 `filter` 和 `search` 方法,加入 `Adaptors` 类,更方便批量处理 `Adaptor` 对象组。+4. 添加 `css_first` 和 `xpath_first` 方法,让使用更简单。+5. 添加新的 `TextHandlers` 类,用于批量处理 `TextHandler` 对象,功能类似 `Adaptors` 类。+6. 添加 `generate_full_css_selector` 和 `generate_full_xpath_selector` 方法。++##### 问题修复 {#v0.2-bugs-squashed}+1. `Adaptors` 类中的 `re_first` 现在会返回所有内部 `Adaptor` 对象中第一个匹配的结果。之前的错误逻辑会返回 `re_first` 在所有 `Adaptor` 对象上的结果。+2. 如果要从选中的元素中返回文本内容,例如 CSS 的 `::text` 函数,无论使用 `.css` 还是 `.xpath` 等方法,`Adaptor` 对象现在都会返回 `TextHandlers`,而不是以前的字符串列表。因此可以写成 `page.css('something::text').re_first(r'regex_pattern').json()`,而不必使用 `page.css('something::text')[0].re_first(r'regex_pattern').json()`。+3. `Adaptor`/`Adaptors` 的 re/re_first 参数现在与 `TextHandler` 一致,提供 `clean_match` 和 `case_sensitive` 参数。+4. `auto_match` 参数现在在初始化 `Adaptor` 时默认开启,但如果要使用此功能,仍需在查询元素时启用它。(这不是错误,而是设计决定。)+5. 修正多处类型标注,让使用 Scrapling 编程时的自动补全更好用。++##### 使用体验改进 {#v0.2-quality-of-life-changes}+1. 将 `css_selector` 和 `xpath_selector` 方法更名为 `generate_css_selector` 和 `generate_xpath_selector`,让命名更清晰,也避免干扰编程时的自动补全。+2. 将大部分旧代码重新整理到 `core` 子包中,并调整其他设计,让代码更清晰,今后更易维护。+3. 重新整理测试目录,使结构更清晰,并为新功能添加测试。tox 环境现在还会在 GitHub 上缓存,以加快每次提交时的自动测试。++## [v0.1.2](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.2) - 2024-10-16 {#v0.1.2}++**更新日志**:++- 修复 `keep_comments` 参数未按预期工作的问题。+- 调整文本函数,在提取文本前自动移除元素中的 HTML 注释,避免 Lxml 的不同处理方式造成影响,例如:++ ```python+ >>> page = Adaptor('<span>CONDITION: <!-- -->Excellent</span>', keep_comments=True)+ >>> page.css('span::text')+ ['CONDITION: ', 'Excellent']+ ```++ 上面的结果是之前由 Lxml 的默认行为产生的,现在会返回完整文本 'CONDITION: Excellent'。+ parsel\scrapy 也有这种行为,所以我想在这里处理它。++- 修复执行 `pip uninstall scrapling` 等命令时,库创建的 SQLite 数据库文件未被删除的问题。++## [v0.1.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1.1) - 2024-10-14 {#v0.1.1}++小幅修复++## [v0.1](https://github.com/D4Vinci/Scrapling/releases/tag/v0.1) - 2024-10-13 {#v0.1}++**完整更新日志**:<https://github.com/D4Vinci/Scrapling/commits/v0.1>diff --git a/docs/stylesheets/extra.css b/docs/stylesheets/extra.cssindex b22888e..acfa537 100644--- a/docs/stylesheets/extra.css+++ b/docs/stylesheets/extra.css@@ -13,6 +13,11 @@:root {--md-code-font: 'Maple Mono';}++[dir="rtl"] .md-typeset code {+ unicode-bidi: isolate;+}+[align="center"] code {font-family: 'Maple Mono';font-style: italic;diff --git a/pyproject.toml b/pyproject.tomlindex 9250947..a99d366 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -101,7 +101,7 @@ all = [[project.urls]Homepage = "https://github.com/D4Vinci/Scrapling"-Changelog = "https://github.com/D4Vinci/Scrapling/blob/main/CHANGELOG.md"+Changelog = "https://scrapling.readthedocs.io/en/latest/changelog.html"Documentation = "https://scrapling.readthedocs.io/en/latest/"Repository = "https://github.com/D4Vinci/Scrapling""Bug Tracker" = "https://github.com/D4Vinci/Scrapling/issues"diff --git a/zensical.ar.yml b/zensical.ar.ymlindex a118893..e3d9796 100644--- a/zensical.ar.yml+++ b/zensical.ar.yml@@ -52,7 +52,7 @@ nav:- استخدام الأنواع المخصصة في Scrapling: development/scrapling_custom_types.md- الدعم والإعلانات: donate.md- المساهمة: https://github.com/D4Vinci/Scrapling/blob/main/CONTRIBUTING.md-- سجل التغييرات: https://github.com/D4Vinci/Scrapling/blob/main/CHANGELOG.md+- سجل التغييرات: changelog.mdtheme:language: arpalette:diff --git a/zensical.de.yml b/zensical.de.ymlindex 69cd465..2ff653a 100644--- a/zensical.de.yml+++ b/zensical.de.yml@@ -53,7 +53,7 @@ nav:- Die Datentypen von Scrapling nutzen: development/scrapling_custom_types.md- Unterstützung und Werbung: donate.md- Mitwirken: https://github.com/D4Vinci/Scrapling/blob/main/CONTRIBUTING.md-- Änderungsverlauf: https://github.com/D4Vinci/Scrapling/blob/main/CHANGELOG.md+- Änderungsverlauf: changelog.mdtheme:language: depalette:diff --git a/zensical.es.yml b/zensical.es.ymlindex 07331b9..547e24d 100644--- a/zensical.es.yml+++ b/zensical.es.yml@@ -53,7 +53,7 @@ nav:- Usar los tipos personalizados de Scrapling: development/scrapling_custom_types.md- Apoyo y publicidad: donate.md- Contribuir: https://github.com/D4Vinci/Scrapling/blob/main/CONTRIBUTING.md-- Historial de cambios: https://github.com/D4Vinci/Scrapling/blob/main/CHANGELOG.md+- Historial de cambios: changelog.mdtheme:language: espalette:diff --git a/zensical.fr.yml b/zensical.fr.ymlindex d642149..175f5e3 100644--- a/zensical.fr.yml+++ b/zensical.fr.yml@@ -53,7 +53,7 @@ nav:- Utiliser les types personnalisés de Scrapling: development/scrapling_custom_types.md- Soutien et publicité: donate.md- Contribuer: https://github.com/D4Vinci/Scrapling/blob/main/CONTRIBUTING.md-- Historique des changements: https://github.com/D4Vinci/Scrapling/blob/main/CHANGELOG.md+- Historique des changements: changelog.mdtheme:language: frpalette:diff --git a/zensical.ja.yml b/zensical.ja.ymlindex c0a3abc..3b60952 100644--- a/zensical.ja.yml+++ b/zensical.ja.yml@@ -53,7 +53,7 @@ nav:- Scrapling の型を使う: development/scrapling_custom_types.md- 支援と広告: donate.md- 開発への参加: https://github.com/D4Vinci/Scrapling/blob/main/CONTRIBUTING.md-- 変更履歴: https://github.com/D4Vinci/Scrapling/blob/main/CHANGELOG.md+- 変更履歴: changelog.mdtheme:language: japalette:diff --git a/zensical.ko.yml b/zensical.ko.ymlindex 2d1b5c5..5160619 100644--- a/zensical.ko.yml+++ b/zensical.ko.yml@@ -53,7 +53,7 @@ nav:- Scrapling 자료형 사용하기: development/scrapling_custom_types.md- 후원과 광고: donate.md- 개발에 참여하기: https://github.com/D4Vinci/Scrapling/blob/main/CONTRIBUTING.md-- 변경 기록: https://github.com/D4Vinci/Scrapling/blob/main/CHANGELOG.md+- 변경 기록: changelog.mdtheme:language: kopalette:diff --git a/zensical.pt-BR.yml b/zensical.pt-BR.ymlindex 0d308b0..debb1ec 100644--- a/zensical.pt-BR.yml+++ b/zensical.pt-BR.yml@@ -53,7 +53,7 @@ nav:- Usar os tipos personalizados do Scrapling: development/scrapling_custom_types.md- Apoio e publicidade: donate.md- Contribuir: https://github.com/D4Vinci/Scrapling/blob/main/CONTRIBUTING.md-- Histórico de mudanças: https://github.com/D4Vinci/Scrapling/blob/main/CHANGELOG.md+- Histórico de mudanças: changelog.mdtheme:language: pt-BRpalette:diff --git a/zensical.ru.yml b/zensical.ru.ymlindex 5a503ec..3eba4aa 100644--- a/zensical.ru.yml+++ b/zensical.ru.yml@@ -53,7 +53,7 @@ nav:- Типы Scrapling: development/scrapling_custom_types.md- Поддержка и реклама: donate.md- Участие в разработке: https://github.com/D4Vinci/Scrapling/blob/main/CONTRIBUTING.md-- История изменений: https://github.com/D4Vinci/Scrapling/blob/main/CHANGELOG.md+- История изменений: changelog.mdtheme:language: rupalette:diff --git a/zensical.yml b/zensical.ymlindex 8170361..e8db0e9 100644--- a/zensical.yml+++ b/zensical.yml@@ -51,7 +51,7 @@ nav:- Using Scrapling's custom types: development/scrapling_custom_types.md- Support and Advertisement: donate.md- Contributing: https://github.com/D4Vinci/Scrapling/blob/main/CONTRIBUTING.md-- Changelog: https://github.com/D4Vinci/Scrapling/blob/main/CHANGELOG.md+- Changelog: changelog.mdtheme:language: enpalette:diff --git a/zensical.zh.yml b/zensical.zh.ymlindex a2f5515..d799bbc 100644--- a/zensical.zh.yml+++ b/zensical.zh.yml@@ -53,7 +53,7 @@ nav:- 使用 Scrapling 的类型: development/scrapling_custom_types.md- 赞助和广告: donate.md- 贡献: https://github.com/D4Vinci/Scrapling/blob/main/CONTRIBUTING.md-- 更新日志: https://github.com/D4Vinci/Scrapling/blob/main/CHANGELOG.md+- 更新日志: changelog.mdtheme:language: zhpalette: