Skip to content

🕷️ 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

docs: Add Simplified Chinese docs for the website

Karim shoaira4dcdf346907
diff --git a/docs/README_CN.md b/docs/README_CN.md
index 4a22467..d6a509d 100644
--- a/docs/README_CN.md
+++ b/docs/README_CN.md
@@ -1,66 +1,66 @@
<!-- mcp-name: io.github.D4Vinci/Scrapling -->
<h1 align="center">
- <a href="https://scrapling.readthedocs.io">
+ <a href="https://scrapling.readthedocs.io/en/latest/zh/">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/docs/assets/cover_dark.svg?sanitize=true">
- <img alt="Scrapling Poster" src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/docs/assets/cover_light.svg?sanitize=true">
+ <img alt="Scrapling 封面" src="https://raw.githubusercontent.com/D4Vinci/Scrapling/main/docs/assets/cover_light.svg?sanitize=true">
</picture>
</a>
<br>
- <small>Effortless Web Scraping for the Modern Web</small>
+ <small>轻松抓取现代网站</small>
</h1>
<p align="center">
- <a href="https://github.com/D4Vinci/Scrapling/actions/workflows/tests.yml" alt="Tests">
- <img alt="Tests" src="https://github.com/D4Vinci/Scrapling/actions/workflows/tests.yml/badge.svg"></a>
- <a href="https://badge.fury.io/py/Scrapling" alt="PyPI version">
- <img alt="PyPI version" src="https://badge.fury.io/py/Scrapling.svg"></a>
+ <a href="https://github.com/D4Vinci/Scrapling/actions/workflows/tests.yml" alt="测试">
+ <img alt="测试" src="https://github.com/D4Vinci/Scrapling/actions/workflows/tests.yml/badge.svg"></a>
+ <a href="https://badge.fury.io/py/Scrapling" alt="PyPI 版本">
+ <img alt="PyPI 版本" src="https://badge.fury.io/py/Scrapling.svg"></a>
<a href="https://hub.docker.com/r/pyd4vinci/scrapling" target="_blank">
- <img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/pyd4vinci/scrapling?labelColor=%20%23FDB062&logo=Docker&labelColor=%20%23528bff"></a>
- <a href="https://clickpy.clickhouse.com/dashboard/scrapling" rel="nofollow"><img src="https://img.shields.io/pypi/dm/scrapling" alt="PyPI package downloads"></a>
- <a href="https://scrapling.readthedocs.io/en/latest/ai/agent-skill.html" alt="AI Agent Skill">
- <img alt="Static Badge" src="https://img.shields.io/badge/Skill-black?style=flat&label=Agent&link=https%3A%2F%2Fscrapling.readthedocs.io%2Fen%2Flatest%2Fai%2Fagent-skill.html"></a>
- <a href="https://clawhub.ai/D4Vinci/scrapling-official" alt="OpenClaw Skill">
- <img alt="OpenClaw Skill" src="https://img.shields.io/badge/Clawhub-darkred?style=flat&label=OpenClaw&link=https%3A%2F%2Fclawhub.ai%2FD4Vinci%2Fscrapling-official"></a>
+ <img alt="Docker 下载次数" src="https://img.shields.io/docker/pulls/pyd4vinci/scrapling?labelColor=%20%23FDB062&logo=Docker&labelColor=%20%23528bff"></a>
+ <a href="https://clickpy.clickhouse.com/dashboard/scrapling" rel="nofollow"><img src="https://img.shields.io/pypi/dm/scrapling" alt="PyPI 包下载次数"></a>
+ <a href="https://scrapling.readthedocs.io/en/latest/zh/ai/agent-skill.html" alt="AI 智能体技能">
+ <img alt="Agent Skill 徽章" src="https://img.shields.io/badge/Skill-black?style=flat&label=Agent&link=https%3A%2F%2Fscrapling.readthedocs.io%2Fen%2Flatest%2Fzh%2Fai%2Fagent-skill.html"></a>
+ <a href="https://clawhub.ai/D4Vinci/scrapling-official" alt="OpenClaw 技能">
+ <img alt="OpenClaw 技能" src="https://img.shields.io/badge/Clawhub-darkred?style=flat&label=OpenClaw&link=https%3A%2F%2Fclawhub.ai%2FD4Vinci%2Fscrapling-official"></a>
<br/>
<a href="https://discord.gg/EMgGbDceNQ" alt="Discord" target="_blank">
<img alt="Discord" src="https://img.shields.io/discord/1360786381042880532?style=social&logo=discord&link=https%3A%2F%2Fdiscord.gg%2FEMgGbDceNQ">
</a>
- <a href="https://x.com/Scrapling_dev" alt="X (formerly Twitter)">
- <img alt="X (formerly Twitter) Follow" src="https://img.shields.io/twitter/follow/Scrapling_dev?style=social&logo=x&link=https%3A%2F%2Fx.com%2FScrapling_dev">
+ <a href="https://x.com/Scrapling_dev" alt="X(原 Twitter)">
+ <img alt="在 X(原 Twitter)上关注" src="https://img.shields.io/twitter/follow/Scrapling_dev?style=social&logo=x&link=https%3A%2F%2Fx.com%2FScrapling_dev">
</a>
<br/>
- <a href="https://pypi.org/project/scrapling/" alt="Supported Python versions">
- <img alt="Supported Python versions" src="https://img.shields.io/pypi/pyversions/scrapling.svg"></a>
+ <a href="https://pypi.org/project/scrapling/" alt="支持的 Python 版本">
+ <img alt="支持的 Python 版本" src="https://img.shields.io/pypi/pyversions/scrapling.svg"></a>
</p>
<p align="center">
- <a href="https://scrapling.readthedocs.io/en/latest/parsing/selection.html"><strong>选择方法</strong></a>
+ <a href="https://scrapling.readthedocs.io/en/latest/zh/parsing/selection.html"><strong>选择方法</strong></a>
&middot;
- <a href="https://scrapling.readthedocs.io/en/latest/fetching/choosing.html"><strong>选择 Fetcher</strong></a>
+ <a href="https://scrapling.readthedocs.io/en/latest/zh/fetching/choosing.html"><strong>选择 Fetcher</strong></a>
&middot;
- <a href="https://scrapling.readthedocs.io/en/latest/spiders/architecture.html"><strong>爬虫</strong></a>
+ <a href="https://scrapling.readthedocs.io/en/latest/zh/spiders/architecture.html"><strong>爬虫</strong></a>
&middot;
- <a href="https://scrapling.readthedocs.io/en/latest/spiders/proxy-blocking.html"><strong>代理轮换</strong></a>
+ <a href="https://scrapling.readthedocs.io/en/latest/zh/spiders/proxy-blocking.html"><strong>代理轮换</strong></a>
&middot;
- <a href="https://scrapling.readthedocs.io/en/latest/cli/overview.html"><strong>CLI</strong></a>
+ <a href="https://scrapling.readthedocs.io/en/latest/zh/cli/overview.html"><strong>CLI</strong></a>
&middot;
- <a href="https://scrapling.readthedocs.io/en/latest/ai/mcp-server.html"><strong>MCP 模式</strong></a>
+ <a href="https://scrapling.readthedocs.io/en/latest/zh/ai/mcp-server.html"><strong>MCP 模式</strong></a>
</p>
-Scrapling 是一个 Python 网页抓取框架,将快速 HTTP 请求、隐身浏览器、强大的解析功能和并发爬取整合到一个库中。
+Scrapling 是一个 Python 网页抓取框架。它将快速 HTTP 请求、隐身浏览器、页面解析和并发爬取整合在一个库中。
-抓取静态页面、渲染 JavaScript、与网站交互,并从页面背后的 API 调用中提取数据。构建爬虫时,可复用会话、轮换代理、自动重试、暂停/恢复,并使用内置的数据导出功能。
+抓取静态页面、运行 JavaScript、操作网站,并从网站的 API 中提取数据。构建爬虫时,可以复用会话、轮换代理、自动重试、暂停和恢复任务,还能直接导出数据。
-通过 Python、终端,或借助 MCP 服务器和 Agent Skill 在 AI 智能体中使用它。从提取几个字段到将整个网站采集为干净的 Markdown,Scrapling 覆盖完整的抓取流程。
+可以在 Python 和终端中使用 Scrapling,也可以通过 MCP 服务器和 Agent Skill 让 AI 智能体使用它。从提取几个字段到将整个网站保存为整洁的 Markdown 文件,Scrapling 都能完成。
## 用 Scrapling 能做什么
-- **[获取与交互](https://scrapling.readthedocs.io/en/latest/fetching/choosing.html)**:快速 HTTP 请求、隐身浏览器、JavaScript 渲染、Cloudflare Turnstile/Interstitial 处理、持久会话,以及后台 API 通信捕获。
-- **[解析与提取](https://scrapling.readthedocs.io/en/latest/parsing/selection.html)**:CSS、XPath、文本和正则表达式搜索、自适应元素跟踪、相似元素匹配,以及干净的 Markdown 输出。
-- **[爬取与导出](https://scrapling.readthedocs.io/en/latest/spiders/getting-started.html)**:并发爬虫、代理轮换、重试、AutoThrottle、暂停/恢复、流式输出、现成的爬虫模板,以及 JSON/JSONL/CSV/XML 导出。
-- **[使用 AI 或终端抓取](https://scrapling.readthedocs.io/en/latest/ai/mcp-server.html)**:供 AI 智能体浏览网页和提取数据的 MCP 服务器、Agent Skill、CLI 命令和交互式 Shell。
+- **[获取和操作页面](https://scrapling.readthedocs.io/en/latest/zh/fetching/choosing.html)**:快速 HTTP 请求、隐身浏览器、JavaScript 渲染、处理 Cloudflare Turnstile 和 Interstitial、持久会话,以及记录后台 API 响应。
+- **[解析页面和提取数据](https://scrapling.readthedocs.io/en/latest/zh/parsing/selection.html)**:使用 CSS、XPath、文本和正则表达式搜索,跟踪页面变化后的元素,查找相似元素,并输出整洁的 Markdown。
+- **[爬取和导出](https://scrapling.readthedocs.io/en/latest/zh/spiders/getting-started.html)**:并发爬虫、代理轮换、重试、AutoThrottle、暂停和恢复、流式输出、现成的模板,以及 JSON、JSONL、CSV 和 XML 导出。
+- **[使用 AI 或终端抓取](https://scrapling.readthedocs.io/en/latest/zh/ai/mcp-server.html)**:供 AI 智能体浏览网页和提取数据的 MCP 服务器、Agent Skill、CLI 命令和交互式 Shell。
从单个页面开始:
@@ -72,7 +72,7 @@ quotes = page.css('.quote .text::text').getall()
print(quotes)
```
-也可以用 Spider 扩大抓取规模:
+也可以用 Spider 抓取更多页面:
```python
from scrapling.spiders import Spider, Response
@@ -110,7 +110,7 @@ result.items.to_json("quotes.json")
</a>
</td>
<td>
- <a href="https://go.nodemaven.com/scraplingseptember" target="_blank">NodeMaven</a> - 最高效的网页抓取与自动化代理提供商,拥有市场上质量最高的 IP。使用优惠码 SCRAPLING35 可享 35% 折扣。
+ <a href="https://go.nodemaven.com/scraplingseptember" target="_blank">NodeMaven</a> - 最高效的网页抓取与自动化代理提供商,拥有市场上质量最高的 IP。使用优惠码 SCRAPLING35 可享 35% 折扣。
</td>
</tr>
<tr>
@@ -132,7 +132,7 @@ result.items.to_json("quotes.json")
<td>
<a href="https://evomi.com?utm_source=github&utm_medium=banner&utm_campaign=d4vinci-scrapling">
<b>Evomi</b>
- </a>:住宅代理低至 0.49 美元/GB。具备完全伪装 Chromium 的爬虫浏览器、住宅 IP、自动验证码解决和反机器人绕过。</br>
+ </a>:住宅代理低至 0.49 美元/GB。提供指纹全面伪装的 Chromium 抓取浏览器,配备住宅 IP,并支持自动处理验证码和绕过反机器人防护。</br>
<b>Scraper API 轻松获取结果。支持 MCP 和 N8N 集成。</b>
</td>
</tr>
@@ -163,7 +163,7 @@ result.items.to_json("quotes.json")
</a>
</td>
<td>
- <a href="https://www.swiftproxy.net/?ref=D4Vinci" target="_blank">Swiftproxy</a> 提供可扩展的住宅代理,覆盖 195+ 国家/地区的 8000 万+ IP,提供快速可靠的连接、自动轮换和强大的反屏蔽性能。提供免费试用。
+ <a href="https://www.swiftproxy.net/?ref=D4Vinci" target="_blank">Swiftproxy</a> 提供可扩展的住宅代理,覆盖 195+ 国家/地区的 8000 万+ IP,提供快速可靠的连接、自动轮换和强大的防封禁功能。提供免费试用。
</td>
</tr>
<tr>
@@ -183,7 +183,7 @@ result.items.to_json("quotes.json")
</a>
</td>
<td>
- <a href="https://proxylane.dev/?utm_source=scrapling&utm_medium=partnership&utm_campaign=scrapling_platinum_202609&utm_content=github_readme" target="_blank">ProxyLane</a>:将封禁和 CAPTCHA 验证码减少 90%。提供 2800 万个优质住宅 IP,适用于大规模网页抓取。覆盖 195 个国家。支持城市、ISP、邮政编码(ZIP)定向。支持固定和轮换会话。流量永不过期,低至 $2/GB。使用优惠码 <strong>SCRAPEANDTAKE</strong> 可享 <em>25% 折扣</em>。
+ <a href="https://proxylane.dev/?utm_source=scrapling&utm_medium=partnership&utm_campaign=scrapling_platinum_202609&utm_content=github_readme" target="_blank">ProxyLane</a>:将封禁和 CAPTCHA 验证码减少 90%。提供 2800 万个优质住宅 IP,适用于大规模网页抓取。覆盖 195 个国家。支持城市、ISP、邮政编码(ZIP)定向。支持使用固定 IP 或轮换 IP 的会话。流量永不过期,低至 $2/GB。使用优惠码 <strong>SCRAPEANDTAKE</strong> 可享 <em>25% 折扣</em>。
</td>
</tr>
<tr>
@@ -208,7 +208,7 @@ result.items.to_json("quotes.json")
</tr>
</table>
-<i><sub>想在这里展示您的广告吗?点击 [这里](https://github.com/sponsors/D4Vinci/sponsorships?tier_id=586646)</sub></i>
+<i><sub>想在这里投放广告?点击[这里](https://github.com/sponsors/D4Vinci/sponsorships?tier_id=586646)</sub></i>
# 赞助商
<!-- sponsors -->
@@ -226,71 +226,77 @@ result.items.to_json("quotes.json")
<!-- /sponsors -->
-<i><sub>想在这里展示您的广告吗?点击 [这里](https://github.com/sponsors/D4Vinci) 并选择适合您的级别!</sub></i>
+<i><sub>想在这里投放广告?点击[这里](https://github.com/sponsors/D4Vinci),选择合适的方案!</sub></i>
---
-## 主要特性
-
-### Spider - 完整的爬取框架
-- 🕷️ **类 Scrapy 的 Spider API**:使用 `start_urls`、async `parse` callback 和`Request`/`Response` 对象定义 Spider。
-- ⚡ **并发爬取**:可配置的并发限制、按域名节流和下载延迟。
-- 🔄 **多 Session 支持**:统一接口,支持 HTTP 请求和隐秘无头浏览器在同一个 Spider 中使用--通过 ID 将请求路由到不同的 Session。
-- 💾 **暂停与恢复**:通过 `crawldir` 保存待处理请求和已访问 URL。按 Ctrl+C 正常停止,再使用同一目录重启。
-- 📡 **Streaming 模式**:通过 `async for item in spider.stream()` 以实时统计 Streaming 抓取的数据--非常适合 UI、管道和长时间运行的爬取。
-- 🛡️ **被阻止请求检测**:自动检测并重试被阻止的请求,支持自定义逻辑。
-- 🚦 **AutoThrottle 自动限速**:不用再猜延迟。Spider 会根据网站的响应速度自动调整每个域名的延迟,当网站开始封禁或限流时把延迟翻倍(或按 `Retry-After` 要求等待),并在恢复正常后重新提速。
-- 🤖 **robots.txt 合规**:可选的 `robots_txt_obey` 标志,支持 `Disallow`、`Crawl-delay` 和 `Request-rate` 指令,并按域名缓存。
-- 🧪 **开发模式**:首次运行时将响应缓存到磁盘,后续运行时直接回放 - 在不重新请求目标服务器的情况下迭代你的 `parse()` 逻辑。
-- 🧩 **现成的 Spider 模板**:跳过样板代码--使用 `CrawlSpider` 基于规则跟踪链接,`SitemapSpider` 基于 sitemap/robots.txt 爬取,`XMLFeedSpider`/`CSVFeedSpider` 用于遍历 XML/RSS 和 CSV 数据源,以及 `ShopifySpider` 用于收集公开 Shopify 店铺中的商品,每个变体一条记录。
-- 🔗 **链接提取**:独立的 `LinkExtractor` 组件,支持 allow/deny 模式、域名过滤、CSS/XPath 范围限定、扩展名过滤和链接规范化--可在模板中使用,也可单独使用。
-- 📦 **内置导出**:通过钩子和您自己的管道导出结果,或使用内置的 JSON/JSONL/CSV/XML 导出器:`result.items.to_json()`、`to_jsonl()`、`to_csv()` 和 `to_xml()`。
-
-### 支持 Session 的高级网站获取
-- **HTTP 请求**:使用 `Fetcher` 类进行快速和隐秘的 HTTP 请求。可以模拟浏览器的 TLS fingerprint、标头并使用 HTTP/3。
-- **动态加载**:通过 `StealthyFetcher` 类使用完整的浏览器自动化获取动态网站,支持 Playwright 的 Chromium 和 Google Chrome。
-- **反机器人绕过**:`StealthyFetcher` 提供高级隐身能力和指纹伪装,可通过自动化轻松绕过所有类型的 Cloudflare Turnstile/Interstitial。
-- **Session 管理**:使用 `FetcherSession` 和 `StealthySession` 类实现持久化 Session 支持,用于跨请求的 cookie 和状态管理。
-- **Proxy 轮换**:内置 `ProxyRotator`,支持轮询或自定义策略,适用于所有 Session 类型,并支持按请求覆盖 Proxy。
-- **域名和广告屏蔽**:在基于浏览器的 Fetcher 中屏蔽对特定域名(及其子域名)的请求,或启用内置广告屏蔽(约 3,500 个已知广告/追踪域名)。
-- **DNS 泄漏防护**:可选的 DNS-over-HTTPS 支持,通过 Cloudflare 的 DoH 路由 DNS 查询,防止使用代理时的 DNS 泄漏。
-- **远程浏览器**:无需在本地启动浏览器,通过 `cdp_url` 用 CDP 连接到已在运行的浏览器,无论它在同一台机器、另一台主机,还是托管的浏览器服务商。您也可以通过 `executable_path` 让任意浏览器 Fetcher 使用您自己的 Chromium 构建版本。
-- **后台 API 捕获**:在浏览器会话中启用 `record_requests=True`,然后使用 `session.network.search(limit=None)` 搜索已保存的响应。无需再次发送请求,即可读取各个页面加载过程中产生的 API 数据和 HTTP 错误。历史记录有容量限制,并保存文本响应体。
-- **Async 支持**:所有 Fetcher 和专用 async Session 类的完整 async 支持。
-
-### 解析与数据提取
-- 🔄 **智能元素跟踪**:使用智能相似性算法在网站更改后重新定位元素。
-- 🎯 **智能灵活选择**:CSS 选择器、XPath 选择器、基于过滤器的搜索、文本搜索、正则表达式搜索等。
-- 🔍 **查找相似元素**:自动定位与已找到元素相似的元素。
+## 主要功能
+
+### Spider:完整的爬虫框架
+
+- 🕷️ **类似 Scrapy 的 Spider API**:使用 `start_urls`、异步 `parse` 回调,以及 `Request` 和 `Response` 对象定义爬虫。
+- ⚡ **并发爬取**:设置并发请求数、每个域名的并发上限,以及下载间隔。
+- 🔄 **多种会话**:在同一个爬虫中使用 HTTP 请求和隐身无头浏览器。按会话 ID 将请求交给不同的会话处理。
+- 💾 **暂停和恢复**:用 `crawldir` 保存待处理请求和已访问的 URL。按 Ctrl+C 安全暂停,再用同一个目录启动即可继续。
+- 📡 **流式输出**:通过 `async for item in spider.stream()` 在数据提取后立即接收它,并查看实时统计信息。适合界面、数据处理流程和长时间运行的任务。
+- 🛡️ **识别被拦截的请求**:自动检测并重试被拦截的请求,也可以自定义处理逻辑。
+- 🚦 **AutoThrottle**:根据网站的响应速度,自动调整每个域名的请求间隔。如果网站拦截请求或限制频率,就将间隔加倍,或遵守 `Retry-After` 指定的等待时间。之后再逐步加快。
+- 🤖 **遵守 robots.txt**:启用 `robots_txt_obey`,即可遵守 `Disallow`、`Crawl-delay` 和 `Request-rate`。规则按域名缓存。
+- 🧪 **开发模式**:首次运行时将响应保存到磁盘,之后直接复用。这样可以修改 `parse()`,而不必再次请求服务器。
+- 🧩 **现成的爬虫模板**:使用 `CrawlSpider` 按规则跟踪链接,使用 `SitemapSpider` 从 sitemap 或 robots.txt 开始爬取,使用 `XMLFeedSpider` 和 `CSVFeedSpider` 读取 XML、RSS 和 CSV 数据源,或使用 `ShopifySpider` 获取公开 Shopify 商店的商品,每个商品变体生成一条数据。
+- 🔗 **提取链接**:`LinkExtractor` 可用模式允许或排除链接,过滤域名和文件扩展名,用 CSS 或 XPath 限定范围,并规范化 URL。它既可配合模板使用,也可单独使用。
+- 📦 **内置导出**:用钩子和自己的处理流程导出数据,或使用内置的 JSON、JSONL、CSV 和 XML 方法:`result.items.to_json()`、`to_jsonl()`、`to_csv()` 和 `to_xml()`。
+
+### 使用会话获取页面
+
+- **HTTP 请求**:用 `Fetcher` 发送快速、隐蔽的 HTTP 请求。支持模拟浏览器的 TLS 指纹和请求头,也支持 HTTP/3。
+- **动态加载**:用 `StealthyFetcher` 的完整浏览器自动化功能抓取动态网站。支持 Playwright 的 Chromium 和 Google Chrome。
+- **绕过反爬检测**:`StealthyFetcher` 隐藏自动化特征并模拟浏览器指纹,能自动处理多种 Cloudflare Turnstile 和 Interstitial 验证。
+- **会话管理**:`FetcherSession` 和 `StealthySession` 可在多次请求之间保留 Cookie 和状态。
+- **代理轮换**:`ProxyRotator` 支持在所有会话类型中按顺序或自定义规则切换代理,也可以为单次请求指定代理。
+- **拦截域名和广告**:拦截指定域名及其子域名的请求,或启用浏览器 Fetcher 的广告拦截功能。内置列表包含约 3,500 个已知广告和跟踪域名。
+- **防止 DNS 泄漏**:启用 DNS-over-HTTPS,通过 Cloudflare 的 DoH 服务发送 DNS 查询,防止使用代理时泄漏 DNS。
+- **远程浏览器**:通过 CDP 和 `cdp_url` 连接已运行的浏览器,包括本机、远程服务器和浏览器服务商提供的浏览器。也可以用 `executable_path` 为任意浏览器 Fetcher 指定自己的 Chromium 程序。
+- **记录后台 API 响应**:在浏览器会话中启用 `record_requests=True`,再用 `session.network.search(limit=None)` 搜索已保存的响应。无需重复请求,即可读取多次页面访问中的 API 数据和 HTTP 错误。历史记录有大小上限,只保存文本响应的内容。
+- **异步支持**:所有 Fetcher 都支持异步操作,并提供专用的异步会话类。
+
+### 解析页面和提取数据
+
+- 🔄 **重新定位元素**:网站结构改变后,用相似度算法重新找到元素。
+- 🎯 **灵活选择**:支持 CSS、XPath、过滤器、文本、正则表达式等方式。
+- 🔍 **相似元素**:自动查找与已选元素相似的元素。
### AI 功能
-- 🤖 **MCP 服务器**:让 AI 聊天机器人和智能体(Claude/Cursor 等)通过 Scrapling 抓取网页,使用 HTTP 请求、浏览器操作、截图、已保存的登录状态和后台 API 响应。借助我们的隐身浏览器和合适的工具,让具备相应能力的 AI 模型能够绕过工作中遇到的任何 CAPTCHA(更不用说我们自带的 Cloudflare 自动解题功能)。通过多种方法减少发送给模型的内容、屏蔽广告,并保护模型免受提示注入。还支持通过 CDP 连接远程浏览器,以及带身份验证选项的 HTTP 传输。([演示视频](https://www.youtube.com/watch?v=qyFk3ZNwOxE))
-- 🧠 **Agent Skill**:[开箱即用的 Agent Skill](https://scrapling.readthedocs.io/en/latest/ai/agent-skill.html),让编码智能体全面掌握本库,使它们用 Scrapling 写出的代码符合当前 API,而不是靠猜测。
-- 📚 **RAG 就绪的 Markdown**:用一行代码(`page.markdown()`)把任意页面转换为干净、经过净化、可直接供 LLM 使用的 Markdown,或使用 `ContentSpider` 模板把整个网站抓取为 Markdown 语料库,整个过程无需调用 LLM。([文档](https://scrapling.readthedocs.io/en/latest/ai/building-rag-systems.html))
-
-### 高性能和经过实战测试的架构
-- 🚀 **闪电般快速**:优化性能超越大多数 Python 抓取库。
-- 🔋 **内存高效**:优化的数据结构和延迟加载,最小内存占用。
-- ⚡ **快速 JSON 序列化**:比标准库快 10 倍。
-- 🏗️ **经过实战测试**:Scrapling 不仅拥有 92% 的测试覆盖率和完整的类型提示覆盖率,而且在过去一年中每天被数百名 Web Scraper 使用。
-
-### 对开发者/Web Scraper 友好的体验
-- 🎯 **交互式 Web Scraping Shell**:可选的内置 IPython Shell,具有 Scrapling 集成、快捷方式和新工具,可加快 Web Scraping 脚本开发,例如将 curl 请求转换为 Scrapling 请求并在浏览器中查看请求结果。
-- 🚀 **直接从终端使用**:可选地,您可以使用 Scrapling 抓取 URL 而无需编写任何代码!
-- 🛠️ **丰富的导航 API**:使用父级、兄弟级和子级导航方法进行高级 DOM 遍历。
-- 🧬 **增强的文本处理**:内置正则表达式、清理方法和优化的字符串操作。
-- 📝 **自动选择器生成**:为任何元素生成强大的 CSS/XPath 选择器。
-- 🔌 **熟悉的 API**:类似于 Scrapy/BeautifulSoup,使用与 Scrapy/Parsel 相同的伪元素。
-- 🤝 **无缝集成 Scrapy**:已经在用 Scrapy?用 `scrapling_response` 装饰任意回调,即可用 Scrapling 的解析器解析您本来就抓取到的响应,无需重写项目。
-- 📘 **完整的类型覆盖**:完整的类型提示,出色的 IDE 支持和代码补全。整个代码库在每次更改时都会自动使用**PyRight**和**MyPy**扫描。
-- 🔋 **现成的 Docker 镜像**:每次发布时,包含所有浏览器的 Docker 镜像会自动构建和推送。
+
+- 🤖 **MCP 服务器**:让 Claude、Cursor 等 AI 助手和智能体通过 Scrapling 提取数据。支持 HTTP 请求、浏览器操作、截图、保存的登录状态和后台 API 响应。它使用我们的隐身浏览器,并提供工具,让具备相应能力的模型处理 CAPTCHA,补充内置的 Cloudflare 验证处理功能。它还减少发送给模型的内容、拦截广告,并防护提示词注入。支持通过 CDP 连接远程浏览器,也支持带身份验证选项的 HTTP 连接。([演示视频](https://www.youtube.com/watch?v=qyFk3ZNwOxE))
+- 🧠 **Agent Skill**:可安装的 [Agent Skill](https://scrapling.readthedocs.io/en/latest/zh/ai/agent-skill.html),帮助编程智能体了解这个库,并编写符合当前 API 的代码。
+- 📚 **用于 RAG 的 Markdown**:用一行代码(`page.markdown()`)将页面转成适合语言模型的整洁 Markdown,或用 `ContentSpider` 模板将整个网站保存为 Markdown 文件。无需语言模型。([文档](https://scrapling.readthedocs.io/en/latest/zh/ai/building-rag-systems.html))
+
+### 快速且经过实际使用
+
+- 🚀 **速度快**:经过优化,性能超过大多数 Python 网页抓取库。
+- 🔋 **内存占用低**:使用优化的数据结构,并按需加载。
+- ⚡ **快速输出 JSON**:速度是标准库的 10 倍。
+- 🏗️ **经过实际检验**:测试覆盖率达 92%,全部代码都有类型注解。过去一年中,数百人每天用它提取数据。
+
+### 开发和数据提取工具
+
+- 🎯 **交互式 Shell**:可选的 IPython Shell,内置 Scrapling、快捷命令和工具,方便快速开发抓取脚本。可将 curl 请求转成 Scrapling 请求,并在浏览器中查看结果。
+- 🚀 **命令行使用**:无需写代码,就能提取 URL 的内容。
+- 🛠️ **DOM 导航**:访问父元素、同级元素和子元素。
+- 🧬 **文本处理**:支持正则表达式、文本清理和优化的字符串操作。
+- 📝 **生成选择器**:为任意元素生成可靠的 CSS 和 XPath 选择器。
+- 🔌 **熟悉的 API**:与 Scrapy 和 BeautifulSoup 相似,并支持 Scrapy 和 Parsel 使用的伪元素。
+- 🤝 **直接集成 Scrapy**:给回调加上 `scrapling_response` 装饰器,就能用 Scrapling 解析器处理已有的 Scrapy 响应,无需重写程序。
+- 📘 **完整的类型注解**:帮助编辑器检查和补全代码。每次修改都会用 **PyRight** 和 **MyPy** 自动检查全部代码。
+- 🔋 **现成的 Docker 镜像**:每次发布新版本时,自动构建并发布包含所有浏览器的 Docker 镜像。
## 入门
-让我们快速展示 Scrapling 的功能,无需深入了解。
+下面是一些常见用法。
### 基本用法
-支持 Session 的 HTTP 请求
+使用会话发送 HTTP 请求
```python
from scrapling.fetchers import Fetcher, FetcherSession
@@ -302,7 +308,7 @@ with FetcherSession(impersonate='chrome') as session: # 使用 Chrome 的最新
page = Fetcher.get('https://quotes.toscrape.com/')
quotes = page.css('.quote .text::text').getall()
```
-高级隐秘模式
+隐身模式
```python
from scrapling.fetchers import StealthyFetcher, StealthySession
@@ -328,7 +334,7 @@ data = page.css('.quote .text::text').getall()
```
### Spider
-构建具有并发请求、多种 Session 类型和暂停/恢复功能的完整爬虫:
+构建支持并发请求、多种会话、暂停和恢复的完整爬虫:
```python
from scrapling.spiders import Spider, Response
@@ -352,7 +358,7 @@ result = QuotesSpider().start()
print(f"抓取了 {len(result.items)} 条引用")
result.items.to_json("quotes.json")
```
-在单个 Spider 中使用多种 Session 类型:
+在同一个 Spider 中使用多种会话:
```python
from scrapling.spiders import Spider, Request, Response
from scrapling.fetchers import FetcherSession, AsyncStealthySession
@@ -373,13 +379,13 @@ class MultiSessionSpider(Spider):
else:
yield Request(link, sid="fast", callback=self.parse) # 显式 callback
```
-通过如下方式运行 Spider 来暂停和恢复长时间爬取,使用 Checkpoint:
+保存进度,就能暂停和恢复长时间运行的任务。这样启动 Spider:
```python
QuotesSpider(crawldir="./crawl_data").start()
```
设置 `crawldir` 后,按 Ctrl+C 保存待处理请求和已访问 URL。使用同一个 `crawldir` 重启即可继续。请单独保存提取的数据。
-也可以用现成模板直接省去编写爬取逻辑,比如获取整个 Shopify 店铺的商品目录:
+也可以使用现成的模板,例如获取整个 Shopify 商店的商品目录:
```python
from scrapling.spiders import ShopifySpider
@@ -388,7 +394,7 @@ class MyStore(ShopifySpider):
result = MyStore().start() # 店铺中的所有商品,每个变体一条记录
```
-模板读取公开集合接口中提供的商品,每个变体一条记录。
+模板从公开的商品集合接口读取商品,每个商品变体生成一条数据。
### 高级解析与导航
```python
@@ -420,15 +426,15 @@ parent_container = first_quote.parent
similar_elements = first_quote.find_similar()
below_elements = first_quote.below_elements
```
-如果您不想获取网站,可以直接使用解析器,如下所示:
+也可以直接使用解析器,无需先获取网页:
```python
from scrapling.parser import Selector
page = Selector("<html>...</html>")
```
-用法完全相同!
+用法相同。
-### Async Session 管理示例
+### 异步会话示例
```python
import asyncio
from scrapling.fetchers import FetcherSession, AsyncStealthySession
@@ -449,11 +455,11 @@ asyncio.run(main())
## CLI 和交互式 Shell
-Scrapling 包含强大的命令行界面:
+也可以在终端中使用 Scrapling:
[![asciicast](https://asciinema.org/a/736339.svg)](https://asciinema.org/a/736339)
-启动交互式 Web Scraping Shell
+启动交互式网页抓取 Shell:
```bash
pip install "scrapling[shell]"
scrapling shell
@@ -467,37 +473,37 @@ scrapling extract fetch 'https://nopecha.com/demo/cloudflare' captchas.html --cs
```
> [!NOTE]
-> 还有许多其他功能,但我们希望保持此页面简洁,包括 MCP 服务器和交互式 Web Scraping Shell。查看完整文档 [这里](https://scrapling.readthedocs.io/en/latest/)
+> 更多功能,包括 MCP 服务器和交互式 Shell,请查看[完整文档](https://scrapling.readthedocs.io/en/latest/zh/)。
-## 性能基准
+## 性能测试
-Scrapling 不仅功能强大--它还速度极快。以下基准测试将 Scrapling 的解析器与其他流行库的最新版本进行了比较。
+Scrapling 的速度也很出色。下面对比它的解析器和其他常用库的最新版本。
-### 文本提取速度测试(5000 个嵌套元素)
+### 文本提取速度(5,000 个嵌套元素)
-| # | 库 | 时间 (ms) | vs Scrapling |
+| # | 库 | 时间(毫秒) | 相对 Scrapling |
|---|:-----------------:|:---------:|:------------:|
| 1 | Scrapling | 1.99 | 1.0x |
| 2 | Parsel/Scrapy | 2.06 | 1.035 |
-| 3 | Raw Lxml | 2.56 | 1.286 |
+| 3 | 原生 Lxml | 2.56 | 1.286 |
| 4 | PyQuery | 23.98 | ~12x |
| 5 | Selectolax | 197.02 | ~99x |
| 6 | MechanicalSoup | 1545.15 | ~776.5x |
-| 7 | BS4 with Lxml | 1562.1 | ~785.0x |
-| 8 | BS4 with html5lib | 3412.73 | ~1714.9x |
+| 7 | BS4 + Lxml | 1562.1 | ~785.0x |
+| 8 | BS4 + html5lib | 3412.73 | ~1714.9x |
-### 元素相似性和文本搜索性能
+### 相似元素和文本搜索
-Scrapling 的自适应元素查找功能明显优于替代方案:
+Scrapling 的自适应元素查找比其他方案更快:
-| 库 | 时间 (ms) | vs Scrapling |
+| 库 | 时间(毫秒) | 相对 Scrapling |
|-------------|:---------:|:------------:|
| Scrapling | 2.3 | 1.0x |
| AutoScraper | 12.58 | 5.47x |
-> 所有基准测试代表 100+ 次运行的平均值。请参阅 [benchmarks.py](https://github.com/D4Vinci/Scrapling/blob/main/benchmarks.py) 了解方法。
+> 每项结果都是至少 100 次运行的平均值。测试方法见 [benchmarks.py](https://github.com/D4Vinci/Scrapling/blob/main/benchmarks.py)。
## 安装
@@ -508,11 +514,11 @@ pip install scrapling
```
> [!IMPORTANT]
-> 此安装仅包括解析器引擎及其依赖项,没有任何 Fetcher 或命令行依赖项。 因此,仅使用此安装时,像上面的示例那样从 `scrapling.fetchers` 或 `scrapling.spiders` 导入任何内容都会引发 `ModuleNotFoundError`。如果要使用任何 Fetcher 或 Spider,请先按照下面的说明安装 Fetcher 的依赖项。
+> 这个命令只安装解析器及其依赖,不包含 Fetcher 或命令行工具。仅安装这些依赖后,像上面的示例那样从 `scrapling.fetchers` 或 `scrapling.spiders` 导入内容,会出现 `ModuleNotFoundError`。要使用 Fetcher 或 Spider,请先按下文安装 Fetcher 的依赖。
-### 可选依赖项
+### 可选依赖
-1. 如果您要使用以下任何额外功能、Fetcher 或它们的类,您将需要安装 Fetcher 的依赖项和它们的浏览器依赖项,如下所示:
+1. 要使用 Fetcher、相关类或下列扩展功能,请先安装 Fetcher 和浏览器的依赖:
```bash
pip install "scrapling[fetchers]"
@@ -520,9 +526,9 @@ pip install scrapling
scrapling install --force # force reinstall
```
- 这会下载所有浏览器,以及它们的系统依赖项和 fingerprint 操作依赖项。
+ 这会下载所有浏览器、所需的系统依赖,以及修改浏览器指纹的工具。
- 或者你可以从代码中安装,而不是运行命令:
+ 也可以在 Python 代码中安装,无需运行命令:
```python
from scrapling.cli import install
@@ -530,47 +536,47 @@ pip install scrapling
install(["--force"], standalone_mode=False) # force reinstall
```
-2. 额外功能:
- - 安装 MCP 服务器功能:
+2. 扩展功能:
+ - 安装 MCP 服务器:
```bash
pip install "scrapling[ai]"
```
- - 安装([构建 RAG 系统](https://scrapling.readthedocs.io/en/latest/ai/building-rag-systems.html))所需的依赖:
+ - 安装[构建 RAG 系统](https://scrapling.readthedocs.io/en/latest/zh/ai/building-rag-systems.html)所需的依赖:
```bash
pip install "scrapling[rag]"
```
- - 安装 Shell 功能(Web Scraping Shell 和 `extract` 命令):
+ - 安装交互式 Shell 和 `extract` 命令:
```bash
pip install "scrapling[shell]"
```
- - 安装所有内容:
+ - 安装所有功能:
```bash
pip install "scrapling[all]"
```
- 需要浏览器抓取时再运行 `scrapling install`。HTTP 请求无需安装浏览器。
+ 如果要使用浏览器 Fetcher,请运行 `scrapling install`。HTTP 请求不需要安装浏览器。
### Docker
-您还可以使用以下命令从 DockerHub 安装包含所有额外功能和浏览器的 Docker 镜像:
+也可以从 DockerHub 下载包含所有扩展功能和浏览器的 Docker 镜像:
```bash
docker pull pyd4vinci/scrapling
```
-或从 GitHub 注册表下载:
+或从 GitHub 容器仓库下载:
```bash
docker pull ghcr.io/d4vinci/scrapling:latest
```
-此镜像使用 GitHub Actions 和仓库主分支自动构建和推送。
+镜像基于仓库的主分支构建,由 GitHub Actions 自动发布。
## 贡献
-我们欢迎贡献!在开始之前,请阅读我们的 [贡献指南](https://github.com/D4Vinci/Scrapling/blob/main/CONTRIBUTING.md)。
+欢迎参与项目!开始前,请阅读[贡献指南](https://github.com/D4Vinci/Scrapling/blob/main/CONTRIBUTING.md)。
## 免责声明
> [!CAUTION]
-> 此库仅用于教育和研究目的。使用此库即表示您同意遵守本地和国际数据抓取和隐私法律。作者和贡献者对本软件的任何滥用不承担责任。始终尊重网站的服务条款和 robots.txt 文件。
+> 本库仅用于学习和研究。使用本库即表示同意遵守当地和国际上的数据抓取及隐私法律。作者和贡献者不对软件被滥用承担责任。请遵守网站的服务条款和 robots.txt 文件。
## 🎓 引用
-如果您将我们的库用于研究目的,请使用以下参考文献引用我们:
+如果在研究中使用本库,请按以下格式引用:
```text
@misc{scrapling,
author = {Karim Shoair},
@@ -583,12 +589,12 @@ docker pull ghcr.io/d4vinci/scrapling:latest
## 许可证
-本作品根据 BSD-3-Clause 许可证授权。
+本项目使用 BSD-3-Clause 许可证。
## 致谢
-此项目包含改编自以下内容的代码:
-- Parsel(BSD 许可证)--用于 [translator](https://github.com/D4Vinci/Scrapling/blob/main/scrapling/core/translator.py)子模块
+本项目包含改编自以下项目的代码:
+- Parsel(BSD 许可证):用于 [translator](https://github.com/D4Vinci/Scrapling/blob/main/scrapling/core/translator.py) 子模块
---
<div align="center"><small>由 Karim Shoair 用❤️设计和制作。</small></div><br>
diff --git a/docs/locales/zh/ai/agent-skill.md b/docs/locales/zh/ai/agent-skill.md
new file mode 100644
index 0000000..435bef1
--- /dev/null
+++ b/docs/locales/zh/ai/agent-skill.md
@@ -0,0 +1,42 @@
+---
+title: "Scrapling Agent Skill:安装与使用"
+description: "为编程智能体安装 Scrapling Skill,提供最新 API 示例和参考资料,帮助它获取页面、解析内容和爬取网站。"
+---
+
+# Scrapling Agent Skill {#scrapling-agent-skill}
+
+[MCP 服务器](mcp-server.md)为 AI 聊天机器人提供抓取网站的工具,而 **Scrapling Agent Skill** 则让编程智能体学会使用 Scrapling 库本身。这样,它编写的代码就会使用当前 API,而不是根据过时的训练数据猜测。
+
+该 Skill 遵循 [AgentSkills](https://agentskills.io/specification) 规范,因此 [Claude Code](https://claude.com/product/claude-code)、[OpenClaw](https://github.com/openclaw/openclaw) 等智能体工具都能读取。它包含页面获取、解析、爬取、MCP 和 RAG 的 Markdown 指南,智能体可以按需加载。加上可直接运行的示例,智能体无需离开编辑器,就能回答大部分 Scrapling 问题并编写正确的抓取代码。
+
+该 Skill 位于仓库的 [agent-skill](https://github.com/D4Vinci/Scrapling/tree/main/agent-skill) 目录中,名称为 `scrapling-official`,版本始终与库版本保持一致。
+
+## 安装 {#installation}
+
+### Skills.sh {#skillssh}
+
+使用 [skills.sh](https://skills.sh) CLI 从仓库安装:
+```bash
+npx skills add D4Vinci/Scrapling --skill scrapling-official
+```
+CLI 会检测已安装的智能体,并为它们添加该 Skill。
+
+### Clawhub {#clawhub}
+
+如果使用 OpenClaw,可以通过 [Clawhub](https://docs.openclaw.ai/tools/clawhub) 安装:
+```bash
+clawhub install scrapling-official
+```
+也可以从它的 [Clawhub 页面](https://clawhub.ai/D4Vinci/scrapling-official)安装。
+
+### 手动下载 {#manual-download}
+
+[直接从仓库](https://github.com/D4Vinci/Scrapling/raw/refs/heads/main/agent-skill/Scrapling-Skill.zip)下载 Skill 的 ZIP 文件,解压到智能体的 Skills 目录。Claude Code 对应的目录是 `~/.claude/skills/`。
+
+## 内容 {#whats-inside}
+
+- **`SKILL.md`**:智能体首先读取的入口文件。它介绍设置方法、Fetcher 的选择和必须遵守的安全规则。例如,调用 CLI 命令时始终传入 `--ai-targeted`,以防范提示词注入。
+- **`references/`**:文档页面的 Markdown 副本,涵盖解析、页面获取、Spider、MCP 服务器和集成。它们按需加载,使用前不会占用智能体的上下文。
+- **`examples/`**:可直接运行的脚本,供智能体参考。
+
+我们已在 OpenClaw 和 Claude Code 中测试该 Skill。如果遇到问题,请提交 [Issue](https://github.com/D4Vinci/Scrapling/issues/new/choose),或通过我们的 [Discord 服务器](https://discord.gg/EMgGbDceNQ)联系。
diff --git a/docs/locales/zh/ai/building-rag-systems.md b/docs/locales/zh/ai/building-rag-systems.md
new file mode 100644
index 0000000..30454a0
--- /dev/null
+++ b/docs/locales/zh/ai/building-rag-systems.md
@@ -0,0 +1,109 @@
+---
+title: "用 Scrapling 将网站转为 Markdown,供 RAG 使用"
+description: "将页面响应转为 Markdown,或用 ContentSpider 采集整个网站,为 RAG 系统准备可分块和建立索引的文本。"
+---
+
+# 用 Scrapling 构建 RAG 系统 {#building-rag-systems-with-scrapling}
+
+RAG 系统的效果取决于输入的文本。原始 HTML 中的标签、导航、脚本和跟踪内容会浪费 token,甚至可能把隐藏的提示词注入内容直接传给 LLM。Scrapling 无需调用 LLM,就能把页面和整个网站转换为经过清理的 Markdown。数据采集因此速度快,也没有按页计费的成本。
+
+## 安装 {#installation}
+
+```bash
+pip install "scrapling[rag]"
+
+scrapling install
+```
+
+`rag` 扩展会安装 Fetcher 和 Markdown 转换支持,`ai`、`shell` 和 `all` 扩展也包含这些功能。`scrapling install` 会下载浏览器依赖,只有使用浏览器的 Fetcher 才需要它们。
+
+## 将单个页面转为 Markdown {#one-page-to-markdown}
+
+每个 [Response](../fetching/choosing.md#response-object) 都有 `markdown()` 方法:
+
+```python
+from scrapling.fetchers import Fetcher
+
+markdown = Fetcher.get("https://example.com").markdown(main_content_only=True)
+```
+
+它适用于所有 Fetcher,因此也可以用一行代码获取受 Cloudflare 保护的页面:
+
+```python
+from scrapling.fetchers import StealthyFetcher
+
+markdown = StealthyFetcher.fetch("https://protected.example.com", solve_cloudflare=True).markdown(main_content_only=True)
+```
+
+两个参数控制输出:
+
+- `main_content_only`:只转换页面 `<body>` 标签内的内容。
+- `css_selector`:只转换匹配 CSS 选择器的元素,并合并所有匹配结果。这样可以只提取处理流程需要的部分,节省 token:
+
+```python
+markdown = Fetcher.get("https://example.com/docs/page").markdown(css_selector="article")
+```
+
+无论传入什么参数,转换前都会移除脚本、样式和隐藏内容。这与 [MCP 服务器](mcp-server.md)保护 AI 智能体免受提示词注入时使用的清理方式相同。它会移除通过内联样式隐藏的元素、带有 `aria-hidden="true"` 的元素、隐藏的 slot、`<template>` 标签、HTML 注释和零宽字符。MCP 服务器在 `main_content_only=True` 时使用这套清理流程。
+
+## 将整个网站转为 Markdown 文档集 {#a-whole-website-to-a-markdown-corpus}
+
+`ContentSpider` 模板会爬取网站并转换每个页面。它基于 [Spider 框架](../spiders/architecture.md),支持并发、AutoThrottle、robots.txt 规则,以及暂停和恢复功能:
+
+```python
+from scrapling.spiders import ContentSpider
+
+class DocsSpider(ContentSpider):
+ name = "docs"
+ start_urls = ["https://example.com/docs/"]
+ allowed_domains = {"example.com"}
+ output_dir = "docs_markdown"
+ max_pages = 200
+
+result = DocsSpider().start()
+result.items.to_jsonl("docs.jsonl")
+```
+
+每个爬取的页面都会生成一个数据项,包含 `url`、`title` 和 `markdown` 键。如果设置了 `output_dir`,每个页面还会保存为一个 Markdown 文件,文件名根据 URL 生成。因此,上面的示例会得到一个包含 `.md` 文件的文件夹,以及一个可直接导入的 `docs.jsonl`。
+
+模板要求设置 `allowed_domains`,让爬取范围始终限制在目标网站内。可用选项如下:
+
+- `css_selector` / `main_content_only`:每个页面都会将它们传给 `markdown()`,其中 `main_content_only` 默认启用。
+- `output_dir`:设置后,每个页面都会写入一个 Markdown 文件。
+- `max_pages`:最多转换的页面数。达到上限时,已排队的请求可能仍会执行,但对应页面不会转换。默认值 `0` 表示不限制。
+
+默认会跟随 `allowed_domains` 内的所有页面链接。模板基于 [CrawlSpider](../spiders/generic-templates.md#crawlspider),因此可以重写 `rules()`,使用自己的 [LinkExtractor](../spiders/generic-templates.md#linkextractor-reference) 控制爬取范围。`allow` 只保留需要的 URL 模式,`deny` 排除不需要的模式,例如登录页、标签列表页和打印版页面:
+
+```python
+from scrapling.spiders import CrawlRule, LinkExtractor, ContentSpider
+
+class DocsSpider(ContentSpider):
+ name = "docs"
+ start_urls = ["https://example.com/"]
+ allowed_domains = {"example.com"}
+
+ def rules(self):
+ return [CrawlRule(LinkExtractor(allow=r"/docs/", deny=[r"/docs/changelog/", r"\?print="]))]
+```
+
+`deny` 的优先级高于 `allow`。与其他 **CrawlSpider** 一样,规则还可以包含 `priority` 或 `process_request` 钩子。
+
+## 将数据导入向量存储 {#feeding-a-vector-store}
+
+JSONL 输出可以接入任何生成 embedding 的流程。下面是一个最小示例:
+
+```python
+import json
+
+with open("docs.jsonl", encoding="utf-8") as f:
+ for line in f:
+ page = json.loads(line)
+ for chunk in split_into_chunks(page["markdown"]):
+ vector_store.add(text=chunk, metadata={"url": page["url"], "title": page["title"]})
+```
+
+在 Spider 中使用 `css_selector`,在文本分块前去掉重复的无关内容,避免后续再清理。embedding 中的噪声越少,检索效果就越好。
+
+## 交互式方案 {#interactive-alternatives}
+
+如果更喜欢通过对话抓取数据,[MCP 服务器](mcp-server.md)可以为 AI 聊天机器人提供同样的 Markdown 提取工具。[Agent Skill](agent-skill.md) 则能教会编程智能体自行编写这些代码。
diff --git a/docs/locales/zh/ai/mcp-server.md b/docs/locales/zh/ai/mcp-server.md
new file mode 100644
index 0000000..c8d4542
--- /dev/null
+++ b/docs/locales/zh/ai/mcp-server.md
@@ -0,0 +1,504 @@
+---
+title: "Scrapling MCP 服务器:设置与抓取流程"
+description: "将 AI 客户端连接到 Scrapling,进行 HTTP 或浏览器抓取。使用会话、保存的登录状态、浏览器操作、定向提取和 API 历史记录。"
+---
+
+# Scrapling MCP 服务器指南 {#scrapling-mcp-server-guide}
+
+<iframe width="560" height="315" src="https://www.youtube.com/embed/qyFk3ZNwOxE?si=3FHzgcYCb66iJ6e3" title="YouTube 视频播放器" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>
+
+**Scrapling MCP 服务器**将 Scrapling 的网页抓取能力直接提供给 AI 聊天机器人或智能体。通过 Claude 或其他支持 MCP 的界面,可以在对话中抓取网站、提取数据并绕过反爬保护。
+
+## 功能 {#features}
+
+Scrapling MCP 服务器提供十六个工具,用于网页抓取和浏览器交互。单次调用工具获取一个 URL 后,会关闭自己创建的浏览器或客户端。会话工具则在调用之间保留 Cookie 和设置,让 AI 可以继续操作同一个标签页,并查看网络历史记录。
+
+### 单次调用工具 {#one-shot-tools}
+
+#### 🚀 基础 HTTP 抓取 {#basic-http-scraping}
+
+- **`make_request`**:快速发送任意方法的 HTTP 请求(GET、POST、PUT、DELETE),并模拟浏览器指纹。它会生成与 TLS 版本匹配的真实浏览器请求头,还支持 HTTP/3 等功能。
+
+#### 🔒 隐身浏览器抓取 {#stealth-browser-scraping}
+
+- **`browser_fetch_once`**:使用隐身浏览器运行 JavaScript 并抓取动态页面。支持模拟指纹、绕过 Cloudflare Turnstile 和 Interstitial,以及控制浏览器和请求。
+
+### 会话工具 {#session-tools}
+
+#### 🔌 会话管理 {#session-management}
+
+- **`browser_open`**:创建持久的隐身浏览器会话,在多次 `browser_fetch` 调用之间保持打开,避免每次重新启动浏览器。它保留浏览器级配置,只返回 `session_id` 和 `session_type`。使用 `list_sessions` 查看实际生效的 `settings`,CDP 会话的该值为空。
+- **`open_request_session`**:创建不使用浏览器的持久 HTTP 会话,配合 `session_make_request` 使用。在请求之间保留 Cookie、连接和浏览器指纹(`impersonate`)。它只返回 `session_id` 和 `session_type`,类型为 `static`。使用 `list_sessions` 查看实际生效的 `settings`。
+- **`close_session`**:关闭持久的浏览器或 HTTP 会话,并释放资源。
+- **`list_sessions`**:列出所有活动会话及其详细信息和 `settings`。
+
+#### 浏览器状态 {#browser-state}
+
+- **`browser_save_state`**:将 Cookie、Local Storage 和 IndexedDB 保存为兼容 Playwright 的 JSON 文件,让登录状态在浏览器会话结束后仍可复用。保存时会覆盖已有文件。
+- **`browser_load_state`**:将保存的文件恢复到已打开的浏览器会话中,也可以在首次加载页面前使用。它会替换当前存储的状态,但不会关闭已有标签页或切换页面。要使用恢复的登录状态,需要获取或重新加载页面。
+
+状态文件存放在运行 MCP 服务器的机器上。它们不包含 `sessionStorage`、打开的标签页或浏览器设置。
+
+#### 🎯 通过会话获取页面 {#fetching-through-a-session}
+
+- **`browser_fetch`**:在已打开的隐身浏览器会话中运行 JavaScript 并抓取一个 URL,支持模拟指纹以及绕过 Cloudflare Turnstile 和 Interstitial。还可以生成包含元素引用、位置和大小的结构化页面快照,帮助 AI 识别控件并规划鼠标操作。
+- **`session_make_request`**:快速发送任意方法的 HTTP 请求(GET、POST、PUT、DELETE),支持模拟浏览器指纹、匹配的浏览器请求头和 HTTP/3。通过 `open_request_session` 打开的会话,复用 Cookie、连接和浏览器指纹。
+
+#### 📸 截图 {#screenshots}
+
+- **`browser_screenshot`**:无需重新加载,将当前页面或指定元素截图为 PNG 或 JPEG。可以检查已填写的字段、打开的菜单、图表或结果卡片。只截取一个元素可以减少无关内容。支持可见区域、整页或单个元素,并可调整 JPEG 质量。截图以图像内容块返回,模型可以直接查看。
+
+#### 当前页面内容 {#current-page-content}
+
+- **`browser_extract`**:无需重新加载,将当前页面或一个元素读取为 AI 快照、HTML、Markdown 或文本。可在填写表单或加载更多内容后提取结果。快照包含元素的角色、名称、引用、位置和大小,方便后续操作。正则搜索会返回匹配的快照行,以及附近上下文和父节点。
+
+#### 浏览器操作 {#browser-actions}
+
+- **`browser_actions`**:在一次调用中串联鼠标操作、字段填写、快捷键、对话框响应和等待。可以接受或关闭浏览器提示和确认框,也可以在输入对话框中填写文本。例如,填写搜索框、提交、等待结果,然后打开一个结果。AI 可以合并已知步骤;需要检查页面变化时,再单独获取快照。
+
+ 悬停以显示菜单和提示,点击按钮和链接,或将鼠标移到嵌套区域内进行纵向或横向滚动。移动和点击支持选择器、快照引用或坐标。以元素为目标时,会自动等待并将其滚动到可见区域。支持分多步移动到坐标、左键、右键和中键点击,以及双击。
+
+ 使用选择器或快照引用定位页面中的字段。可以填写文本、勾选或取消勾选复选框、选择单选按钮,以及按可见标签选择原生下拉列表中的一个或多个选项。文本可以替换现有内容、清空内容,或从当前光标位置继续输入。快捷键可以选择和删除文本、移动焦点、提交表单或关闭菜单。慢速模式逐字输入,并在字符之间及各个操作之间加入随机暂停。
+
+ 在下一步操作前,可以等待结果出现、加载遮罩消失或页面加载事件发生。也支持固定暂停,以及等待网络活动平息。
+
+#### JavaScript {#javascript}
+
+- **`browser_evaluate`**:在当前页面运行 JavaScript,进行自定义数据提取、计算或页面特有的操作。AI 可以汇总多个元素的数据、读取应用状态或更新页面内容。支持异步脚本,并以 JSON 返回结果。
+
+#### 网络历史记录 {#network-history}
+
+- **`browser_network_requests`**:查找跨标签页、页面加载和浏览器操作的已完成请求。可以找出页面数据背后的 API 调用、检查 HTTP 错误并查看已保存的重定向。默认隐藏静态资源,以缩小结果。请求详情以 JSON 返回,较长的历史记录支持分页。
+- **`browser_network_request`**:以结构化 JSON 查看某条已记录请求的摘要、HTTP 头信息、发送数据或文本响应体。完整返回选中的部分,无需加载页面或重发请求。已保存的响应在页面变化后仍然可用。大小限制会控制历史记录的规模;对于非文本、过大或无法读取的响应体,会用说明指出原因。请在关闭 MCP 会话前读取需要的详情。
+
+只有受支持的文本 `Content-Type` 才会读取并保存响应体,例如 HTML、JSON、XML 或 JavaScript。二进制、缺失或未知的内容类型只保留请求元数据和 HTTP 头信息,不读取或保存响应体。浏览器仍会正常加载资源。
+
+只保存已完成的请求,包括 HTTP 4xx 和 5xx 响应。失败和未完成的请求会被忽略。条目在捕获完成后才会出现,读取历史记录或关闭会话不会等待捕获。切换页面或关闭时仍在捕获的内容可能被忽略。保存的字节来自浏览器,可能与服务器原始字节不同。若为有效 UTF-8,文本按 Playwright 的 UTF-8 方式解码,否则使用声明的字符集。
+
+### Shadow DOM {#shadow-dom}
+
+在 `browser_fetch_once` 或每次 `browser_fetch` 调用中设置 `pierce_shadow=true`,即可包含开放 Shadow DOM 的内容。默认值为 `false`。选择器示例和限制请参阅 [Shadow DOM](../fetching/stealthy.md#shadow-dom)。
+
+### 核心能力 {#key-capabilities}
+
+- **内容提取**:将网页或元素转换为 Markdown、HTML,或提取干净的文本。
+- **CSS 选择器**:先用 Scrapling 精确选择元素,再将内容交给 AI。
+- **绕过反爬保护**:处理 Cloudflare Turnstile、Interstitial 和其他保护。
+- **代理支持**:使用代理隐藏来源或选择请求所在地区。
+- **模拟浏览器**:通过 TLS 指纹、匹配版本的真实浏览器请求头等方式模拟真实浏览器。
+- **持久会话**:在多次请求中复用浏览器会话,提高性能。
+- **广告拦截**:所有浏览器工具都会自动阻止发往约 3,500 个已知广告和跟踪域名的请求,节省 token 并加快加载。
+- **提示词注入防护**:自动清理可能用于攻击的隐藏内容,包括通过内联样式隐藏的元素、aria-hidden、隐藏的 slot、零宽字符、HTML 注释和 template 标签。
+
+#### 为什么使用 Scrapling MCP 服务器,而不是其他工具? {#but-why-use-scrapling-mcp-server-instead-of-other-available-tools}
+
+除了隐身能力和绕过 Cloudflare Turnstile、Interstitial 的功能,Scrapling 的服务器还是唯一能选择指定元素再交给 AI 的服务器。这可以节省很多时间和 token!
+
+其他服务器通常提取内容后,将全部内容交给 AI,让它寻找需要的字段。这会让 AI 为无关内容消耗大量 token。Scrapling 允许先用 CSS 选择器缩小内容范围,再传给 AI,让整个过程更快、更高效。
+
+如果不会编写 CSS 选择器,也不用担心。可以在提示词中要求 AI 为目标字段编写选择器,让它尝试不同组合,直到找到合适的方式。后面的示例会展示这一点。
+
+## 安装 {#installation}
+
+安装带 MCP 支持的 Scrapling,并确认浏览器依赖也已安装。
+
+```bash
+# Install Scrapling with MCP server dependencies
+pip install "scrapling[ai]"
+
+# Install browser dependencies
+scrapling install
+```
+
+也可以直接使用 Docker Registry 中的镜像:
+```bash
+docker pull pyd4vinci/scrapling
+```
+或者从 GitHub Registry 下载:
+```bash
+docker pull ghcr.io/d4vinci/scrapling:latest
+```
+
+## 设置 MCP 服务器 {#setting-up-the-mcp-server}
+
+下面介绍如何把 Scrapling MCP 服务器添加到 [Claude Desktop](https://claude.ai/download) 和 [Claude Code](https://www.anthropic.com/claude-code)。其他支持 MCP 的聊天机器人也可以参考相同步骤:
+
+!!! note "注意"
+ 下面使用的 `scrapling-mcp` 命令在 v0.4.13 中加入,直接对应 `scrapling mcp`。它让只接受单个命令的 MCP 注册目录和客户端更容易接入 Scrapling。旧版本请使用 `scrapling` 命令,并将 `mcp` 作为第一个参数。
+
+### Claude Desktop {#claude-desktop}
+
+1. 打开 Claude Desktop。
+2. 点击左上角菜单(☰),依次选择 Settings → Developer → Edit Config。
+3. 添加 Scrapling MCP 服务器配置:
+```json
+"ScraplingServer": {
+ "command": "scrapling-mcp"
+}
+```
+如果这是第一个 MCP 服务器,将文件内容设为:
+```json
+{
+ "mcpServers": {
+ "ScraplingServer": {
+ "command": "scrapling-mcp"
+ }
+ }
+}
+```
+根据[官方文章](https://modelcontextprotocol.io/quickstart/user),如果没有配置文件,这一步会创建它;如果已有配置文件,就会打开现有文件。文件位置如下:
+
+1. **MacOS**:`~/Library/Application Support/Claude/claude_desktop_config.json`
+2. **Windows**:`%APPDATA%\Claude\claude_desktop_config.json`
+
+为确保正常运行,请使用 `scrapling-mcp` 可执行文件的完整路径。可以用以下命令查找:
+
+1. **MacOS**:`which scrapling-mcp`
+2. **Windows**:`where scrapling-mcp`
+
+在我的 Mac 上,结果是 `/Users/<MyUsername>/.venv/bin/scrapling-mcp`,因此最终配置如下:
+```json
+{
+ "mcpServers": {
+ "ScraplingServer": {
+ "command": "/Users/<MyUsername>/.venv/bin/scrapling-mcp"
+ }
+ }
+}
+```
+#### Docker {#docker}
+
+如果使用 Docker 镜像,配置类似这样:
+```json
+{
+ "mcpServers": {
+ "ScraplingServer": {
+ "command": "docker",
+ "args": [
+ "run", "-i", "--rm", "pyd4vinci/scrapling", "mcp"
+ ]
+ }
+ }
+}
+```
+
+[Cursor](https://cursor.com/docs/context/mcp)、[WindSurf](https://windsurf.com/university/tutorials/configuring-first-mcp-server) 等客户端也适用相同的配置思路。
+
+### Claude Code {#claude-code}
+
+[Claude Code](https://www.anthropic.com/claude-code) 的配置更简单:
+
+```bash
+claude mcp add ScraplingServer "/Users/<MyUsername>/.venv/bin/scrapling-mcp"
+```
+查找 Scrapling 可执行文件路径:
+
+1. **MacOS**:`which scrapling-mcp`
+2. **Windows**:`where scrapling-mcp`
+
+更多细节请参阅 Anthropic 关于[向 Claude Code 添加 MCP 服务器](https://docs.anthropic.com/en/docs/claude-code/mcp#option-1%3A-add-a-local-stdio-server)的文章。
+
+添加服务器后,完全退出并重新启动应用。在 Claude Desktop 中,应能看到输入框右下角的 MCP 服务器图标(🔧),或输入框 `Search and tools` 菜单中的 `ScraplingServer`。
+
+### 自定义浏览器可执行文件 {#custom-browser-executable}
+
+`browser_fetch_once` 和 `browser_open` 可以使用兼容 Chromium 的自定义浏览器可执行文件,替代自带的 Chromium。这适用于定制浏览器版本或轻量浏览器引擎。
+
+要为整个 MCP 服务器统一设置,在启动时传入可执行文件路径:
+
+```bash
+scrapling-mcp --executable-path "/path/to/chromium"
+```
+
+在 Claude Desktop 配置中,将该选项加入服务器参数:
+
+```json
+{
+ "mcpServers": {
+ "ScraplingServer": {
+ "command": "/Users/<MyUsername>/.venv/bin/scrapling-mcp",
+ "args": [
+ "--executable-path",
+ "/path/to/chromium"
+ ]
+ }
+ }
+}
+```
+
+也可以在启动前设置环境变量 `SCRAPLING_EXECUTABLE_PATH`。AI 仍可在单次 `browser_fetch_once` 调用中,或使用 `browser_open` 打开会话时,选择另一个浏览器可执行文件。
+
+### 连接远程浏览器 {#connecting-to-remote-browsers}
+
+`browser_open` 不一定要启动本地浏览器。传入 CDP URL 后,它会通过 [Chrome DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/) 连接到已运行的浏览器。浏览器可以在同一台机器、其他主机或托管浏览器服务中运行:
+```
+Open a stealthy browser session on wss://cdp.provider.example/session/abc123, then use it to scrape the product details from https://shop.example.com. Close the session when you're done.
+```
+返回的 `session_id` 可以照常用于 `browser_fetch`、`browser_extract`、`browser_actions`、`browser_evaluate`、`browser_screenshot`、`browser_network_requests`、`browser_network_request`、`browser_save_state` 和 `browser_load_state`。
+
+URL 可以是浏览器服务提供的 WebSocket 地址(`ws://`/`wss://`),也可以是自行启动并开启远程调试端口的浏览器 HTTP 地址:
+```commandline
+chrome --remote-debugging-port=9222
+```
+可以通过 `cdp_url="http://localhost:9222"` 连接它;如果浏览器运行在另一台机器上,则使用那台机器的地址。
+
+!!! note "说明"
+
+ * 浏览器已经在运行,因此 CDP 会话会忽略仅在启动浏览器时生效的选项:`headless`、`real_chrome` 和 `executable_path`(包括上面提到的服务器默认值)。<br/>
+ * 其他选项仍然生效(`locale`、`useragent`、`proxy`、`cookies`、`timezone_id` 等),因为每个会话都会在远程浏览器中创建自己的浏览器上下文。
+
+### Streamable HTTP {#streamable-http}
+从 0.3.6 版起,MCP 服务器可以使用 Streamable HTTP 传输方式,替代传统的 stdio 传输方式。
+
+原来使用的是以下 stdio 命令:
+```bash
+scrapling-mcp
+```
+改用以下命令即可启用 Streamable HTTP:
+```bash
+scrapling-mcp --http
+```
+服务器默认监听地址为 127.0.0.1,端口为 8000,两者都可以按下面的方式设置:
+```bash
+scrapling-mcp --http --host '0.0.0.0' --port 8000
+```
+默认只接受来自同一台机器的连接。要让其他机器通过网络访问服务器,请传入 `--host '0.0.0.0'`。网络访问和下面介绍的身份验证是两个独立的设置。
+
+在 Docker 中运行 Streamable HTTP 时,必须手动绑定到 0.0.0.0 并设置 token,否则映射的端口无法连接到服务器,因为容器中的 127.0.0.1 只能在容器内部访问:
+```bash
+docker run -p 8000:8000 -e SCRAPLING_MCP_AUTH_TOKEN="<your-token>" pyd4vinci/scrapling mcp --http --host '0.0.0.0'
+```
+
+### 身份验证 {#authentication}
+
+stdio 只能由启动它的程序访问。切换到 Streamable HTTP 后,任何能访问该端口的人都可以调用全部工具,包括从服务器所在的机器获取任意 URL。因此,Streamable HTTP 要求身份验证;只传入 `--http` 时,服务器会拒绝启动,并要求提供 token:
+```bash
+scrapling-mcp --http --auth-token "$(openssl rand -hex 32)"
+```
+客户端必须在 `Authorization` 请求头中发送该 token。没有 token 的请求会收到 `401` 响应:
+```json
+{
+ "mcpServers": {
+ "ScraplingServer": {
+ "url": "https://your-server.example.com/mcp",
+ "headers": {
+ "Authorization": "Bearer <your-token>"
+ }
+ }
+ }
+}
+```
+通过命令行传入 token 会使它留在 shell 历史记录和进程列表中,因此建议使用 `SCRAPLING_MCP_AUTH_TOKEN` 环境变量:
+```bash
+export SCRAPLING_MCP_AUTH_TOKEN="<your-token>"
+scrapling-mcp --http
+```
+如果确实需要关闭身份验证,例如在默认地址 127.0.0.1 上进行本地测试,必须明确传入 `--no-auth`:
+```bash
+scrapling-mcp --http --no-auth
+```
+同时使用 `--no-auth` 和 `--host '0.0.0.0'`,会让任何能访问该端口的人调用全部工具,因此不要在不受信任的网络中这样设置。
+
+服务器监听公网地址时,还应指定允许的主机名,以启用 DNS 重绑定攻击防护。这类攻击会让浏览器访问的网站尝试连接到本地服务器。可以多次传入该选项:
+```bash
+scrapling-mcp --http --allowed-host 'your-server.example.com:8000'
+```
+
+!!! note "说明"
+
+ * 身份验证仅适用于 Streamable HTTP。stdio 会忽略它,并在日志中记录警告。<br/>
+ * 普通 HTTP 会以明文发送 token,因此将服务器开放到互联网前,应在它前面部署负责 TLS 的反向代理。<br/>
+ * 这是一个共享密钥,不是每个客户端各自的凭据。所有客户端使用同一个 token,更换 token 后需要重启服务器。<br/>
+ * 使用 `--http --no-auth` 启动时,服务器仍会记录警告,提醒身份验证已关闭。<br/>
+ * 同时传入 `--auth-token` 和 `--no-auth` 时,服务器会保留 token 并继续验证身份,不会悄悄关闭身份验证。
+
+## 示例 {#examples}
+
+下面介绍一些测试 MCP 服务器时使用的提示词。也许大家能想出更有创意的用法,写出更好的提示词 :)
+
+我们会从简单的提示词逐步讲到更复杂的提示词。示例使用 Claude Desktop,但相同思路也适用于其他客户端。
+
+1. **基本网页抓取**
+
+ 将网页的主要内容提取为 Markdown:
+
+ ```
+ Scrape the main content from https://example.com and convert it to markdown format.
+ ```
+
+ Claude 可以使用 `make_request` 获取页面,并返回干净、易读的内容。HTTP 请求默认最多尝试三次,每次尝试之间等待一秒。如果页面需要 JavaScript 或阻止 HTTP 请求,AI 可以改用 `browser_fetch_once`。这两个工具都会在调用结束后关闭各自的资源。
+
+ 同一个提示词可以写得更明确:
+ ```
+ Use regular requests to scrape the main content from https://example.com and convert it to markdown format.
+ ```
+ 这样可以告诉 Claude 要使用哪个工具,无需让它猜。有时它会自行使用普通请求,有时又会在没有明显理由的情况下认为浏览器更适合这个网站。通常,明确指定工具可以节省时间和费用,也能让结果更一致。
+
+2. **定向提取数据**
+
+ 使用 CSS 选择器提取指定元素:
+
+ ```
+ Get all product titles from https://shop.example.com using the CSS selector '.product-title'. If the request fails, retry up to 5 times every 10 seconds.
+ ```
+
+ 服务器只会提取与选择器匹配的元素,并以结构化列表返回。这里让工具最多尝试 5 次,以应对网站连接问题,不过默认设置已适合大多数情况。
+
+3. **收集电商数据**
+
+ 再看一个稍复杂的提示词:
+ ```
+ Open a stealthy browser session and visit these e-commerce URLs one at a time:
+ - https://shop1.com/product-a
+ - https://shop2.com/product-b
+ - https://shop3.com/product-c
+
+ Get the product names, prices, and descriptions from each page. Close the session when done.
+ ```
+
+ Claude 可以复用一个浏览器会话,按顺序为每个 URL 调用 `browser_fetch`,再分析提取的数据。
+
+4. **更复杂的工作流程**
+
+ 假设要获取 PlayStation 商店第一页上的所有动作游戏,可以使用以下提示词:
+ ```
+ Extract the URLs of all games on this page, then visit each game in order and return a list of all action games: https://store.playstation.com/en-us/pages/browse
+ ```
+ 如果普通请求就能获取数据,可以让 AI 复用 HTTP 会话,避免启动浏览器:
+ ```
+ Open an HTTP session, extract the URLs of all games on this page, then fetch each game in order and return a list of all action games. Close the session when done: https://store.playstation.com/en-us/pages/browse
+ ```
+ 如果会编写 CSS 选择器,还可以在 AI 读取内容前缩小提取范围:
+ ```
+ Use an HTTP session to extract the URLs of all games on the page below, then fetch each game in order and return a list of all action games.
+ The selector for games in the first page is `[href*="/concept/"]` and the selector for the genre in each game page is `[data-qa="gameInfo#releaseInformation#genre-value"]`.
+ Close the session when done.
+
+ URL: https://store.playstation.com/en-us/pages/browse
+ ```
+
+5. **从有 Cloudflare 保护的网站获取数据**
+
+ 如果认为目标网站有 Cloudflare 保护,请直接告诉 Claude,不要让它自行发现。
+ ```
+ What's the price of this product? Be cautious, as it utilizes Cloudflare's Turnstile protection. Make the browser visible while you work.
+
+ https://ao.com/product/oo101uk-ninja-woodfire-outdoor-pizza-oven-brown-99357-685.aspx
+ ```
+
+6. **较长的工作流程**
+
+ 例如,可以使用这样的提示词:
+ ```
+ Extract all product URLs for the following category, then return the prices and details for the first 3 products.
+
+ https://www.arnotts.ie/furniture/bedroom/bed-frames/
+ ```
+ 但下面的提示词更好:
+ ```
+ Go to the following category URL and extract all product URLs using the CSS selector "a". Then, reuse the session to fetch the first 3 product pages in order and extract each product’s price and details. Close the session when done.
+
+ Keep the output in markdown format to reduce irrelevant content.
+
+ Category URL:
+ https://www.arnotts.ie/furniture/bedroom/bed-frames/
+ ```
+
+7. **使用持久会话**
+
+ 抓取同一个网站的多个页面时,使用持久浏览器会话可以避免为每个请求启动新浏览器的开销:
+ ```
+ Open a stealthy browser session, then use it to scrape the main details from the first 5 product pages on https://shop.example.com. Close the session when you're done.
+ ```
+ Claude 会用 `browser_open` 创建持久浏览器,通过该会话为每个商品页面调用 `browser_fetch`,最后调用 `close_session`。这比每个页面都启动一个新浏览器快得多。
+
+ !!! danger "危险"
+
+ 使用持久会话时,完成后一定要关闭会话,否则它会一直保持打开状态!
+
+
+8. **在较长的流程中使用持久会话**
+
+ 另一个需要 Claude 多思考的较长测试示例:
+
+ ```
+ Use Scrapling MCP to do the following in this order:
+
+ 1. Open a stealthy browser session with headless mode off.
+ 2. Go to this page and collect the number of stars: https://github.com/D4Vinci/Scrapling
+ 3. From the README, get the URL that shows the number of downloads and go to it.
+ 4. Get the number of downloads and the top 3 countries from the graph.
+ 5. Prepare a report with the results.
+ 6. Close the browser.
+ ```
+
+这些只是一些例子,还可以发挥创意,探索更多用法。
+
+## 最佳实践 {#best-practices}
+
+下面是一些技术建议。
+
+### 1. 选择合适的工具 {#1-choose-the-right-tool}
+- **`make_request`**:快速完成单个页面或 API 的 HTTP 请求
+- **`browser_fetch_once`**:获取单个需要 JavaScript 的动态页面,或包括 Cloudflare 在内的受保护网站
+- **会话工具**:处理相关请求、浏览器操作、截图和网络历史记录
+
+### 2. 提高性能 {#2-optimize-performance}
+- 复用会话,并按顺序获取每个 URL
+- 禁用不需要的资源
+- 设置合适的超时时间
+- 使用 CSS 选择器定向提取内容
+
+### 3. 处理动态内容 {#3-handle-dynamic-content}
+- 对单页应用(SPA)使用 `network_idle`
+- 设置 `wait_selector` 来等待指定元素
+- 对加载较慢的网站增加超时时间
+
+### 4. 数据质量 {#4-data-quality}
+- 使用 `main_content_only=true` 选取并清理页面的正文
+- 根据用途选择合适的 `extraction_type`
+
+### 5. 提示词注入防护 {#5-prompt-injection-protection}
+启用 `main_content_only`(默认启用)时,MCP 服务器会自动清理抓取的内容,移除恶意网站可能用来向 AI 上下文注入指令的隐藏内容:
+
+- **用于隐藏内容的内联样式**:`display:none`、`visibility:hidden`,以及透明度、字号、高度、宽度、最大高度或最大宽度为零的样式
+- **对辅助功能隐藏的元素**:`aria-hidden="true"`
+- **模板标签和隐藏插槽**:`<template>` 和 `<slot hidden>` 元素
+- **HTML 注释**:`<!-- ... -->`
+- **零宽字符**:零宽空格等不可见的 Unicode 字符
+
+提取 HTML、Markdown 和文本时都会自动执行此防护。保留默认的 `main_content_only=true` 可以获得最完整的防护。
+
+### 6. 管理会话 {#6-manage-sessions}
+- 单次获取页面时,使用 `make_request` 或 `browser_fetch_once`;它们会关闭各自的资源,不会留下供后续调用使用的会话
+- 抓取多个页面时,使用 `browser_open` 创建持久浏览器会话,再通过该会话为每个页面调用 `browser_fetch`
+- 发送多个普通 HTTP 请求时,改用 `open_request_session`,并为每个请求调用 `session_make_request`;它会在调用之间保留 Cookie、连接和浏览器指纹(`impersonate`),无需启动浏览器
+- 会话会保留创建时的会话级配置,浏览器会话包括 headless、locale、cookies、隐身功能开关等,HTTP 请求会话包括 `impersonate` 和 `proxy`。每次调用时,通过 `browser_fetch`/`session_make_request` 传入请求级选项,如 timeout、wait_selector、network_idle、solve_cloudflare 等;默认值见工具的 schema
+- `browser_fetch` 可以通过已打开的隐身浏览器会话处理 Cloudflare 验证
+- 使用完毕后,务必调用 `close_session` 关闭会话并释放资源
+- 使用 `list_sessions` 查看仍在运行的会话,以及各会话创建时使用的 `settings`(返回给 AI 智能体;CDP 会话中为空)
+- 调用创建会话的工具时,可以传入自定义 `session_id`,用有意义的名称(如 `"search"`、`"checkout"`)代替默认的随机十六进制值。如果所选 ID 已被使用,工具会抛出异常,便于及时发现冲突
+
+### 7. 截图 {#7-capturing-screenshots}
+
+- `browser_screenshot` 会截取通过 `browser_fetch` 在隐身浏览器会话中打开的页面。它不会重新加载页面,因此 AI 可以查看已填写的字段、已展开的菜单,以及其他操作的结果。
+- 图片会以真正的 `ImageContent` 块返回,让模型直接查看页面。
+- 可以截取可见视口,也可以截取整个页面,包括需要向下滚动才能看到的内容。
+- 可以只截取某个字段、图表、卡片或结果,减少周围内容的干扰。截取元素时,可以将目标滚动到可见区域。
+- 需要无损图片时选择 PNG;需要减少数据量时选择 JPEG,并调整画质。
+- 截图前,AI 可以使用 `browser_actions` 等待内容加载或完成交互。
+
+## 法律和道德事项 {#legal-and-ethical-considerations}
+
+⚠️ **重要准则:**
+
+- **检查 robots.txt**:访问 `https://website.com/robots.txt`,查看抓取规则
+- **遵守请求频率限制**:不要用大量请求使服务器过载
+- **服务条款**:阅读并遵守网站条款
+- **版权**:尊重知识产权
+- **隐私**:注意个人数据保护相关法律
+- **商业用途**:确认已取得商业使用所需的许可
+
+---
+
+*由 Scrapling 团队用 ❤️ 打造。祝抓取顺利!*
diff --git a/docs/locales/zh/api-reference/custom-types.md b/docs/locales/zh/api-reference/custom-types.md
new file mode 100644
index 0000000..2882fe0
--- /dev/null
+++ b/docs/locales/zh/api-reference/custom-types.md
@@ -0,0 +1,26 @@
+---
+title: "TextHandler 和 AttributesHandler API 参考"
+description: "查看 Scrapling 的文本、文本列表和属性工具:正则表达式、JSON 转换和值搜索。"
+---
+
+# 自定义类型参考 {#custom-types-api-reference}
+
+这里列出了 Scrapling 自定义类型的参数、属性和方法。
+
+可以直接导入:
+
+```python
+from scrapling.core.custom_types import TextHandler, TextHandlers, AttributesHandler
+```
+
+## ::: scrapling.core.custom_types.TextHandler
+ handler: python
+ :docstring:
+
+## ::: scrapling.core.custom_types.TextHandlers
+ handler: python
+ :docstring:
+
+## ::: scrapling.core.custom_types.AttributesHandler
+ handler: python
+ :docstring:
diff --git a/docs/locales/zh/api-reference/fetchers.md b/docs/locales/zh/api-reference/fetchers.md
new file mode 100644
index 0000000..ff7e396
--- /dev/null
+++ b/docs/locales/zh/api-reference/fetchers.md
@@ -0,0 +1,48 @@
+---
+title: "HTTP 和浏览器 Fetcher API 参考"
+description: "查看 Fetcher、AsyncFetcher、StealthyFetcher 和会话的 API,包括请求选项、浏览器设置和返回类型。"
+---
+
+# Fetcher 类 {#fetchers-classes}
+
+这里列出了所有 Fetcher 类的参数、属性和方法。
+
+可以直接导入:
+
+```python
+from scrapling.fetchers import (
+ Fetcher, AsyncFetcher, StealthyFetcher,
+ FetcherSession, AsyncStealthySession, StealthySession
+)
+```
+
+## ::: scrapling.fetchers.Fetcher
+ handler: python
+ :docstring:
+
+## ::: scrapling.fetchers.AsyncFetcher
+ handler: python
+ :docstring:
+
+## ::: scrapling.fetchers.StealthyFetcher
+ handler: python
+ :docstring:
+
+
+## 会话类 {#session-classes}
+
+### HTTP 会话 {#http-sessions}
+
+## ::: scrapling.fetchers.FetcherSession
+ handler: python
+ :docstring:
+
+### 隐身浏览器会话 {#stealth-sessions}
+
+## ::: scrapling.fetchers.StealthySession
+ handler: python
+ :docstring:
+
+## ::: scrapling.fetchers.AsyncStealthySession
+ handler: python
+ :docstring:
diff --git a/docs/locales/zh/api-reference/mcp-server.md b/docs/locales/zh/api-reference/mcp-server.md
new file mode 100644
index 0000000..74d2bc2
--- /dev/null
+++ b/docs/locales/zh/api-reference/mcp-server.md
@@ -0,0 +1,96 @@
+---
+title: "Scrapling MCP 服务器 API 参考"
+description: "查看 MCP 服务器工具及其请求、响应和会话模型,用于通过 HTTP 和浏览器提取数据。"
+---
+
+# MCP 服务器参考 {#mcp-server-api-reference}
+
+**Scrapling MCP 服务器**通过 Model Context Protocol(MCP)提供十六个数据提取和浏览器操作工具。将 Scrapling 接入 AI 助手和智能体,就能通过对话提取数据,并使用反检测功能。
+
+用下面的命令启动 MCP 服务器:
+
+```bash
+scrapling mcp
+```
+
+也可以直接导入服务器类:
+
+```python
+from scrapling.core.ai import ScraplingMCPServer
+
+server = ScraplingMCPServer()
+server.serve(http=False, host="127.0.0.1", port=8000)
+```
+
+要使用自己的 Chromium 兼容浏览器程序,请传入 `executable_path`:
+
+```python
+server = ScraplingMCPServer(executable_path="/path/to/chromium")
+```
+
+## 响应模型 {#response-model}
+
+页面获取和 HTTP 请求工具返回以下结构,每次调用返回一个响应。会话管理工具使用后面的模型。`browser_screenshot` 将页面或元素的截图和当前 URL 作为图像块和文本块返回。`browser_extract` 和 `browser_actions` 返回纯文本。两个网络工具通过后面的模型返回结构化 JSON。`browser_evaluate` 将结果转为 JSON,放在文本块中返回。
+
+## ::: scrapling.core.ai.server.ResponseModel
+ handler: python
+ :docstring:
+
+## 网络请求模型 {#network-request-models}
+
+`browser_network_requests` 返回 `NetworkRequestsModel`,包含 `requests`、`next_cursor`、`has_more` 和 `dropped_count`。每个 `NetworkRequestInfo` 包含 `id`、`url`、`method`、`resource_type` 和 `status`。要读取下一页,将 `next_cursor` 作为 `after_id` 传入。`has_more` 表示当前历史记录中是否还有匹配结果。
+
+`browser_network_request` 返回 `NetworkRequestModel`,包含 `request_id`、`part`、`data` 和 `note`。摘要和请求头或响应头是对象。完整保存的内容以字符串返回,即使响应内容是 JSON 也是如此。`note` 说明内容是否缺失,或头部信息是否不完整。
+
+## ::: scrapling.core.ai._network_formatting.NetworkRequestInfo
+ handler: python
+ :docstring:
+
+## ::: scrapling.core.ai.server.NetworkRequestsModel
+ handler: python
+ :docstring:
+
+## ::: scrapling.core.ai._network_formatting.NetworkRequestModel
+ handler: python
+ :docstring:
+
+## 会话模型 {#session-models}
+
+用于会话管理的模型类:
+
+## ::: scrapling.core.ai.server.SessionInfo
+ handler: python
+ :docstring:
+
+## ::: scrapling.core.ai.server.SessionCreatedModel
+ handler: python
+ :docstring:
+
+## ::: scrapling.core.ai.server.SessionClosedModel
+ handler: python
+ :docstring:
+
+## MCP 服务器类 {#mcp-server-class}
+
+MCP 服务器的主类提供以下工具:
+
+- **`make_request`**:通过 HTTP 获取一个 URL,模拟浏览器,并自动关闭客户端。支持 GET、POST、PUT 和 DELETE。
+- **`browser_fetch_once`**:用隐身浏览器获取一个 URL,执行 JavaScript、处理 Cloudflare 验证,然后关闭浏览器。如果之后还要操作页面或查看网络历史记录,请使用持久会话。
+
+- **`browser_extract`**:读取当前页面或元素,输出适合 AI 的结构化视图、HTML、Markdown 或文本,无需重新加载。表单和操作结果会保留。结构化视图包含元素的角色、名称、引用、位置和尺寸。正则表达式搜索返回匹配行、附近内容和父节点。
+- **`browser_actions`**:在一次调用中组合鼠标移动、悬停、点击、滚动、填写表单、快捷键、对话框响应和等待。可以接受或关闭提示和确认框,也可以在输入对话框中填写内容。例如,填写搜索框、提交、等待并打开结果,无需每一步都调用一次工具。
+
+ 移动和点击支持选择器、结构化视图中的引用或坐标。工具会等待元素出现,并将其滚动到可见区域。支持分步移动、鼠标左键、右键和中键点击、双击,以及嵌套区域内的滚动。
+
+ 用选择器或结构化视图中的引用选择表单字段。可以输入文字、勾选或取消勾选复选框、选择单选按钮,以及按标签选择原生下拉框中的一个或多个选项。可以替换或清空文字,也可以从光标处继续输入。快捷键作用于当前焦点。慢速模式会在字符和操作之间加入随机停顿。
+
+ 用选择器或结构化视图中的引用等待内容或加载遮罩达到所需状态。也可以等待页面加载事件、网络空闲或指定时长。
+
+- **`browser_evaluate`**:在当前页面执行 JavaScript,用于自定义数据提取、计算、读取应用状态或修改内容。支持异步脚本,并返回 JSON 结果。
+- **`browser_network_requests`**:搜索跨标签页、页面跳转和操作的已完成浏览器请求。查找保存的 API 请求、HTTP 错误和重定向。默认隐藏静态资源,减少无关结果。失败或未完成的请求会被跳过。返回可分页的结构化数据。
+- **`browser_network_request`**:以结构化 JSON 读取已保存请求的摘要、头部信息、发送的数据或文本内容,无需再次发送请求。所选部分会完整返回。页面跳转后仍可读取已保存的响应,包括 4xx 和 5xx HTTP 响应。记录完成后才会出现在历史中。读取历史或关闭会话不会等待尚未完成的记录,它们可能在页面跳转或关闭时丢失。字节数据来自 Playwright,可能与服务器发送的原始字节不同。保存的字节是有效 UTF-8 时,使用该编码解码,与 Playwright 一致;否则使用声明的字符集。只读取和保存具有受支持的文本 `Content-Type` 的响应内容。二进制、缺失或未知类型只保留元数据和头部信息,不读取内容。这不会改变页面加载方式。历史记录有大小限制。可选的说明会指出内容不是文本、超过大小限制或无法读取等情况。请在关闭 MCP 会话前读取需要的数据。
+- **`browser_fetch`**:在已打开的隐身浏览器会话中获取页面,并提取 HTML、Markdown、文本或结构化视图。视图可以覆盖整页或单个元素,并包含供后续操作使用的引用、位置和尺寸。
+
+## ::: scrapling.core.ai.server.ScraplingMCPServer
+ handler: python
+ :docstring:
diff --git a/docs/locales/zh/api-reference/proxy-rotation.md b/docs/locales/zh/api-reference/proxy-rotation.md
new file mode 100644
index 0000000..b033152
--- /dev/null
+++ b/docs/locales/zh/api-reference/proxy-rotation.md
@@ -0,0 +1,18 @@
+---
+title: "ProxyRotator API 参考"
+description: "查看 ProxyRotator 的代理选择和轮换策略,用于 HTTP 和浏览器会话。"
+---
+
+# 代理轮换 {#proxy-rotation}
+
+`ProxyRotator` 可以在任何 Fetcher 和会话中切换代理,也能安全地供多个线程使用。
+
+可以直接导入这个类:
+
+```python
+from scrapling.fetchers import ProxyRotator
+```
+
+## ::: scrapling.engines.toolbelt.proxy_rotation.ProxyRotator
+ handler: python
+ :docstring:
diff --git a/docs/locales/zh/api-reference/response.md b/docs/locales/zh/api-reference/response.md
new file mode 100644
index 0000000..aa3c990
--- /dev/null
+++ b/docs/locales/zh/api-reference/response.md
@@ -0,0 +1,18 @@
+---
+title: "Response API 参考"
+description: "查看响应状态、响应头、内容、元数据、Markdown 转换和 follow 方法,并使用从 Selector 继承的方法提取数据。"
+---
+
+# Response 类 {#response-class}
+
+`Response` 类表示所有 Fetcher 返回的 HTTP 响应。它提供状态、响应头、内容和 Cookie,也通过继承 `Selector` 提供解析功能。
+
+导入 `Response` 类:
+
+```python
+from scrapling.engines.toolbelt.custom import Response
+```
+
+## ::: scrapling.engines.toolbelt.custom.Response
+ handler: python
+ :docstring:
diff --git a/docs/locales/zh/api-reference/selector.md b/docs/locales/zh/api-reference/selector.md
new file mode 100644
index 0000000..81ec09b
--- /dev/null
+++ b/docs/locales/zh/api-reference/selector.md
@@ -0,0 +1,24 @@
+---
+title: "Selector 和 Selectors API 参考"
+description: "查看 Selector 和 Selectors 的 HTML 解析、选择、提取、导航和自适应元素定位方法。"
+---
+
+# Selector 类 {#selector-class}
+
+`Selector` 是 Scrapling 中用于解析 HTML 和选择元素的核心类。
+
+这里列出了 `Selector` 的全部参数、属性和方法。
+
+可以直接从 `scrapling` 导入 `Selector`:
+
+```python
+from scrapling.parser import Selector
+```
+
+## ::: scrapling.parser.Selector
+ handler: python
+ :docstring:
+
+## ::: scrapling.parser.Selectors
+ handler: python
+ :docstring:
diff --git a/docs/locales/zh/api-reference/spiders.md b/docs/locales/zh/api-reference/spiders.md
new file mode 100644
index 0000000..ea8d1df
--- /dev/null
+++ b/docs/locales/zh/api-reference/spiders.md
@@ -0,0 +1,42 @@
+---
+title: "Spider、请求和结果 API 参考"
+description: "查看 Spider 钩子、请求、会话、爬取统计和导出方法。"
+---
+
+# Spider 类 {#spider-classes}
+
+这里列出了爬虫框架中各个类的参数、属性和方法。
+
+可以直接导入:
+
+```python
+from scrapling.spiders import Spider, Request, CrawlResult, SessionManager, Response
+```
+
+## ::: scrapling.spiders.Spider
+ handler: python
+ :docstring:
+
+## ::: scrapling.spiders.Request
+ handler: python
+ :docstring:
+
+## 结果类 {#result-classes}
+
+## ::: scrapling.spiders.result.CrawlResult
+ handler: python
+ :docstring:
+
+## ::: scrapling.spiders.result.CrawlStats
+ handler: python
+ :docstring:
+
+## ::: scrapling.spiders.result.ItemList
+ handler: python
+ :docstring:
+
+## 会话管理 {#session-management}
+
+## ::: scrapling.spiders.session.SessionManager
+ handler: python
+ :docstring:
diff --git a/docs/locales/zh/assets b/docs/locales/zh/assets
new file mode 120000
index 0000000..41aef43
--- /dev/null
+++ b/docs/locales/zh/assets
@@ -0,0 +1 @@
+../../assets
\ No newline at end of file
diff --git a/docs/locales/zh/benchmarks.md b/docs/locales/zh/benchmarks.md
new file mode 100644
index 0000000..555b2bf
--- /dev/null
+++ b/docs/locales/zh/benchmarks.md
@@ -0,0 +1,33 @@
+---
+title: "HTML 解析器性能测试:Scrapling 与其他库"
+description: "对比 Scrapling 和其他 Python 库在 HTML 解析、文本提取和相似元素搜索中的性能。"
+---
+
+# 性能测试 {#performance-benchmarks}
+
+Scrapling 的速度也很出色。下面对比它的解析器和其他常用库。
+
+### 文本提取速度(5,000 个嵌套元素) {#text-extraction-speed-test-5000-nested-elements}
+
+| # | 库 | 时间(毫秒) | 相对 Scrapling |
+|---|:-----------------:|:---------:|:------------:|
+| 1 | Scrapling | 1.99 | 1.0x |
+| 2 | Parsel/Scrapy | 2.06 | 1.035 |
+| 3 | 原生 Lxml | 2.56 | 1.286 |
+| 4 | PyQuery | 23.98 | ~12x |
+| 5 | Selectolax | 197.02 | ~99x |
+| 6 | MechanicalSoup | 1545.15 | ~776.5x |
+| 7 | BS4 + Lxml | 1562.1 | ~785.0x |
+| 8 | BS4 + html5lib | 3412.73 | ~1714.9x |
+
+
+### 相似元素和文本搜索 {#element-similarity-text-search-performance}
+
+Scrapling 的自适应元素查找比其他方案更快:
+
+| 库 | 时间(毫秒) | 相对 Scrapling |
+|-------------|:---------:|:------------:|
+| Scrapling | 2.3 | 1.0x |
+| AutoScraper | 12.58 | 5.47x |
+
+> 每项结果都是 100 次测量的平均值。测试方法见 [benchmarks.py](https://github.com/D4Vinci/Scrapling/blob/main/benchmarks.py)。
diff --git a/docs/locales/zh/cli/extract-commands.md b/docs/locales/zh/cli/extract-commands.md
new file mode 100644
index 0000000..32aca52
--- /dev/null
+++ b/docs/locales/zh/cli/extract-commands.md
@@ -0,0 +1,325 @@
+---
+title: "通过 CLI 将网页保存为 Markdown、HTML 或文本"
+description: "使用 scrapling extract 保存 HTTP 请求或浏览器获取的结果。用 CSS 筛选内容,设置请求选项,并选择输出格式。"
+---
+
+# Scrapling 提取命令指南 {#scrapling-extract-command-guide}
+
+**无需编程,直接在终端中抓取网页!**
+
+`scrapling extract` 命令可以直接在终端中下载和提取网站内容,无需编写代码。它适合初学者、研究人员,以及需要快速获取网页数据的人。
+
+!!! success "前置知识"
+
+ 1. 阅读 [Fetcher 基础](../fetching/choosing.md),了解 [Response 对象](../fetching/choosing.md#response-object)并选择合适的 Fetcher。
+ 2. 阅读[元素查询](../parsing/selection.md),学习如何从 [Selector](../parsing/main_classes.md#selector)/[Response](../fetching/choosing.md#response-object) 对象中查找和提取元素。
+ 3. 阅读[主要类](../parsing/main_classes.md),了解 [Response](../fetching/choosing.md#response-object) 从 [Selector](../parsing/main_classes.md#selector) 继承了哪些属性和方法。
+ 4. 至少阅读 Fetcher 部分的一篇相关指南:[HTTP 请求](../fetching/static.md)或[通过浏览器获取页面](../fetching/stealthy.md)。
+
+## Extract 命令组是什么? {#what-is-the-extract-command-group}
+
+这是一组简单的终端工具,可以:
+
+- **下载网页**,并将内容保存到文件。
+- **将 HTML 转为易读的格式**,例如 Markdown,也可以保留 HTML 或只提取页面文本。
+- **使用自定义 CSS 选择器**,提取页面的特定部分。
+- **发送 HTTP 请求或通过浏览器获取页面**。
+- **调整几乎所有选项**,包括请求头、Cookie 和代理。代码中可用的大部分选项也能在命令行中使用。
+
+!!! tip "面向 AI 的模式"
+
+ 所有提取命令都支持 `--ai-targeted` 选项。启用后,只提取页面正文中的主要内容,并移除无用标签(script、style、noscript、svg)、可能用于提示词注入的隐藏元素(通过内联样式隐藏的元素、aria-hidden、隐藏的 slot 和 template 标签)、Unicode 零宽字符和 HTML 注释。对于浏览器命令(`fetch`),它还会自动启用广告拦截。输出要交给 AI 模型时,适合使用此模式。
+
+## 快速开始 {#quick-start}
+
+- **下载网页**
+
+ 将网页内容下载为干净、易读的文本:
+ ```bash
+ scrapling extract get "https://example.com" page_content.txt
+ ```
+ 该命令发送 HTTP GET 请求,并把页面文本保存到 `page_content.txt`。
+
+- **保存为其他格式**
+
+ 修改文件扩展名即可选择输出格式:
+ ```bash
+ # Convert the HTML content to Markdown, then save it to the file (great for documentation)
+ scrapling extract get "https://blog.example.com" article.md
+
+ # Save the HTML content as it is to the file
+ scrapling extract get "https://example.com" page.html
+
+ # Save a clean version of the text content of the webpage to the file
+ scrapling extract get "https://example.com" content.txt
+
+ # Or use the Docker image with something like this:
+ docker run -v $(pwd)/output:/output pyd4vinci/scrapling extract get "https://blog.example.com" /output/article.md
+ ```
+
+- **提取指定内容**
+
+ 所有命令都可以通过 `--css-selector` 或 `-s` 使用 CSS 选择器,提取页面的特定部分。下面的示例会展示用法。
+
+## 可用命令 {#available-commands}
+
+运行 `scrapling extract --help`,即可看到以下命令列表:
+```bash
+Usage: scrapling extract [OPTIONS] COMMAND [ARGS]...
+
+ Fetch web pages using various fetchers and extract full/selected HTML content as HTML, Markdown, or extract text content.
+
+Options:
+ --help Show this message and exit.
+
+Commands:
+ get Perform a GET request and save the content to a file.
+ post Perform a POST request and save the content to a file.
+ put Perform a PUT request and save the content to a file.
+ delete Perform a DELETE request and save the content to a file.
+ fetch Use StealthyFetcher to fetch content with advanced stealth features.
+```
+
+下面逐一介绍。
+
+### HTTP 请求 {#http-requests}
+
+1. **GET 请求**
+
+ 最常用的网页内容下载命令:
+
+ ```bash
+ scrapling extract get [URL] [OUTPUT_FILE] [OPTIONS]
+ ```
+
+ **示例:**
+ ```bash
+ # Basic download
+ scrapling extract get "https://news.site.com" news.md
+
+ # Download with custom timeout
+ scrapling extract get "https://example.com" content.txt --timeout 60
+
+ # Extract only specific content using CSS selectors
+ scrapling extract get "https://blog.example.com" articles.md --css-selector "article"
+
+ # Send a request with cookies
+ scrapling extract get "https://scrapling.requestcatcher.com" content.md --cookies "session=abc123; user=john"
+
+ # Add user agent
+ scrapling extract get "https://api.site.com" data.txt -H "User-Agent: MyBot 1.0"
+
+ # Add multiple headers
+ scrapling extract get "https://site.com" page.html -H "Accept: text/html" -H "Accept-Language: en-US"
+ ```
+ 用 `scrapling extract get --help` 查看可用选项:
+ ```bash
+ Usage: scrapling extract get [OPTIONS] URL OUTPUT_FILE
+
+ Perform a GET request and save the content to a file.
+
+ The output file path can be an HTML file, a Markdown file of the HTML content, or the text content itself. Use file extensions (`.html`/`.md`/`.txt`) respectively.
+
+ Options:
+ -H, --headers TEXT HTTP headers in format "Key: Value" (can be used multiple times)
+ --cookies TEXT Cookies string in format "name1=value1;name2=value2"
+ --timeout INTEGER Request timeout in seconds (default: 30)
+ --proxy TEXT Proxy URL in format "http://username:password@host:port"
+ -s, --css-selector TEXT CSS selector to extract specific content from the page. It returns all matches.
+ -p, --params TEXT Query parameters in format "key=value" (can be used multiple times)
+ --follow-redirects / --no-follow-redirects Whether to follow redirects (default: True)
+ --verify / --no-verify Whether to verify SSL certificates (default: True)
+ --impersonate TEXT Browser to impersonate (e.g., chrome, firefox).
+ --stealthy-headers / --no-stealthy-headers Use stealthy browser headers (default: True)
+ --ai-targeted Extract only main content and sanitize hidden elements for AI consumption (default: False)
+ --help Show this message and exit.
+
+ ```
+ 这些选项在其他请求命令中的用法相同,因此不再重复说明。
+
+2. **POST 请求**
+
+ ```bash
+ scrapling extract post [URL] [OUTPUT_FILE] [OPTIONS]
+ ```
+
+ **示例:**
+ ```bash
+ # Submit form data
+ scrapling extract post "https://api.site.com/search" results.html --data "query=python&type=tutorial"
+
+ # Send JSON data
+ scrapling extract post "https://api.site.com" response.txt --json '{"username": "test", "action": "search"}'
+ ```
+ 用 `scrapling extract post --help` 查看可用选项:
+ ```bash
+ Usage: scrapling extract post [OPTIONS] URL OUTPUT_FILE
+
+ Perform a POST request and save the content to a file.
+
+ The output file path can be an HTML file, a Markdown file of the HTML content, or the text content itself. Use file extensions (`.html`/`.md`/`.txt`) respectively.
+
+ Options:
+ -d, --data TEXT Form data to include in the request body (as string, ex: "param1=value1&param2=value2")
+ -j, --json TEXT JSON data to include in the request body (as string)
+ -H, --headers TEXT HTTP headers in format "Key: Value" (can be used multiple times)
+ --cookies TEXT Cookies string in format "name1=value1;name2=value2"
+ --timeout INTEGER Request timeout in seconds (default: 30)
+ --proxy TEXT Proxy URL in format "http://username:password@host:port"
+ -s, --css-selector TEXT CSS selector to extract specific content from the page. It returns all matches.
+ -p, --params TEXT Query parameters in format "key=value" (can be used multiple times)
+ --follow-redirects / --no-follow-redirects Whether to follow redirects (default: True)
+ --verify / --no-verify Whether to verify SSL certificates (default: True)
+ --impersonate TEXT Browser to impersonate (e.g., chrome, firefox).
+ --stealthy-headers / --no-stealthy-headers Use stealthy browser headers (default: True)
+ --ai-targeted Extract only main content and sanitize hidden elements for AI consumption (default: False)
+ --help Show this message and exit.
+
+ ```
+
+3. **PUT 请求**
+
+ ```bash
+ scrapling extract put [URL] [OUTPUT_FILE] [OPTIONS]
+ ```
+
+ **示例:**
+ ```bash
+ # Send data
+ scrapling extract put "https://scrapling.requestcatcher.com/put" results.html --data "update=info" --impersonate "firefox"
+
+ # Send JSON data
+ scrapling extract put "https://scrapling.requestcatcher.com/put" response.txt --json '{"username": "test", "action": "search"}'
+ ```
+ 用 `scrapling extract put --help` 查看可用选项:
+ ```bash
+ Usage: scrapling extract put [OPTIONS] URL OUTPUT_FILE
+
+ Perform a PUT request and save the content to a file.
+
+ The output file path can be an HTML file, a Markdown file of the HTML content, or the text content itself. Use file extensions (`.html`/`.md`/`.txt`) respectively.
+
+ Options:
+ -d, --data TEXT Form data to include in the request body
+ -j, --json TEXT JSON data to include in the request body (as string)
+ -H, --headers TEXT HTTP headers in format "Key: Value" (can be used multiple times)
+ --cookies TEXT Cookies string in format "name1=value1;name2=value2"
+ --timeout INTEGER Request timeout in seconds (default: 30)
+ --proxy TEXT Proxy URL in format "http://username:password@host:port"
+ -s, --css-selector TEXT CSS selector to extract specific content from the page. It returns all matches.
+ -p, --params TEXT Query parameters in format "key=value" (can be used multiple times)
+ --follow-redirects / --no-follow-redirects Whether to follow redirects (default: True)
+ --verify / --no-verify Whether to verify SSL certificates (default: True)
+ --impersonate TEXT Browser to impersonate (e.g., chrome, firefox).
+ --stealthy-headers / --no-stealthy-headers Use stealthy browser headers (default: True)
+ --ai-targeted Extract only main content and sanitize hidden elements for AI consumption (default: False)
+ --help Show this message and exit.
+ ```
+
+4. **DELETE 请求**
+
+ ```bash
+ scrapling extract delete [URL] [OUTPUT_FILE] [OPTIONS]
+ ```
+
+ **示例:**
+ ```bash
+ # Send data
+ scrapling extract delete "https://scrapling.requestcatcher.com/delete" results.html
+
+ # Send JSON data
+ scrapling extract delete "https://scrapling.requestcatcher.com/" response.txt --impersonate "chrome"
+ ```
+ 用 `scrapling extract delete --help` 查看可用选项:
+ ```bash
+ Usage: scrapling extract delete [OPTIONS] URL OUTPUT_FILE
+
+ Perform a DELETE request and save the content to a file.
+
+ The output file path can be an HTML file, a Markdown file of the HTML content, or the text content itself. Use file extensions (`.html`/`.md`/`.txt`) respectively.
+
+ Options:
+ -H, --headers TEXT HTTP headers in format "Key: Value" (can be used multiple times)
+ --cookies TEXT Cookies string in format "name1=value1;name2=value2"
+ --timeout INTEGER Request timeout in seconds (default: 30)
+ --proxy TEXT Proxy URL in format "http://username:password@host:port"
+ -s, --css-selector TEXT CSS selector to extract specific content from the page. It returns all matches.
+ -p, --params TEXT Query parameters in format "key=value" (can be used multiple times)
+ --follow-redirects / --no-follow-redirects Whether to follow redirects (default: True)
+ --verify / --no-verify Whether to verify SSL certificates (default: True)
+ --impersonate TEXT Browser to impersonate (e.g., chrome, firefox).
+ --stealthy-headers / --no-stealthy-headers Use stealthy browser headers (default: True)
+ --ai-targeted Extract only main content and sanitize hidden elements for AI consumption (default: False)
+ --help Show this message and exit.
+ ```
+
+### 通过浏览器获取页面 {#browser-fetching}
+
+对于 JavaScript 页面、浏览器自动化和受保护的网站,使用 `fetch`。它调用 `StealthyFetcher`,并支持全部隐身选项。
+
+```bash
+scrapling extract fetch "https://scrapling.requestcatcher.com/" content.md --network-idle
+scrapling extract fetch "https://scrapling.requestcatcher.com/" data.txt --wait-selector ".content-loaded"
+scrapling extract fetch "https://scrapling.requestcatcher.com/" page.html --no-headless --disable-resources
+scrapling extract fetch "https://nopecha.com/demo/cloudflare" data.txt --solve-cloudflare --css-selector "#padded_content a"
+scrapling extract fetch "https://site.com" content.md --proxy "http://proxy-server:8080"
+```
+
+使用 `--pierce-shadow` 可以包含开放 Shadow DOM 中的内容。该选项默认关闭,也可以用 `--no-pierce-shadow` 明确关闭。选择器示例和限制请参阅 [Shadow DOM](../fetching/stealthy.md#shadow-dom)。
+
+```bash
+scrapling extract fetch "https://example.com" content.md --pierce-shadow
+```
+
+运行 `scrapling extract fetch --help` 查看全部选项:
+
+```text
+Usage: scrapling extract fetch [OPTIONS] URL OUTPUT_FILE
+
+ Use StealthyFetcher to fetch content with advanced stealth features.
+
+Options:
+ --headless / --no-headless Run browser in headless mode (default: True)
+ --disable-resources / --enable-resources Drop unnecessary resources for speed boost (default: False)
+ --block-webrtc / --allow-webrtc Block WebRTC entirely (default: False)
+ --solve-cloudflare / --no-solve-cloudflare Solve Cloudflare challenges (default: False)
+ --allow-webgl / --block-webgl Allow WebGL (default: True)
+ --pierce-shadow / --no-pierce-shadow Include open Shadow DOM content (default: False)
+ --network-idle / --no-network-idle Wait for network idle (default: False)
+ --real-chrome/--no-real-chrome If you have a Chrome browser installed on your device, enable this, and the Fetcher will launch an instance of your browser and use it. (default: False)
+ --timeout INTEGER Timeout in milliseconds (default: 30000)
+ --wait INTEGER Additional wait time in milliseconds after page load (default: 0)
+ -s, --css-selector TEXT CSS selector to extract specific content from the page. It returns all matches.
+ --wait-selector TEXT CSS selector to wait for before proceeding
+ --hide-canvas / --show-canvas Add noise to canvas operations (default: False)
+ --locale TEXT Specify user locale. Defaults to the system default locale.
+ --proxy TEXT Proxy URL in format "http://username:password@host:port"
+ -H, --extra-headers TEXT Extra headers in format "Key: Value" (can be used multiple times)
+ --dns-over-https / --no-dns-over-https Route DNS through Cloudflare's DoH to prevent DNS leaks when using proxies (default: False)
+ --block-ads / --no-block-ads Block requests to known ad and tracker domains (default: False)
+ --executable-path TEXT Path to a custom Chromium-compatible browser executable. Falls back to the SCRAPLING_EXECUTABLE_PATH environment variable when not set.
+ --ai-targeted Extract only main content and sanitize hidden elements for AI consumption (default: False)
+ --help Show this message and exit.
+```
+
+## 何时使用各个命令 {#when-to-use-each-command}
+
+如果刚接触网页抓取,可以按以下规则选择:
+
+- 简单网站、博客或新闻文章,使用 **`get`**。
+- JavaScript 页面、浏览器自动化或受保护的网站(包括 Cloudflare),使用 **`fetch`**。
+
+## 法律与伦理 {#legal-and-ethical-considerations}
+
+⚠️ **重要原则:**
+
+- **检查 robots.txt**:访问 `https://website.com/robots.txt`,查看爬取规则。
+- **遵守请求频率限制**:不要用大量请求压垮服务器。
+- **服务条款**:阅读并遵守网站条款。
+- **版权**:尊重知识产权。
+- **隐私**:遵守个人数据保护法律。
+- **商业用途**:确保已获得商业使用许可。
+
+---
+
+*祝抓取顺利!请始终遵守网站规则以及适用的法律法规。*
diff --git a/docs/locales/zh/cli/interactive-shell.md b/docs/locales/zh/cli/interactive-shell.md
new file mode 100644
index 0000000..85e8334
--- /dev/null
+++ b/docs/locales/zh/cli/interactive-shell.md
@@ -0,0 +1,236 @@
+---
+title: "在 Scrapling 交互式 Shell 中测试网页抓取"
+description: "在 IPython Shell 中获取页面、尝试选择器并检查结果。转换 curl 命令、复用最近的响应,并测试抓取代码。"
+---
+
+# Scrapling 交互式 Shell 指南 {#scrapling-interactive-shell-guide}
+
+<script src="https://asciinema.org/a/736339.js" id="asciicast-736339" async data-autoplay="1" data-loop="1" data-cols="225" data-rows="40" data-start-at="00:06" data-speed="1.5" data-theme="tango"></script>
+
+**面向开发者和数据科学家的网页抓取 REPL**
+
+Scrapling 交互式 Shell 是基于 IPython 的增强环境,专为网页抓取设计。它提供全部 Scrapling 功能、实用快捷方式、自动页面管理,以及 curl 命令转换等工具。
+
+!!! success "前置知识"
+
+ 1. 阅读 [Fetcher 基础](../fetching/choosing.md),了解 [Response 对象](../fetching/choosing.md#response-object)并选择合适的 Fetcher。
+ 2. 阅读[元素查询](../parsing/selection.md),学习如何从 [Selector](../parsing/main_classes.md#selector)/[Response](../fetching/choosing.md#response-object) 对象中查找和提取元素。
+ 3. 阅读[主要类](../parsing/main_classes.md),了解 [Response](../fetching/choosing.md#response-object) 从 [Selector](../parsing/main_classes.md#selector) 继承了哪些属性和方法。
+ 4. 至少阅读 Fetcher 部分的一篇相关指南:[HTTP 请求](../fetching/static.md)或[通过浏览器获取页面](../fetching/stealthy.md)。
+
+## 为什么使用交互式 Shell? {#why-use-the-interactive-shell}
+
+交互式 Shell 可以即时探索和测试,不必每次修改脚本后再重新运行。它适合:
+
+- **快速验证想法**:立即测试抓取方案。
+- **探索数据**:以交互方式浏览网站并提取数据。
+- **学习 Scrapling**:实时尝试各项功能。
+- **调试抓取代码**:逐步执行请求并检查结果。
+- **转换命令**:用一行代码将浏览器开发者工具中的 curl 命令转为 Fetcher 请求。
+
+## 开始使用 {#getting-started}
+
+### 启动 Shell {#launch-the-shell}
+
+```bash
+# Start the interactive shell
+scrapling shell
+
+# Execute code and exit (useful for scripting)
+scrapling shell -c "get('https://quotes.toscrape.com'); print(len(page.css('.quote')))"
+
+# Set logging level
+scrapling shell --loglevel info
+```
+
+启动后会显示 Scrapling 横幅,随后就可以开始抓取,如上面的视频所示:
+
+```python
+# No imports needed - everything is ready!
+get('https://news.ycombinator.com')
+
+# Explore the page structure
+page.css('a')[:5] # Look at first 5 links
+
+# Refine your selectors
+stories = page.css('.titleline>a')
+len(stories) # 30
+
+# Extract specific data
+for story in stories[:3]:
+ title = story.text
+ url = story['href']
+ print(f"{title}: {url}")
+
+# Try different approaches
+titles = page.css('.titleline>a::text') # Direct text extraction
+urls = page.css('.titleline>a::attr(href)') # Direct attribute extraction
+```
+
+## 内置快捷方式 {#built-in-shortcuts}
+
+Shell 提供这些快捷方式,减少重复代码:
+
+- **`get(url, **kwargs)`**:HTTP GET 请求,代替 `Fetcher.get`。
+- **`post(url, **kwargs)`**:HTTP POST 请求,代替 `Fetcher.post`。
+- **`put(url, **kwargs)`**:HTTP PUT 请求,代替 `Fetcher.put`。
+- **`delete(url, **kwargs)`**:HTTP DELETE 请求,代替 `Fetcher.delete`。
+- **`fetch(url, **kwargs)`**:通过隐身浏览器获取页面,代替 `StealthyFetcher.fetch`。
+
+常用类无需导入即可使用,包括 `Fetcher`、`AsyncFetcher`、`StealthyFetcher` 和 `Selector`。
+
+### 自动管理页面 {#smart-page-management}
+
+Shell 会自动记录请求和页面:
+
+- **访问当前页面**
+
+ `page` 和 `response` 会自动更新为最近获取的页面:
+
+ ```python
+ get('https://quotes.toscrape.com')
+ # 'page' and 'response' both refer to the last fetched page
+ page.url # 'https://quotes.toscrape.com'
+ response.status # Prints 200; Same as page.status
+ ```
+
+- **页面历史**
+
+ `pages` 用一个 `Selectors` 对象保留最近五个页面:
+
+ ```python
+ get('https://site1.com')
+ get('https://site2.com')
+ get('https://site3.com')
+
+ # Access last 5 pages
+ len(pages) # `Selectors` object with `page` history -> 3
+ pages[0].url # First page in history -> 'https://site1.com'
+ pages[-1].url # Most recent page -> 'https://site3.com'
+
+ # Work with historical pages
+ for i, old_page in enumerate(pages):
+ print(f"Page {i}: {old_page.url} - {old_page.status}")
+ ```
+
+## 其他实用命令 {#additional-helpful-commands}
+
+### 查看页面 {#page-visualization}
+
+在浏览器中查看获取的页面:
+
+```python
+get('https://quotes.toscrape.com')
+view(page) # Opens the page HTML in your default browser
+```
+
+### 转换 curl 命令 {#curl-command-integration}
+
+Shell 提供 `uncurl` 和 `curl2fetcher`,可以把浏览器开发者工具中的 curl 命令转换为 `Fetcher` 请求。
+
+先把一条请求复制为 curl 命令:
+
+<img src="../assets/scrapling_shell_curl.png" title="将 Chrome 中的请求复制为 curl 命令" alt="将 Chrome 中的请求复制为 curl 命令" style="width: 70%;"/>
+
+- **将 curl 命令转为请求对象**
+
+ ```python
+ curl_cmd = '''curl 'https://scrapling.requestcatcher.com/post' \
+ -X POST \
+ -H 'Content-Type: application/json' \
+ -d '{"name": "test", "value": 123}' '''
+
+ request = uncurl(curl_cmd)
+ request.method # -> 'post'
+ request.url # -> 'https://scrapling.requestcatcher.com/post'
+ request.headers # -> {'Content-Type': 'application/json'}
+ ```
+
+- **直接执行 curl 命令**
+
+ ```python
+ # Convert and execute in one step
+ curl2fetcher(curl_cmd)
+ page.status # -> 200
+ ```
+
+### IPython 功能 {#ipython-features}
+
+Shell 继承了 IPython 的全部功能:
+
+```python
+# Magic commands
+%time page = get('https://example.com') # Time execution
+%history # Show command history
+%save filename.py 1-10 # Save commands 1-10 to file
+
+# Tab completion works everywhere
+page.c<TAB> # Shows: css, cookies, headers, etc.
+Fetcher.<TAB> # Shows all Fetcher methods
+
+# Object inspection
+get? # Show get documentation
+```
+
+## 示例 {#examples}
+
+下面是几个由 AI 生成的示例:
+
+#### 采集电商数据 {#e-commerce-data-collection}
+
+```python
+# Start with product listing page
+catalog = get('https://shop.example.com/products')
+
+# Find product links
+product_links = catalog.css('.product-link::attr(href)').getall()
+print(f"Found {len(product_links)} products")
+
+# Sample a few products first
+for link in product_links[:3]:
+ product = get(catalog.urljoin(link))
+ name = product.css('.product-name::text').get('')
+ price = product.css('.price::text').get('')
+ print(f"{name}: {price}")
+
+# Scale up with sessions for efficiency
+from scrapling.fetchers import FetcherSession
+with FetcherSession() as session:
+ products = []
+ for link in product_links:
+ product = session.get(catalog.urljoin(link))
+ products.append({
+ 'name': product.css('.product-name::text').get(''),
+ 'price': product.css('.price::text').get(''),
+ 'url': link
+ })
+```
+
+#### API 集成与测试 {#api-integration-and-testing}
+
+```python
+>>> # Test API endpoints interactively
+>>> response = get('https://jsonplaceholder.typicode.com/posts/1')
+>>> response.json()
+{'userId': 1, 'id': 1, 'title': 'sunt aut...', 'body': 'quia et...'}
+
+>>> # Test POST requests
+>>> new_post = post('https://jsonplaceholder.typicode.com/posts',
+... json={'title': 'Test Post', 'body': 'Test content', 'userId': 1})
+>>> new_post.json()['id']
+101
+
+>>> # Test with different data
+>>> updated = put('https://jsonplaceholder.typicode.com/posts/1',
+... json={'title': 'Updated Title'})
+```
+
+## 获取帮助 {#getting-help}
+
+如果终端中的帮助还不够,可以查看:
+
+- [Scrapling 文档](https://scrapling.readthedocs.io/en/latest/zh/)
+- [Discord 社区](https://discord.gg/EMgGbDceNQ)
+- [GitHub Issues](https://github.com/D4Vinci/Scrapling/issues)
+
+就是这样!祝抓取顺利。Shell 让网页抓取像对话一样简单。
diff --git a/docs/locales/zh/cli/overview.md b/docs/locales/zh/cli/overview.md
new file mode 100644
index 0000000..f0c842f
--- /dev/null
+++ b/docs/locales/zh/cli/overview.md
@@ -0,0 +1,36 @@
+---
+title: "Scrapling CLI:在终端中抓取数据"
+description: "安装 Scrapling 终端工具,在提取命令、交互式 Shell 和 MCP 服务器之间选择,并按照对应指南完成任务。"
+---
+
+# 命令行界面 {#command-line-interface}
+
+从 v0.3 开始,Scrapling 提供命令行界面,包含三类主要功能:
+
+1. **交互式 Shell**:基于 IPython 的交互式网页抓取环境,提供多种快捷方式和实用工具。
+2. **提取命令**:无需编程,直接在终端中抓取网站。
+3. **实用命令**:安装和管理工具。
+
+```bash
+# Launch interactive shell
+scrapling shell
+
+# Convert the content of a page to markdown and save it to a file
+scrapling extract get "https://example.com" content.md
+
+# Get help for any command
+scrapling --help
+scrapling extract --help
+```
+
+## 环境要求 {#requirements}
+
+使用本节工具前,需要安装 `shell` 扩展依赖组:
+```bash
+pip install "scrapling[shell]"
+```
+如果要通过浏览器获取页面,还需要安装浏览器依赖:
+```bash
+scrapling install
+```
+该命令会下载 Chromium 及其系统依赖,并更新 TLD 列表。HTTP 请求不需要这一步。
diff --git a/docs/locales/zh/development/adaptive_storage_system.md b/docs/locales/zh/development/adaptive_storage_system.md
new file mode 100644
index 0000000..ed23dc5
--- /dev/null
+++ b/docs/locales/zh/development/adaptive_storage_system.md
@@ -0,0 +1,73 @@
+---
+title: "为自适应解析编写自定义存储后端"
+description: "为 Scrapling 自适应解析实现 save 和 retrieve。编写 Redis 存储后端,保存和读取元素属性。"
+---
+
+# 编写自己的存储系统 {#writing-your-retrieval-system}
+
+Scrapling 默认使用 SQLite。本教程介绍如何编写自己的存储系统,为 `adaptive` 功能保存元素属性。
+
+例如,可以使用 Firebase,让不同机器上的多个 Spider 共用一个数据库。使用这样的在线数据库,可以让 Spider 共享自适应数据。
+
+存储类首先需要满足三个要求:
+
+1. 继承抽象类 `scrapling.core.storage.StorageSystemMixin`,并接收字符串参数 `url`,以保持库的处理逻辑一致。
+2. 在类上使用 `functools.lru_cache` 装饰器,与其他类一样遵循单例设计模式。
+3. 按照类型提示实现 `save` 和 `retrieve` 方法:
+ - `save` 方法不返回值,会从库接收两个参数。
+ * 第一个参数是元素本身,类型为 `lxml.html.HtmlElement`。必须用子模块 `scrapling.core.utils._StorageTools` 中的 `element_to_dict` 函数将其转成字典,以保持格式一致,然后按需保存到数据库。
+ * 第二个参数是字符串,作为后续读取时使用的标识。它与初始化时传入的 `url` 组合后,必须对每行数据都唯一,否则 `adaptive` 数据会对应错误。
+ - `retrieve` 方法接收标识字符串,结合初始化时传入的 `url`,从数据库读取并返回元素的字典。如果不存在,则返回 `None`。
+
+> 如果这些步骤还不够清楚,可以查看 [storage_adaptors](https://github.com/D4Vinci/Scrapling/blob/main/scrapling/core/storage.py) 文件中我的 SQLite3 实现。
+
+只要类满足这些要求,后续就很简单。如果打算在多线程应用中使用本库,请确保自定义类支持多线程。默认使用的类是线程安全的。
+
+抽象类中也提供了一些可选的辅助函数。直接查看[代码](https://github.com/D4Vinci/Scrapling/blob/main/scrapling/core/storage.py)会更容易理解,其中有详细注释 :)
+
+
+## 实际示例:Redis 存储 {#real-world-example-redis-storage}
+
+下面是一个由 AI 生成的 Redis 实用示例:
+
+```python
+import redis
+import orjson
+from functools import lru_cache
+from scrapling.core.storage import StorageSystemMixin
+from scrapling.core.utils import _StorageTools
+
+@lru_cache(None)
+class RedisStorage(StorageSystemMixin):
+ def __init__(self, host='localhost', port=6379, db=0, url=None):
+ super().__init__(url)
+ self.redis = redis.Redis(
+ host=host,
+ port=port,
+ db=db,
+ decode_responses=False
+ )
+
+ def save(self, element, identifier: str) -> None:
+ # Convert element to dictionary
+ element_dict = _StorageTools.element_to_dict(element)
+
+ # Create key
+ key = f"scrapling:{self._get_base_url()}:{identifier}"
+
+ # Store as JSON
+ self.redis.set(
+ key,
+ orjson.dumps(element_dict)
+ )
+
+ def retrieve(self, identifier: str) -> dict | None:
+ # Get data
+ key = f"scrapling:{self._get_base_url()}:{identifier}"
+ data = self.redis.get(key)
+
+ # Parse JSON if exists
+ if data:
+ return orjson.loads(data)
+ return None
+```
diff --git a/docs/locales/zh/development/scrapling_custom_types.md b/docs/locales/zh/development/scrapling_custom_types.md
new file mode 100644
index 0000000..2a50930
--- /dev/null
+++ b/docs/locales/zh/development/scrapling_custom_types.md
@@ -0,0 +1,27 @@
+---
+title: "在自己的代码中使用 Scrapling 的文本和属性类型"
+description: "在解析器之外使用 TextHandler、TextHandlers 和 AttributesHandler。了解它们的 Python 基础类型、JSON 辅助方法和只读属性。"
+---
+
+# 使用 Scrapling 的自定义类型 {#using-scraplings-custom-types}
+
+> Scrapling 的自定义类型也可以在库外使用。毕竟,直接使用比复制代码更好 :)
+
+### 当前所有类型都可以单独导入 {#all-current-types-can-be-imported-alone-like-below}
+```python
+from scrapling.core.custom_types import TextHandler, AttributesHandler
+
+somestring = TextHandler('{}')
+parsed = somestring.json()
+somedict_1 = AttributesHandler({'a': 1})
+somedict_2 = AttributesHandler(a=1)
+```
+
+`TextHandler` 是 Python `str` 的子类,因此 Python 字符串支持的所有标准操作和方法都能使用。
+`parsed` 是字典 `{}`,不是字符串 `'{}'`。检查实例时使用 `isinstance(somestring, TextHandler)`,检查类时使用 `issubclass(TextHandler, str)`。
+
+`AttributesHandler` 是 `collections.abc.Mapping` 的子类,因此不可修改,也就是只读,并继承了它的操作。之后可以通过 `_data` 属性访问传入的数据,但它的类型是 `types.MappingProxyType`,同样是只读的,比 `collections.abc.Mapping` 快一点。
+
+如果刚接触 Python,可以这样理解:Python 标准 `dict` 类型的操作和方法,在 `AttributesHandler` 上也能使用,但修改数据的操作除外。
+
+如果要修改 `AttributesHandler` 中的数据,必须先将其转成字典,例如使用 `dict` 函数,然后在对象之外修改这个字典。
diff --git a/docs/locales/zh/donate.md b/docs/locales/zh/donate.md
new file mode 100644
index 0000000..8d55928
--- /dev/null
+++ b/docs/locales/zh/donate.md
@@ -0,0 +1,37 @@
+---
+title: "赞助 Scrapling,支持持续开发"
+description: "通过 GitHub Sponsors 或 Buy Me a Coffee 支持 Scrapling,也可以查看广告方案及其权益。"
+---
+
+# 赞助和广告 {#support-and-advertisement}
+
+我在业余时间开发这些项目,投入资金和精力,让社区可以免费使用。你的支持能帮我支付费用、承担日常责任、改进现有项目,并开发新项目,也能补充我的咖啡储备。
+
+可以通过 [GitHub Sponsors](https://github.com/sponsors/D4Vinci) 或 [Buy Me a Coffee](https://buymeacoffee.com/d4vinci) 支持我。
+
+谢谢支持!继续学习和探索。❤️
+
+## 广告 {#advertisement}
+如果想在社区中**推广**你的公司,可以查看[现有方案](https://github.com/sponsors/D4Vinci):
+
+### 1. [Silver 方案](https://github.com/sponsors/D4Vinci/sponsorships?tier_id=435495)(每月 100 美元) {#1-the-silver-tier-100month}
+权益:
+
+1. 你的标志展示在 [Scrapling 项目页顶部](https://github.com/D4Vinci/Scrapling?tab=readme-ov-file#sponsors)。
+2. 同一个标志也会展示在 [PyPI 项目页顶部](https://pypi.org/project/scrapling/)和 [Docker 镜像页](https://hub.docker.com/r/pyd4vinci/scrapling),与项目页一致。
+
+### 2. [Gold 方案](https://github.com/sponsors/D4Vinci/sponsorships?tier_id=591422)(每月 200 美元) {#2-the-gold-tier-200month}
+权益:
+
+1. 你的标志展示在 [Scrapling 项目页顶部](https://github.com/D4Vinci/Scrapling?tab=readme-ov-file#sponsors)。
+2. 同一个标志也会展示在 [PyPI 项目页顶部](https://pypi.org/project/scrapling/)和 [Docker 镜像页](https://hub.docker.com/r/pyd4vinci/scrapling),与项目页一致。
+3. 你的标志展示在 [Scrapling 网站](https://scrapling.readthedocs.io/en/latest/zh/)的主要赞助商区域。
+
+### 3. [Platinum 方案](https://github.com/sponsors/D4Vinci/sponsorships?tier_id=586646)(每月 300 美元) {#3-the-platinum-tier-300month}
+权益:
+
+1. 你的标志展示在 [Scrapling 项目页最上方](https://github.com/D4Vinci/Scrapling?tab=readme-ov-file#platinum-sponsors)的醒目位置,并附上最多 25 个单词的介绍。
+2. 同一个标志也会展示在 [PyPI 页面](https://pypi.org/project/scrapling/)和 [Docker 页面](https://hub.docker.com/r/pyd4vinci/scrapling),与项目页一致。
+3. 你的标志在 [Scrapling 网站](https://scrapling.readthedocs.io/en/latest/zh/)的主要赞助商区域获得醒目展示。
+4. 获得 Discord 社区的合作伙伴身份,并在 Twitter 和 Discord 上发布合作公告。
+5. 在每次版本发布说明的末尾获得鸣谢。
\ No newline at end of file
diff --git a/docs/locales/zh/fetching/choosing.md b/docs/locales/zh/fetching/choosing.md
new file mode 100644
index 0000000..83294ea
--- /dev/null
+++ b/docs/locales/zh/fetching/choosing.md
@@ -0,0 +1,95 @@
+---
+title: "为网页抓取选择 HTTP 请求或浏览器"
+description: "为抓取任务选择 Fetcher 或 StealthyFetcher。了解何时使用直接 HTTP 请求、JavaScript 渲染和可复用会话。"
+---
+
+# Fetcher 基础 {#fetchers-basics}
+
+## 简介 {#introduction}
+Fetcher 是用于发送请求或获取页面的类。一行代码就能使用多种功能,并得到一个 [Response](#response-object) 对象。从 v0.3 开始,所有 Fetcher 都有独立的会话类,用于保持会话运行。例如,浏览器 Fetcher 可以在所有请求完成前一直保持同一个浏览器打开,而不必重复打开浏览器。具体用哪种方式取决于任务需求。
+
+在 v0.2 之前,Scrapling 只是一个解析引擎。加入 Fetcher,是为了逐步覆盖网页抓取的整个流程。
+
+> Fetcher 不只是对其他库的简单封装。它们把这些库作为请求和获取页面的引擎,同时提供底层引擎没有的功能,并充分利用和优化这些引擎,让它们更适合网页抓取。
+
+## Fetcher 概览 {#fetchers-overview}
+
+Scrapling 提供 HTTP Fetcher(`Fetcher` 和 `AsyncFetcher`)以及浏览器 Fetcher(`StealthyFetcher`)。重复发送请求时可以使用相应的会话类。
+
+下表可帮助快速选择。
+
+
+| 功能 | Fetcher | StealthyFetcher |
+|--------------------|---------------------------------------------------|--------------------------------------------------------------------------------------------|
+| 相对速度 | 🐇🐇🐇🐇🐇 | 🐇🐇🐇 |
+| 隐蔽性 | ⭐⭐ | ⭐⭐⭐⭐⭐ |
+| 反机器人应对选项 | ⭐⭐ | ⭐⭐⭐⭐⭐ |
+| 加载 JavaScript | ❌ | ✅ |
+| 内存用量 | ⭐ | ⭐⭐⭐ |
+| 适用场景 | 只需 HTTP 请求即可完成的基础抓取 | - 动态加载的网站 <br/>- 简单自动化 <br/>- 从简单到复杂的防护 |
+| 浏览器 | ❌ | Chromium 和 Google Chrome |
+| 使用的浏览器 API | ❌ | Playwright |
+| 配置难度 | 简单 | 简单 |
+
+接下来的页面会分别详细介绍。
+
+## 配置所有 Fetcher 的解析器 {#parser-configuration-in-all-fetchers}
+所有 Fetcher 的导入方式相同,后面的页面会具体展示:
+```python
+from scrapling.fetchers import Fetcher, AsyncFetcher, StealthyFetcher
+```
+无需创建实例,即可直接使用。默认会采用解析器的标准设置:
+```python
+page = StealthyFetcher.fetch('https://example.com')
+```
+如果要配置处理响应的解析器([Selector 类](../parsing/main_classes.md#selector)),先执行以下操作:
+```python
+from scrapling.fetchers import Fetcher
+Fetcher.configure(adaptive=True, keep_comments=False) # and the rest
+```
+或者
+```python
+from scrapling.fetchers import Fetcher
+Fetcher.adaptive=True
+Fetcher.keep_comments=False
+```
+然后继续编写其他代码。
+
+可用的配置参数有 `adaptive`、`adaptive_domain`、`huge_tree`、`keep_comments`、`storage` 和 `storage_args`,与 [Selector](../parsing/main_classes.md#selector) 的对应参数相同。随时可以通过 `<fetcher_class>.display_config()` 查看当前配置。
+
+!!! info
+
+ `adaptive` 默认关闭。要使用自适应功能,需要先启用它。
+
+### 为每次请求配置解析器 {#set-parser-config-per-request}
+上面的配置会全局应用到通过该类发出的所有请求,目的是简化使用。
+
+如果不同请求需要不同配置,可以向请求方法(`fetch`/`get`/`post`/...)的 `selector_config` 参数传入字典。
+
+## Response 对象 {#response-object}
+`Response` 基于 [Selector](../parsing/main_classes.md#selector),还包含响应头、状态、Cookie 等响应信息,如下所示:
+```python
+from scrapling.fetchers import Fetcher
+page = Fetcher.get('https://example.com')
+
+page.status # HTTP status code
+page.reason # Status message
+page.cookies # Response cookies as a dictionary
+page.headers # Response headers
+page.request_headers # Request headers
+page.history # Response history of redirections, if any
+page.body # Raw response body as bytes
+page.encoding # Response encoding
+page.meta # Response metadata dictionary (e.g., proxy used). Mainly helpful with the spiders system.
+```
+所有 Fetcher 都返回 `Response` 对象。启用 `record_requests=True` 的浏览器会话,也会通过 `session.network.search(limit=None)` 和 `session.network.get(request_id)` 返回已保存的 `Response` 对象。有关保存 API 响应和迁移到 v5 的说明,请参阅[网络历史记录](stealthy.md#network-history)。
+
+`Response` 还可以用一行代码把页面转换为适合 LLM 使用的干净 Markdown:
+```python
+markdown = Fetcher.get('https://example.com').markdown(main_content_only=True)
+```
+转换前始终会移除脚本、样式、隐藏内容和提示注入内容。传入 `css_selector` 可以只转换指定元素。这需要安装 `rag` 扩展依赖,`ai`/`shell`/`all` 也包含它。详细说明见[构建 RAG 系统](../ai/building-rag-systems.md)。
+
+!!! note
+
+ 与 [Selector](../parsing/main_classes.md#selector) 不同,从 v0.4 开始,`Response` 的响应体始终为 bytes。
diff --git a/docs/locales/zh/fetching/static.md b/docs/locales/zh/fetching/static.md
new file mode 100644
index 0000000..08aff76
--- /dev/null
+++ b/docs/locales/zh/fetching/static.md
@@ -0,0 +1,449 @@
+---
+title: "使用 Fetcher 和 FetcherSession 进行 Python HTTP 抓取"
+description: "发送支持浏览器模拟、Cookie、代理和可复用会话的同步或异步 HTTP 请求,并使用 Scrapling 提取响应数据。"
+---
+
+# HTTP 请求 {#http-requests}
+
+`Fetcher` 基于高性能的 `curl_cffi`,提供快速、轻量的 HTTP 请求,以及多种隐身功能。
+
+!!! success "前提条件"
+
+ 1. 已阅读 [Fetcher 基础](../fetching/choosing.md),了解 [Response 对象](../fetching/choosing.md#response-object),并知道如何选择 Fetcher。
+ 2. 已阅读[查询元素](../parsing/selection.md),了解如何从 [Selector](../parsing/main_classes.md#selector)/[Response](../fetching/choosing.md#response-object) 对象中查找和提取元素。
+ 3. 已阅读[主要类](../parsing/main_classes.md),了解 [Response](../fetching/choosing.md#response-object) 从 [Selector](../parsing/main_classes.md#selector) 继承的属性和方法。
+
+## 基本用法 {#basic-usage}
+这个 Fetcher 的主要导入方式与其他 Fetcher 相同:
+
+```python
+from scrapling.fetchers import Fetcher
+```
+解析选项的配置方法见[这里](choosing.md#parser-configuration-in-all-fetchers)。
+
+### 通用参数 {#shared-arguments}
+这些请求方法共有一些参数,先介绍它们。
+
+- **url**:目标 URL。
+- **stealthy_headers**:生成并添加真实浏览器请求头,包括 Google referer,默认开启。
+- **follow_redirects**:控制重定向。**默认为 `"safe"`**,跟随重定向,但拒绝指向内部或私有 IP 的目标,以防范 SSRF。传入 `True` 可不受限制地跟随所有重定向,传入 `False` 则完全关闭重定向。
+- **timeout**:每次请求的最长等待时间,单位为秒。**默认 30 秒**。
+- **retries**:失败请求的最大尝试次数,包含首次尝试。**默认 3 次**。
+- **retry_delay**:重试之间的等待时间,单位为秒。**默认 1 秒**。
+- **impersonate**:模拟指定浏览器的 TLS 指纹。可以传入浏览器字符串或列表,例如 `"chrome110"`、`"firefox102"`、`"safari15_5"` 表示指定版本,`"chrome"`、`"firefox"`、`"safari"`、`"edge"` 则自动使用最新可用版本。这样,请求在 TLS 层面看起来来自真实浏览器。传入列表时,每次请求随机选择一个。**默认使用最新可用的 Chrome 版本。**
+- **http3**:使用 HTTP/3 协议发送请求。**默认为 False**。与 `impersonate` 同时使用可能出现问题。
+- **cookies**:请求使用的 Cookie,可以是 `name→value` 字典或字典列表。
+- **proxy**:此请求使用的代理,所有 HTTP 和 HTTPS 流量都会经过它。格式为 `http://username:password@localhost:8030`。
+- **proxy_auth**:代理的 HTTP Basic 认证,格式为 (username, password) 元组。
+- **proxies**:代理字典,格式为 `{"http": proxy_url, "https": proxy_url}`。
+- **proxy_rotator**:用于自动轮换代理的 `ProxyRotator` 实例,不能与 `proxy` 或 `proxies` 同时使用。
+- **headers**:请求中添加的请求头,可以覆盖 `stealthy_headers` 生成的任意请求头。
+- **max_redirects**:最大重定向次数。**默认 30 次**,设为 -1 表示不限制。
+- **verify**:是否验证 HTTPS 证书。**默认为 True**。
+- **cert**:客户端证书和密钥的文件名元组,格式为 (cert, key)。
+- **selector_config**:创建最终 `Selector`/`Response` 对象时使用的自定义解析参数字典。
+
+!!! note "注意事项:"
+
+ 1. 当前可模拟的浏览器有(`"edge"`、`"chrome"`、`"chrome_android"`、`"safari"`、`"safari_beta"`、`"safari_ios"`、`"safari_ios_beta"`、`"firefox"`、`"tor"`)。<br/>
+ 2. 可用浏览器及其版本会自动显示在参数补全中,并随 `curl_cffi` 更新。<br/>
+ 3. 启用 `impersonate` 或 `stealthy_headers` 后,Fetcher 会自动生成与所用浏览器版本匹配的真实请求头。
+
+如需进一步自定义,还可以向各方法传入 `curl_cffi` 支持、而该方法尚未直接提供的参数。
+
+### 文本编码 {#text-encoding}
+
+如果非 UTF-8 页面出现乱码,可以随请求传入 `default_encoding="shift_jis"`,或页面实际使用的编码。只有 `Content-Type` 响应头未指定字符集时,才会使用这个后备编码。它不会覆盖服务器提供的字符集。
+
+如果服务器提供了错误的字符集,可用 `selector_config={"encoding": "shift_jis"}` 强制指定正确编码。
+
+### HTTP 方法 {#http-methods}
+不同方法还有各自的参数,例如 GET 的 `params`,以及 POST、PUT、DELETE 的 `data`/`json`。
+
+通过例子更容易理解:
+
+> 注意:不支持 `OPTIONS` 和 `HEAD` 方法。
+#### GET {#get}
+```python
+from scrapling.fetchers import Fetcher
+# Basic GET
+page = Fetcher.get('https://example.com')
+page = Fetcher.get('https://scrapling.requestcatcher.com/get', stealthy_headers=True)
+page = Fetcher.get('https://scrapling.requestcatcher.com/get', proxy='http://username:password@localhost:8030')
+# With parameters
+page = Fetcher.get('https://example.com/search', params={'q': 'query'})
+
+# With headers
+page = Fetcher.get('https://example.com', headers={'User-Agent': 'Custom/1.0'})
+# Basic HTTP authentication
+page = Fetcher.get("https://example.com", auth=("my_user", "password123"))
+# Browser impersonation
+page = Fetcher.get('https://example.com', impersonate='chrome')
+# HTTP/3 support
+page = Fetcher.get('https://example.com', http3=True)
+```
+异步请求只需稍作调整:
+```python
+from scrapling.fetchers import AsyncFetcher
+# Basic GET
+page = await AsyncFetcher.get('https://example.com')
+page = await AsyncFetcher.get('https://scrapling.requestcatcher.com/get', stealthy_headers=True)
+page = await AsyncFetcher.get('https://scrapling.requestcatcher.com/get', proxy='http://username:password@localhost:8030')
+# With parameters
+page = await AsyncFetcher.get('https://example.com/search', params={'q': 'query'})
+# With headers
+page = await AsyncFetcher.get('https://example.com', headers={'User-Agent': 'Custom/1.0'})
+# Basic HTTP authentication
+page = await AsyncFetcher.get("https://example.com", auth=("my_user", "password123"))
+# Browser impersonation
+page = await AsyncFetcher.get('https://example.com', impersonate='chrome110')
+# HTTP/3 support
+page = await AsyncFetcher.get('https://example.com', http3=True)
+```
+这里的 `page` 始终是 [Response](choosing.md#response-object) 对象,也就是一种 [Selector](../parsing/main_classes.md#selector),因此可以直接解析:
+```python
+page.css('.something.something')
+
+page = Fetcher.get('https://api.github.com/events')
+>>> page.json()
+[{'id': '<redacted>',
+ 'type': 'PushEvent',
+ 'actor': {'id': '<redacted>',
+ 'login': '<redacted>',
+ 'display_login': '<redacted>',
+ 'gravatar_id': '',
+ 'url': 'https://api.github.com/users/<redacted>',
+ 'avatar_url': 'https://avatars.githubusercontent.com/u/<redacted>'},
+ 'repo': {'id': '<redacted>',
+...
+```
+#### POST {#post}
+```python
+from scrapling.fetchers import Fetcher
+# Basic POST
+page = Fetcher.post('https://scrapling.requestcatcher.com/post', data={'key': 'value'}, params={'q': 'query'})
+page = Fetcher.post('https://scrapling.requestcatcher.com/post', data={'key': 'value'}, stealthy_headers=True)
+page = Fetcher.post('https://scrapling.requestcatcher.com/post', data={'key': 'value'}, proxy='http://username:password@localhost:8030', impersonate="chrome")
+# Another example of form-encoded data
+page = Fetcher.post('https://example.com/submit', data={'username': 'user', 'password': 'pass'}, http3=True)
+# JSON data
+page = Fetcher.post('https://example.com/api', json={'key': 'value'})
+```
+异步请求只需稍作调整:
+```python
+from scrapling.fetchers import AsyncFetcher
+# Basic POST
+page = await AsyncFetcher.post('https://scrapling.requestcatcher.com/post', data={'key': 'value'})
+page = await AsyncFetcher.post('https://scrapling.requestcatcher.com/post', data={'key': 'value'}, stealthy_headers=True)
+page = await AsyncFetcher.post('https://scrapling.requestcatcher.com/post', data={'key': 'value'}, proxy='http://username:password@localhost:8030', impersonate="chrome")
+# Another example of form-encoded data
+page = await AsyncFetcher.post('https://example.com/submit', data={'username': 'user', 'password': 'pass'}, http3=True)
+# JSON data
+page = await AsyncFetcher.post('https://example.com/api', json={'key': 'value'})
+```
+#### PUT {#put}
+```python
+from scrapling.fetchers import Fetcher
+# Basic PUT
+page = Fetcher.put('https://example.com/update', data={'status': 'updated'})
+page = Fetcher.put('https://example.com/update', data={'status': 'updated'}, stealthy_headers=True, impersonate="chrome")
+page = Fetcher.put('https://example.com/update', data={'status': 'updated'}, proxy='http://username:password@localhost:8030')
+# Another example of form-encoded data
+page = Fetcher.put("https://scrapling.requestcatcher.com/put", data={'key': ['value1', 'value2']})
+```
+异步请求只需稍作调整:
+```python
+from scrapling.fetchers import AsyncFetcher
+# Basic PUT
+page = await AsyncFetcher.put('https://example.com/update', data={'status': 'updated'})
+page = await AsyncFetcher.put('https://example.com/update', data={'status': 'updated'}, stealthy_headers=True, impersonate="chrome")
+page = await AsyncFetcher.put('https://example.com/update', data={'status': 'updated'}, proxy='http://username:password@localhost:8030')
+# Another example of form-encoded data
+page = await AsyncFetcher.put("https://scrapling.requestcatcher.com/put", data={'key': ['value1', 'value2']})
+```
+
+#### DELETE {#delete}
+```python
+from scrapling.fetchers import Fetcher
+page = Fetcher.delete('https://example.com/resource/123')
+page = Fetcher.delete('https://example.com/resource/123', stealthy_headers=True, impersonate="chrome")
+page = Fetcher.delete('https://example.com/resource/123', proxy='http://username:password@localhost:8030')
+```
+异步请求只需稍作调整:
+```python
+from scrapling.fetchers import AsyncFetcher
+page = await AsyncFetcher.delete('https://example.com/resource/123')
+page = await AsyncFetcher.delete('https://example.com/resource/123', stealthy_headers=True, impersonate="chrome")
+page = await AsyncFetcher.delete('https://example.com/resource/123', proxy='http://username:password@localhost:8030')
+```
+
+## 会话管理 {#session-management}
+
+要用相同配置发送多个请求,可以使用 `FetcherSession`。它同时支持同步和异步代码,会自动识别并切换会话类型,不需要导入另一个类。
+
+`FetcherSession` 接受请求方法中的几乎所有参数。可以先为整个会话配置默认值,再轻松覆盖某次请求的设置,如下面的示例所示。
+
+```python
+from scrapling.fetchers import FetcherSession
+
+# Create a session with default configuration
+with FetcherSession(
+ impersonate='chrome',
+ http3=True,
+ stealthy_headers=True,
+ timeout=30,
+ retries=3
+) as session:
+ # Make multiple requests with the same settings and the same cookies
+ page1 = session.get('https://scrapling.requestcatcher.com/get')
+ page2 = session.post('https://scrapling.requestcatcher.com/post', data={'key': 'value'})
+ page3 = session.get('https://api.github.com/events')
+
+ # All requests share the same session and connection pool
+```
+
+也可以给 `FetcherSession` 配置 `ProxyRotator`,在请求之间自动轮换代理:
+
+```python
+from scrapling.fetchers import FetcherSession, ProxyRotator
+
+rotator = ProxyRotator([
+ 'http://proxy1:8080',
+ 'http://proxy2:8080',
+ 'http://proxy3:8080',
+])
+
+with FetcherSession(proxy_rotator=rotator, impersonate='chrome') as session:
+ # Each request automatically uses the next proxy in rotation
+ page1 = session.get('https://example.com/page1')
+ page2 = session.get('https://example.com/page2')
+
+ # You can check which proxy was used via the response metadata
+ print(page1.meta['proxy'])
+```
+
+向请求方法直接传入 `proxy=`,可以覆盖这次请求使用的会话代理或轮换器:
+
+```python
+with FetcherSession(proxy='http://default-proxy:8080') as session:
+ # Uses the session proxy
+ page1 = session.get('https://example.com/page1')
+
+ # Override the proxy for this specific request
+ page2 = session.get('https://example.com/page2', proxy='http://special-proxy:9090')
+```
+
+异步示例:
+
+```python
+async with FetcherSession(impersonate='firefox', http3=True) as session:
+ # All standard HTTP methods available
+ response = await session.get('https://example.com')
+ response = await session.post('https://scrapling.requestcatcher.com/post', json={'data': 'value'})
+ response = await session.put('https://scrapling.requestcatcher.com/put', data={'update': 'info'})
+ response = await session.delete('https://scrapling.requestcatcher.com/delete')
+```
+更好的写法:
+```python
+import asyncio
+from scrapling.fetchers import FetcherSession
+
+# Async session usage
+async with FetcherSession(impersonate="safari") as session:
+ urls = ['https://example.com/page1', 'https://example.com/page2']
+
+ tasks = [
+ session.get(url) for url in urls
+ ]
+
+ pages = await asyncio.gather(*tasks)
+```
+
+`Fetcher` 会通过 `FetcherSession` 为每次请求创建一个临时会话。
+
+### 会话的优点 {#session-benefits}
+
+- **速度更快**:比每次请求都创建会话快 10 倍。
+- **保留 Cookie**:自动在请求之间管理 Cookie。
+- **节省资源**:多个请求的内存和 CPU 使用更高效。
+- **集中配置**:在同一个地方管理请求设置。
+
+## 示例 {#examples}
+下面是一些完整示例,帮助初学者开始网页抓取。
+
+### 基本 HTTP 请求 {#basic-http-request}
+
+```python
+from scrapling.fetchers import Fetcher
+
+# Make a request
+page = Fetcher.get('https://example.com')
+
+# Check the status
+if page.status == 200:
+ # Extract title
+ title = page.css('title::text').get()
+ print(f"Page title: {title}")
+
+ # Extract all links
+ links = page.css('a::attr(href)').getall()
+ print(f"Found {len(links)} links")
+```
+
+### 抓取产品 {#product-scraping}
+
+```python
+from scrapling.fetchers import Fetcher
+
+def scrape_products():
+ page = Fetcher.get('https://example.com/products')
+
+ # Find all product elements
+ products = page.css('.product')
+
+ results = []
+ for product in products:
+ results.append({
+ 'title': product.css('.title::text').get(),
+ 'price': product.css('.price::text').re_first(r'\d+\.\d{2}'),
+ 'description': product.css('.description::text').get(),
+ 'in_stock': product.has_class('in-stock')
+ })
+
+ return results
+```
+
+### 下载文件 {#downloading-files}
+
+```python
+from scrapling.fetchers import Fetcher
+
+page = Fetcher.get('https://raw.githubusercontent.com/D4Vinci/Scrapling/main/docs/assets/main_cover.png')
+with open(file='main_cover.png', mode='wb') as f:
+ f.write(page.body)
+```
+
+### 处理分页 {#pagination-handling}
+
+```python
+from scrapling.fetchers import Fetcher
+
+def scrape_all_pages():
+ base_url = 'https://example.com/products?page={}'
+ page_num = 1
+ all_products = []
+
+ while True:
+ # Get current page
+ page = Fetcher.get(base_url.format(page_num))
+
+ # Find products
+ products = page.css('.product')
+ if not products:
+ break
+
+ # Process products
+ for product in products:
+ all_products.append({
+ 'name': product.css('.name::text').get(),
+ 'price': product.css('.price::text').get()
+ })
+
+ # Next page
+ page_num += 1
+
+ return all_products
+```
+
+### 提交表单 {#form-submission}
+
+```python
+from scrapling.fetchers import Fetcher
+
+# Submit login form
+response = Fetcher.post(
+ 'https://example.com/login',
+ data={
+ 'username': '[email protected]',
+ 'password': 'password123'
+ }
+)
+
+# Check login success
+if response.status == 200:
+ # Extract user info
+ user_name = response.css('.user-name::text').get()
+ print(f"Logged in as: {user_name}")
+```
+
+### 提取表格 {#table-extraction}
+
+```python
+from scrapling.fetchers import Fetcher
+
+def extract_table():
+ page = Fetcher.get('https://example.com/data')
+
+ # Find table
+ table = page.css('table')[0]
+
+ # Extract headers
+ headers = [
+ th.text for th in table.css('thead th')
+ ]
+
+ # Extract rows
+ rows = []
+ for row in table.css('tbody tr'):
+ cells = [td.text for td in row.css('td')]
+ rows.append(dict(zip(headers, cells)))
+
+ return rows
+```
+
+### 导航菜单 {#navigation-menu}
+
+```python
+from scrapling.fetchers import Fetcher
+
+def extract_menu():
+ page = Fetcher.get('https://example.com')
+
+ # Find navigation
+ nav = page.css('nav')[0]
+
+ menu = {}
+ for item in nav.css('li'):
+ links = item.css('a')
+ if links:
+ link = links[0]
+ menu[link.text] = {
+ 'url': link['href'],
+ 'has_submenu': bool(item.css('.submenu'))
+ }
+
+ return menu
+```
+
+## 适用场景 {#when-to-use}
+
+以下情况适合使用 `Fetcher`:
+
+- 需要快速发送 HTTP 请求。
+- 希望尽量减少额外资源开销。
+- 不需要执行 JavaScript,通过请求就能抓取网站。
+- 需要一些隐身功能,例如网站有防护,但没有 JavaScript 挑战。
+
+以下情况适合使用 `FetcherSession`:
+
+- 对同一网站或不同网站发送多个请求。
+- 需要在请求之间保留 Cookie 或认证状态。
+- 希望通过连接复用提高性能。
+- 需要让多个请求使用一致的配置。
+- 使用需要会话状态的 API。
+
+以下情况应使用其他 Fetcher:
+
+- 需要浏览器自动化。
+- 需要更高级的反机器人应对或隐身功能。
+- 需要执行 JavaScript 或与动态内容交互。
diff --git a/docs/locales/zh/fetching/stealthy.md b/docs/locales/zh/fetching/stealthy.md
new file mode 100644
index 0000000..7395364
--- /dev/null
+++ b/docs/locales/zh/fetching/stealthy.md
@@ -0,0 +1,536 @@
+---
+title: "使用 StealthyFetcher 抓取 JavaScript 网站"
+description: "用 Scrapling 浏览器会话渲染页面、等待数据、复用登录状态并读取后台 API 响应。配置代理和防护挑战处理。"
+---
+
+# 使用 StealthyFetcher 在浏览器中获取页面 {#browser-fetching-with-stealthyfetcher}
+
+`StealthyFetcher` 可以加载 JavaScript 页面,并通过带有反机器人应对功能的 Chromium 或 Google Chrome 执行自动化。它使用经过隐身调整的 [Playwright API](https://playwright.dev/python/docs/intro)。
+
+要自动操作页面,需要了解一些 [Playwright Page API](https://playwright.dev/python/docs/api/class-page),后面会说明。
+
+!!! success "前提条件"
+
+ 1. 已阅读 [Fetcher 基础](../fetching/choosing.md),了解 [Response 对象](../fetching/choosing.md#response-object),并知道如何选择 Fetcher。
+ 2. 已阅读[查询元素](../parsing/selection.md),了解如何从 [Selector](../parsing/main_classes.md#selector)/[Response](../fetching/choosing.md#response-object) 对象中查找和提取元素。
+ 3. 已阅读[主要类](../parsing/main_classes.md),了解 [Response](../fetching/choosing.md#response-object) 从 [Selector](../parsing/main_classes.md#selector) 继承的属性和方法。
+
+## 基本用法 {#basic-usage}
+这个 Fetcher 的主要导入方式与其他 Fetcher 相同:
+
+```python
+from scrapling.fetchers import StealthyFetcher
+```
+解析选项的配置方法见[这里](choosing.md#parser-configuration-in-all-fetchers)。
+
+下面通过示例逐个介绍大部分参数。如需快速查阅,可以直接查看[完整参数表](#full-list-of-arguments)。
+
+!!! abstract "说明"
+
+ `fetch` 的异步版本是 `async_fetch`。
+
+
+目前提供三种主要运行方式,可以按需要组合使用。
+
+分别是:
+
+### 1. 自带的 Chromium {#1-bundled-chromium}
+```python
+StealthyFetcher.fetch('https://example.com')
+```
+打开自带的 Chromium,使用默认隐身设置并加载页面。
+
+### 2. 已安装的 Chrome {#2-real-chrome}
+```python
+StealthyFetcher.fetch('https://example.com', real_chrome=True)
+```
+如果设备上已安装 Google Chrome,可以使用这个选项。它与第一种方式类似,但使用本机的 Google Chrome 而不是 Chromium。这样请求更接近真实用户,也更难被识别为自动化。
+
+如果还没有安装 Google Chrome,可以通过以下终端命令为库安装,而不必手动处理:
+```commandline
+playwright install chrome
+```
+
+### 3. CDP 连接 {#3-cdp-connection}
+```python
+StealthyFetcher.fetch('https://example.com', cdp_url='ws://localhost:9222')
+```
+除了在本机启动 Chromium 或 Google Chrome,还可以通过 [Chrome DevTools Protocol](https://chromedevtools.github.io/devtools-protocol/) 连接远程浏览器。
+
+URL 可以是浏览器服务商提供的 WebSocket 地址(`ws://`/`wss://`),也可以是浏览器的 HTTP 地址,例如 `http://localhost:9222`。
+
+
+## 它提供哪些功能? {#what-does-it-do}
+
+StealthyFetcher 提供以下反机器人应对功能:
+
+1. 通过 `solve_cloudflare=True` 自动处理所有类型的 Cloudflare Turnstile 和 Interstitial 挑战。
+2. 避免 CDP runtime 和 WebRTC 泄露信息。
+3. 隔离 JavaScript 执行,移除多种 Playwright 指纹,并避免一些已知机器人行为触发检测。
+4. 为 Canvas 添加随机噪声,防止通过 Canvas 识别指纹。
+5. 自动处理已知的无头模式检测方式,并提供选项来应对时区不一致检测。
+6. 还有其他应对防护的选项。
+
+## 完整参数列表 {#full-list-of-arguments}
+这个 Fetcher 及其会话类提供很多选项。在查看[示例](#examples)前,先列出完整参数:
+
+
+| 参数 | 说明 | 可选 |
+|:---------------------:|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:--------:|
+| url | 目标 URL。 | ❌ |
+| headless | `True` 表示无头模式,即不显示窗口,**默认如此**。`False` 表示显示浏览器窗口。 | ✔️ |
+| disable_resources | 阻止不必要的资源请求以提高速度。类型包括 `font`、`image`、`media`、`beacon`、`object`、`imageset`、`texttrack`、`websocket`、`csp_report` 和 `stylesheet`。 | ✔️ |
+| cookies | 为下一次请求设置 Cookie。 | ✔️ |
+| useragent | 指定 User-Agent 字符串。**未指定时,Fetcher 会生成并使用相同浏览器及版本的真实 User-Agent。** | ✔️ |
+| network_idle | 等待页面至少连续 500 ms 没有网络连接。 | ✔️ |
+| load_dom | 等待页面上的所有 JavaScript 加载并执行,即等待 `domcontentloaded` 状态。默认开启。 | ✔️ |
+| pierce_shadow | 将开放的 Shadow DOM 内容包含在响应 HTML 中,默认为 `False`。可以为整个会话设置,也可以按请求覆盖。 | ✔️ |
+| timeout | 页面操作和等待使用的超时时间,单位为毫秒。默认为 30,000 ms,即 30 秒。 | ✔️ |
+| wait | 所有步骤结束后,在关闭页面并返回 `Response` 前额外等待的时间,单位为毫秒。 | ✔️ |
+| page_action | 用于自动化的函数,接收 `page` 对象,在导航后执行所需操作。 | ✔️ |
+| page_setup | 接收 `page` 对象并在导航前执行的函数。用于注册必须在页面加载前准备好的事件监听器或路由。 | ✔️ |
+| wait_selector | 等待指定 CSS 选择器达到指定状态。 | ✔️ |
+| init_script | JavaScript 文件的绝对路径,在此会话中的每个页面创建时执行。 | ✔️ |
+| wait_selector_state | 等待 `wait_selector` 指定的元素达到这个状态。_默认状态为 `attached`。_ | ✔️ |
+| google_search | 设置 Google referer 请求头,默认开启。 | ✔️ |
+| extra_headers | 要添加到请求中的额外请求头字典。_同时使用时,`google_search` 设置的 referer 优先于这里的值。_ | ✔️ |
+| proxy | 请求使用的代理,可以是字符串,或仅包含 'server'、'username'、'password' 的字典。 | ✔️ |
+| real_chrome | 启用后,Fetcher 会启动并使用设备上已安装的 Chrome。 | ✔️ |
+| locale | 区域设置,例如 `en-GB`、`de-DE`。影响 `navigator.language`、请求头 `Accept-Language`,以及数字和日期格式。默认使用系统区域设置。 | ✔️ |
+| timezone_id | 修改浏览器时区,默认使用系统时区。 | ✔️ |
+| cdp_url | 连接此 CDP URL 来控制已有浏览器,而不是启动新实例。 | ✔️ |
+| user_data_dir | 用户数据目录的路径,用于保存 Cookie、本地存储等浏览器会话数据。默认创建临时目录。**仅支持会话。** | ✔️ |
+| extra_flags | 启动浏览器时传入的额外参数列表。 | ✔️ |
+| solve_cloudflare | 返回响应前,处理所有类型的 Cloudflare Turnstile 和 Interstitial 挑战。默认为 `False`。 | ✔️ |
+| block_webrtc | 强制 WebRTC 遵守代理设置,避免泄露本地 IP 地址。 | ✔️ |
+| hide_canvas | 为 Canvas 操作添加随机噪声,防止指纹识别。 | ✔️ |
+| allow_webgl | 默认开启。关闭后会完全禁用 WebGL 和 WebGL 2.0。不建议关闭,因为很多 WAF 会检查 WebGL 是否启用。 | ✔️ |
+| additional_args | 传给 Playwright 上下文的额外设置,优先级高于 Scrapling 设置。 | ✔️ |
+| selector_config | 创建最终 `Selector`/`Response` 对象时使用的自定义解析参数字典。 | ✔️ |
+| blocked_domains | 要阻止请求的域名集合,也会匹配子域名,例如 `"example.com"` 也会阻止 `"sub.example.com"`。 | ✔️ |
+| block_ads | 阻止向约 3,500 个已知广告或跟踪域名发送请求,可与 `blocked_domains` 结合使用。 | ✔️ |
+| dns_over_https | 通过 Cloudflare 的 DNS-over-HTTPS 发送 DNS 查询,避免使用代理时发生 DNS 泄露。 | ✔️ |
+| proxy_rotator | 自动轮换代理的 `ProxyRotator` 实例,不能与 `proxy` 同时使用。 | ✔️ |
+| retries | 失败请求的重试次数,默认为 3。 | ✔️ |
+| retry_delay | 重试之间的等待秒数,默认为 1。 | ✔️ |
+| record_requests | 在 `session.network` 中保留已完成的请求及保存的响应。仅用于会话,默认为 `False`。 | ✔️ |
+| max_recorded_requests | 每个会话保留的最大请求条目数,默认为 1,000。保存的响应体还受固定大小限制。 | ✔️ |
+| executable_path | 自定义浏览器可执行文件的绝对路径,用来替代自带的 Chromium。适用于特殊安装方式或自定义浏览器构建。 | ✔️ |
+
+在会话类中,可以为整个会话设置这些参数。部分标签页级设置还可以在每次请求中单独覆盖,包括 `google_search`、`timeout`、`wait`、`page_action`、`page_setup`、`extra_headers`、`disable_resources`、`wait_selector`、`wait_selector_state`、`network_idle`、`load_dom`、`pierce_shadow`、`solve_cloudflare`、`blocked_domains`、`proxy` 和 `selector_config`。
+
+!!! note "注意事项:"
+
+ 1. 在我的测试中,`disable_resources` 让部分网站的请求加快了约 25%,也能减少代理流量。但要谨慎使用,因为它可能导致某些网站一直无法完成加载。
+ 2. 所有请求默认启用 `google_search`,将 referer 设为 `https://www.google.com/`。它的优先级高于 `extra_headers` 中设置的 referer。
+ 3. 未指定 User-Agent 且启用无头模式时,Fetcher 会生成并使用同版本浏览器的真实 User-Agent。未启用无头模式时,则使用浏览器默认的 User-Agent,在当前版本中与普通浏览器相同。
+ 4. `init_script` 注册在浏览器上下文中,因此会在页面创建时运行。隐身模式默认使用 Patchright 的隔离执行上下文。如果 `page_action` 需要读取脚本放在 `window` 上的全局值,应在操作函数中调用 `page.evaluate(..., isolated_context=False)`。
+
+## 会话管理 {#session-management}
+
+使用 `StealthySession`/`AsyncStealthySession`,可以在多次请求期间保持浏览器打开,并复用同一配置。这些类支持 `fetch` 的所有参数,因此可以统一设置整个会话。
+
+```python
+from scrapling.fetchers import StealthySession
+
+
+with StealthySession(
+ headless=True,
+ disable_resources=True,
+ real_chrome=True
+) as session:
+
+ page1 = session.fetch('https://example1.com')
+ page2 = session.fetch('https://example2.com')
+ page3 = session.fetch('https://dynamic-site.com')
+
+
+```
+
+### 使用异步会话 {#async-session-usage}
+
+```python
+import asyncio
+from scrapling.fetchers import AsyncStealthySession
+
+async def scrape_multiple_sites():
+ async with AsyncStealthySession(
+ network_idle=True,
+ timeout=30000,
+ max_pages=3
+ ) as session:
+
+ pages = await asyncio.gather(
+ session.fetch('https://spa-app1.com'),
+ session.fetch('https://spa-app2.com'),
+ session.fetch('https://dynamic-content.com')
+ )
+ return pages
+```
+
+`max_pages` 控制**浏览器标签页池**中同时打开的最大标签页数。请求完成后,标签页保持打开。每次请求时,库会按以下步骤处理:
+
+1. 如果有空闲标签页,就复用它。每次请求都会应用自己的 `timeout`、`extra_headers`、`disable_resources`、`blocked_domains` 等标签页设置,不会沿用上一次请求的配置。
+2. 否则,如果当前标签页数少于 `max_pages`,就打开新标签页。
+3. 否则,以不到一秒的间隔检查是否有标签页空闲。等待 60 秒后仍不可用,就抛出 `TimeoutError`。这可能发生在目标网站无响应时。
+
+出现错误的标签页会被关闭并替换。也可以随时调用 `session.close_pages()` 关闭所有标签页,下一次请求会打开新的标签页。
+
+这样就能在同一个浏览器中同时获取多个 URL,节省资源,而且速度很快 :)
+
+标签页保持打开,也意味着下次请求开始时,之前的页面仍然存在。下一次请求的 `page_setup` 会在离开旧页面前运行,因此可以把自动化操作串联到多次请求中。
+
+在 0.3.2 到 0.4.14 版本中,请求后会关闭标签页,因为复用时可能残留前一次请求的设置。从 0.4.15 开始,每次复用都会重置设置,因此标签页可以保持打开。
+
+### 保存和加载会话状态 {#save-and-load-session-state}
+
+使用 `save_state(path)` 把 Cookie、本地存储和 IndexedDB 保存到 JSON 文件。使用 `load_state(path)` 在另一个会话中恢复,或替换当前会话的已存储状态。两者都接受字符串或 `pathlib.Path`,并返回 `None`。文件格式与 Playwright 的存储状态文件兼容。
+
+```python
+from scrapling.fetchers import StealthySession
+
+with StealthySession() as session:
+ session.fetch('https://example.com')
+ session.save_state('state.json')
+
+with StealthySession() as session:
+ session.load_state('state.json')
+ page = session.fetch('https://example.com')
+```
+
+登录或其他浏览器操作完成后再保存。在已启动的会话中调用这两个方法,并先等待所有抓取完成。加载会替换已有 Cookie、本地存储和 IndexedDB。要使用恢复的登录状态,需要获取或重新加载页面;加载状态本身不会让现有标签页跳转。
+
+使用 `AsyncStealthySession` 时需要 `await`:
+
+```python
+from scrapling.fetchers import AsyncStealthySession
+
+async def restore_session():
+ async with AsyncStealthySession() as session:
+ await session.load_state('state.json')
+ page = await session.fetch('https://example.com')
+ await session.save_state('state.json')
+ return page
+```
+
+这些方法只保存和恢复共享浏览器上下文,不影响单次代理请求的临时上下文。使用 `proxy_rotator` 的会话没有共享上下文,因此会抛出 `RuntimeError`。固定的会话 `proxy` 可以正常使用。
+
+文件不包含 `sessionStorage`、打开的标签页或浏览器设置。保存会覆盖文件,其父目录必须已存在。文件和 JSON 错误会直接抛给调用方。
+
+### 会话的优点 {#session-benefits}
+
+- **复用浏览器**:后续请求使用同一个浏览器实例,速度更快。
+- **保留 Cookie**:像普通浏览器一样自动管理 Cookie 和会话状态。
+- **一致的指纹**:所有请求使用相同的浏览器指纹。
+- **节省内存**:比每次请求都启动新浏览器更节省资源。
+
+
+## 示例 {#examples}
+通过示例更容易理解,下面逐一展示。
+
+### 控制资源 {#resource-control}
+
+```python
+
+page = StealthyFetcher.fetch('https://example.com', disable_resources=True)
+```
+
+### Shadow DOM {#shadow-dom}
+
+有些页面把内容放在开放的 Shadow Root 中,这些内容不会出现在页面的普通 HTML 里。启用 `pierce_shadow`,即可把它们加入响应,再照常使用 CSS 或 XPath:
+
+```python
+from scrapling.fetchers import StealthyFetcher
+
+page = StealthyFetcher.fetch('https://example.com', pierce_shadow=True)
+titles = page.css('product-card .title::text').getall()
+```
+
+此选项默认为 `False`。也可以为会话开启,再针对单次请求关闭:
+
+```python
+from scrapling.fetchers import StealthySession
+
+with StealthySession(pierce_shadow=True) as session:
+ page = session.fetch('https://example.com')
+ plain_page = session.fetch('https://example.com', pierce_shadow=False)
+```
+
+相同选项也适用于 `async_fetch` 和异步会话。
+
+只包含开放的 Shadow Root,不会遍历封闭的 Shadow Root 或 iframe 文档。如果组件在页面加载后才出现,可以使用 `wait_selector`。
+
+每个开放的 Shadow Root 会在响应中包装为一个 `<shadow-root>` 元素。Slot 保留原有标签和属性,并包含分配给它的节点;如果没有分配节点,则使用后备内容。未分配到 Slot 的 Light DOM 子节点会被省略。真实浏览器页面不会被修改。
+
+```html
+<product-card>
+ <shadow-root>
+ <div class="title">Product name</div>
+ <slot name="price"><span class="price">20</span></slot>
+ </shadow-root>
+</product-card>
+```
+
+后代选择器可以跨这些元素查找。直接子元素选择器则必须包含新增的包装元素和 Slot:
+
+```python
+titles = page.css('product-card .title::text').getall()
+titles = page.css('product-card > shadow-root > .title::text').getall()
+prices = page.css('product-card > shadow-root > slot[name="price"] > .price::text').getall()
+```
+
+这些包装元素和 Slot 会出现在 XPath 路径、`.children`、`response.body` 和 HTML 导出中。Markdown 和文本提取只返回内容,不输出标签。表示隐藏状态的 Slot 属性仍会保留,供内容清理使用。
+
+快照遵循内容顺序,但不计算 CSS 可见性或布局。包含 `<shadow-root>` 的选择器针对 Scrapling 响应,而不是真实浏览器页面。其他 HTML 解析器可能以不同方式处理这些特殊嵌套结构。
+
+### 屏蔽域名 {#domain-blocking}
+
+```python
+
+page = StealthyFetcher.fetch('https://example.com', blocked_domains={"ads.example.com", "tracker.net"})
+```
+
+### 控制网络 {#network-control}
+
+```python
+
+page = StealthyFetcher.fetch('https://example.com', network_idle=True)
+
+
+page = StealthyFetcher.fetch('https://example.com', timeout=30000)
+
+
+page = StealthyFetcher.fetch('https://example.com', proxy='http://username:password@host:port')
+```
+
+### 下载文件 {#downloading-files}
+
+```python
+page = StealthyFetcher.fetch('https://raw.githubusercontent.com/D4Vinci/Scrapling/main/docs/assets/main_cover.png')
+
+with open(file='main_cover.png', mode='wb') as f:
+ f.write(page.body)
+```
+
+`Response` 对象的 `body` 属性始终返回 `bytes`。
+
+### 导航前设置 {#pre-navigation-setup}
+如果事件监听器、路由或脚本必须在页面导航前注册,使用 `page_setup`。这个函数接收 `page` 对象,并在 `page.goto()` 之前运行。
+
+```python
+from patchright.sync_api import Page
+
+def capture_websockets(page: Page):
+ page.on("websocket", lambda ws: print(f"WebSocket opened: {ws.url}"))
+
+page = StealthyFetcher.fetch('https://example.com', page_setup=capture_websockets)
+```
+异步版本:
+```python
+from patchright.async_api import Page
+
+async def capture_websockets(page: Page):
+ page.on("websocket", lambda ws: print(f"WebSocket opened: {ws.url}"))
+
+page = await StealthyFetcher.async_fetch('https://example.com', page_setup=capture_websockets)
+```
+
+可以与 `page_action` 配合使用:`page_setup` 在导航前执行,`page_action` 在导航后执行。
+
+### Cloudflare 和隐身选项 {#cloudflare-and-stealth-options}
+
+```python
+
+page = StealthyFetcher.fetch('https://nopecha.com/demo/cloudflare', solve_cloudflare=True)
+
+
+page = StealthyFetcher.fetch(
+ 'https://protected-site.com',
+ solve_cloudflare=True,
+ block_webrtc=True,
+ real_chrome=True,
+ hide_canvas=True,
+ google_search=True,
+ proxy='http://username:password@host:port', # It can also be a dictionary with only the keys 'server', 'username', and 'password'.
+)
+```
+
+`solve_cloudflare` 会自动检测并处理所有类型的 Cloudflare Turnstile 和 Interstitial 挑战:
+
+- JavaScript 挑战,由 Cloudflare 管理
+- 交互式挑战,例如点击验证框
+- 无感挑战,在后台自动验证
+
+也支持包含嵌入式验证码的自定义页面。
+
+!!! notes "**重要说明:**"
+
+ 1. 某些网站使用自定义实现,需要设置 `wait_selector`,确保解开验证码后继续等待真实页面内容。我们尽量让处理逻辑通用,但有些网站确实属于特殊情况。
+ 2. 使用 Cloudflare 处理功能时,超时应至少设为 60 秒,留出足够的挑战处理时间。
+ 3. 这项功能可以与代理和其他隐身选项一起使用。
+
+### 浏览器自动化 {#browser-automation}
+这里需要了解 [Playwright Page API](https://playwright.dev/python/docs/api/class-page)。传入的函数接收 Playwright 的 Page 对象,执行所需操作,然后 Fetcher 继续工作。
+
+如果启用了 `network_idle`,这个函数会在等待完成后立即执行。它在等待 `wait_selector` 之前执行,因此除了自动化,也可以用于其他页面修改。
+
+下面通过页面的[鼠标事件](https://playwright.dev/python/docs/api/class-mouse),先用滚轮滚动,再移动鼠标。
+```python
+from patchright.sync_api import Page
+
+def scroll_page(page: Page):
+ page.mouse.wheel(10, 0)
+ page.mouse.move(100, 400)
+ page.mouse.up()
+
+page = StealthyFetcher.fetch('https://example.com', page_action=scroll_page)
+```
+使用异步抓取方法时,这个函数也必须是异步函数。
+```python
+from patchright.async_api import Page
+
+async def scroll_page(page: Page):
+ await page.mouse.wheel(10, 0)
+ await page.mouse.move(100, 400)
+ await page.mouse.up()
+
+page = await StealthyFetcher.async_fetch('https://example.com', page_action=scroll_page)
+```
+
+### 等待条件 {#wait-conditions}
+
+```python
+
+page = StealthyFetcher.fetch(
+ 'https://quotes.toscrape.com/js-delayed/',
+ wait_selector='.quote',
+ wait_selector_state='visible'
+)
+```
+这是返回响应前最后一项可配置的等待条件。向 `wait_selector` 传入 CSS 选择器,Fetcher 会等待 `wait_selector_state` 指定的状态。未指定时默认为 `attached`,即元素已经出现在 DOM 中。
+
+之后,如果开启 `load_dom`,Fetcher 会再次检查所有 JavaScript 是否已加载并执行,也就是是否达到 `domcontentloaded` 状态,必要时继续等待。这个选项默认开启。如果启用了 `network_idle`,还会再次等待 `network_idle` 满足条件。
+
+可以等待以下状态([来源](https://playwright.dev/python/docs/api/class-page#page-wait-for-selector)):
+
+- `attached`:等待元素出现在 DOM 中。
+- `detached`:等待元素从 DOM 中移除。
+- `visible`:等待元素的边界框非空,且没有设置 `visibility:hidden`。没有内容或设置了 `display:none` 的元素边界框为空,不算可见。
+- `hidden`:等待元素从 DOM 中移除、边界框为空,或设置了 `visibility:hidden`。它与 `'visible'` 相反。
+
+### 网络历史记录 {#network-history}
+
+在浏览器会话中启用 `record_requests`,即可检查跨页面加载、操作和标签页的已完成请求。历史记录覆盖会话的所有上下文,包括临时代理上下文,并把响应保存为 Scrapling `Response`。可以查找 API 调用、HTTP 错误和重定向,而不必再次发送请求。会话关闭后也能读取已保存的响应头和响应体。失败或尚未完成的请求会被省略,已完成的 HTTP 4xx 和 5xx 响应则会保留。
+
+```python
+from scrapling.fetchers import StealthySession
+
+with StealthySession(record_requests=True, max_recorded_requests=1000) as session:
+ session.fetch('https://example.com', network_idle=True)
+
+for response in session.network.search(resource_type='document', limit=None):
+ print(response.meta['network_id'], response.url, response.status)
+ if note := response.meta.get('body_note'):
+ print(note)
+ else:
+ print(response.body)
+ print(response.css('title::text').get())
+
+session.network.clear()
+```
+
+同一 API 也适用于 `AsyncStealthySession`。记录功能默认关闭。创建会话时设置 `record_requests=True`,需要时再设置 `max_recorded_requests`。
+
+- `session.network.search(url_pattern=None, method=None, resource_type=None, status=None, after_id=0, limit=100, include_static=True)` 按网络 ID 顺序返回已保存的 `Response`。`limit=None` 返回所有仍被保留的匹配项。`url_pattern` 是搜索时使用的正则表达式,模式无效时会在搜索时抛出错误。`after_id` 选择网络 ID 更大的响应。`include_static=False` 只保留 XHR/fetch 请求和 HTTP 错误;使用 `True` 可包含所有资源类型和已保存的重定向。
+- `session.network.get(request_id)` 返回一个已保存的 `Response`,如果记录已被移除,则返回 `None`。
+- `session.network.clear()` 清空历史记录。请求 ID 仍继续递增,不会重复使用。
+
+每个已保存的 `Response` 都可以直接访问 `.url`、`.method`、`.status`、`.headers`、`.request_headers`、字节形式的 `.body`、`.json()` 和 CSS/XPath 方法。`.meta` 包含 `network_id`、`resource_type` 和 `request_body`,后者为字节或 `None`。如果读取完整响应头失败,保存的头信息可能不完整。这些都是本地读取。即使在异步会话中,也不要使用 await 等待这些读取,或调用 `.body()`。如果保存的内容无法解析,原始字节仍会保留,但 CSS/XPath 方法会使用空文档。
+
+要按 URL 查找 API 流量,可以使用 `session.network.search(url_pattern=r'https://api\.example\.com/.*', limit=None)`。只需要某种请求类型时,再加上 `resource_type='fetch'` 或 `resource_type='xhr'`。
+
+记录器只读取并保存受支持的文本 `Content-Type` 响应体,包括 `text/*`、`+json`/`+xml` 类型及 SVG、JSON、XML、JavaScript、GraphQL 和 URL 编码的表单数据。二进制、未知类型或没有 `Content-Type` 的响应只保留元数据,不保留响应体字节。浏览器仍会正常加载资源。
+
+保存的响应字节来自 Playwright,可能与服务器最初发送的字节不同。如果字节是有效的 UTF-8,就按 UTF-8 读取,与 Playwright 一致;否则使用声明的字符集。响应头保持不变。
+
+被跳过、过大或无法读取的响应体返回 `b''`,原因保存在 `response.meta.get('body_note')`。非文本内容的说明是 `Non-text body; not saved.`。响应元数据和可用响应头仍会保留。已保存的文本,包括空文本,不带这个说明。HEAD 响应及状态码 204、205、304 的响应保持为空,也不带说明。
+
+历史记录的 `search`、`get` 和 `clear` 都是本地同步调用,即使使用异步会话也一样。只有响应转换并保存后,条目才会出现。浏览器事件在 Playwright 活动期间处理,异步记录还需要事件循环运行。读取历史记录不会等待正在进行的记录操作。
+
+关闭会话也不会等待记录操作。页面导航或浏览器上下文关闭时,尚未完成的记录可能丢失。已经保存的响应在关闭后仍可读取。
+
+默认最多保留 1,000 个请求。每个响应体最多 1 MiB,所有响应体合计最多 20 MiB。达到限制时会删除旧记录。这些响应体大小限制是固定的,不能通过会话参数修改。它们只限制保留的条目和响应字节,不限制浏览器总内存、并行记录、临时完整读取、解析后的 HTML 或请求体。
+
+#### 迁移到 v5 {#migrating-in-v5}
+
+v5 移除了 `capture_xhr` 和 `response.captured_xhr`。请创建独立的浏览器会话,设置 `record_requests=True`,再读取 `session.network.search(url_pattern=..., limit=None)`。这也替代了单次 Fetcher 调用的 API 记录方式,所以需要保留会话实例。过滤条件应用于整个会话的已保存历史,而不是记录阶段或某一次抓取。只保存受支持的文本响应体。`search()` 默认最多返回 100 个匹配项,`limit=None` 返回所有仍保留的匹配项,但不会改变历史记录的存储限制。
+
+### 浏览器请求头和区域设置 {#browser-headers-and-locale}
+
+```python
+page = StealthyFetcher.fetch(
+ 'https://example.com',
+ google_search=True,
+ useragent='Mozilla/5.0...',
+ locale='en-US',
+)
+```
+
+### 综合示例 {#general-example}
+```python
+from scrapling.fetchers import StealthyFetcher
+
+def scrape_dynamic_content():
+
+ page = StealthyFetcher.fetch(
+ 'https://example.com/dynamic',
+ network_idle=True,
+ wait_selector='.content'
+ )
+
+
+ content = page.css('.content')
+
+ return {
+ 'title': content.css('h1::text').get(),
+ 'items': [
+ item.text for item in content.css('.item')
+ ]
+ }
+```
+
+### 代理轮换 {#proxy-rotation}
+
+```python
+from scrapling.fetchers import StealthySession, ProxyRotator
+
+
+rotator = ProxyRotator([
+ "http://proxy1:8080",
+ "http://proxy2:8080",
+ "http://proxy3:8080",
+])
+
+
+with StealthySession(proxy_rotator=rotator, headless=True) as session:
+ page1 = session.fetch('https://example1.com')
+ page2 = session.fetch('https://example2.com')
+
+
+ page3 = session.fetch('https://example3.com', proxy='http://specific-proxy:8080')
+```
+
+!!! warning
+
+ 所有浏览器 Fetcher 及其会话默认使用持久浏览器上下文和标签页池。但浏览器无法为每个标签页单独设置代理。因此,使用 `ProxyRotator` 时,Fetcher 会为每个代理创建独立上下文,每个上下文只有一个标签页。任务完成后,标签页和对应上下文都会关闭。
+
+## 适用场景 {#when-to-use}
+
+以下情况适合使用 StealthyFetcher:
+
+- 需要绕过反机器人防护。
+- 需要可靠的浏览器指纹。
+- 需要完整的 JavaScript 支持。
+- 希望自动启用隐身功能。
+- 需要浏览器自动化。
+- 需要处理 Cloudflare 防护。
diff --git a/docs/locales/zh/index.md b/docs/locales/zh/index.md
new file mode 100644
index 0000000..7337e0b
--- /dev/null
+++ b/docs/locales/zh/index.md
@@ -0,0 +1,243 @@
+---
+title: "Scrapling:Python 网页抓取框架"
+description: "Scrapling:轻松抓取现代网站。"
+---
+
+<style>
+.md-typeset h1 {
+ display: none;
+}
+[data-md-color-scheme="default"] .only-dark { display: none; }
+[data-md-color-scheme="slate"] .only-light { display: none; }
+</style>
+
+<br/>
+<div align="center">
+ <a href="index.html" alt="封面">
+ <img alt="Scrapling" src="assets/cover_light.svg" class="only-light">
+ <img alt="Scrapling" src="assets/cover_dark.svg" class="only-dark">
+ </a>
+</div>
+
+<h2 align="center"><i>轻松抓取现代网站</i></h2><br>
+
+Scrapling 是一个 Python 网页抓取框架。它将快速 HTTP 请求、隐身浏览器、页面解析和并发爬取整合在一个库中。
+
+抓取静态页面、运行 JavaScript、操作网站,并从网站的 API 中提取数据。构建爬虫时,可以复用会话、轮换代理、自动重试、暂停和恢复任务,还能直接导出数据。
+
+可以在 Python 和终端中使用 Scrapling,也可以通过 MCP 服务器和 Agent Skill 让 AI 智能体使用它。从提取几个字段到将整个网站保存为整洁的 Markdown 文件,Scrapling 都能完成。
+
+## 用 Scrapling 能做什么 {#what-you-can-do-with-scrapling}
+
+- **[获取和操作页面](fetching/choosing.md)**:快速 HTTP 请求、隐身浏览器、JavaScript 渲染、处理 Cloudflare Turnstile 和 Interstitial、持久会话,以及记录后台 API 响应。
+- **[解析页面和提取数据](parsing/selection.md)**:使用 CSS、XPath、文本和正则表达式搜索,跟踪页面变化后的元素,查找相似元素,并输出整洁的 Markdown。
+- **[爬取和导出](spiders/getting-started.md)**:并发爬虫、代理轮换、重试、AutoThrottle、暂停和恢复、流式输出、现成的模板,以及 JSON、JSONL、CSV 和 XML 导出。
+- **[使用 AI 或终端抓取](ai/mcp-server.md)**:供 AI 智能体浏览网页和提取数据的 MCP 服务器、Agent Skill、CLI 命令和交互式 Shell。
+
+从单个页面开始:
+
+```python
+from scrapling.fetchers import Fetcher
+
+page = Fetcher.get('https://quotes.toscrape.com/')
+quotes = page.css('.quote .text::text').getall()
+print(quotes)
+```
+
+也可以用 Spider 抓取更多页面:
+
+```python
+from scrapling.spiders import Spider, Response
+
+class QuotesSpider(Spider):
+ name = "quotes"
+ start_urls = ["https://quotes.toscrape.com/"]
+
+ async def parse(self, response: Response):
+ for quote in response.css('.quote'):
+ yield {
+ "text": quote.css('.text::text').get(),
+ "author": quote.css('.author::text').get(),
+ }
+
+result = QuotesSpider().start()
+print(len(result.items))
+result.items.to_json("quotes.json")
+```
+
+这段代码输出 `10`,并将名言和作者保存到 `quotes.json`。
+
+## 主要赞助商 {#top-sponsors}
+
+--8<-- "sponsors.html"
+
+<i><sub>想在这里投放广告?点击[这里](https://github.com/sponsors/D4Vinci),选择一个方案,即可获得相应权益。</sub></i>
+
+## 主要功能 {#key-features}
+
+### Spider:完整的爬虫框架 {#spiders-a-full-crawling-framework}
+- 🕷️ **类似 Scrapy 的 Spider API**:使用 `start_urls`、异步 `parse` 回调,以及 `Request` 和 `Response` 对象定义爬虫。
+- ⚡ **并发爬取**:设置并发请求数、每个域名的并发上限,以及下载间隔。
+- 🔄 **多种会话**:在同一个爬虫中使用 HTTP 请求和隐身无头浏览器。按会话 ID 将请求交给不同的会话处理。
+- 💾 **暂停和恢复**:用 `crawldir` 保存待处理请求和已访问的 URL。按 Ctrl+C 安全暂停,再用同一个目录启动即可继续。
+- 📡 **流式输出**:通过 `async for item in spider.stream()` 在数据提取后立即接收它,并查看实时统计信息。适合界面、数据处理流程和长时间运行的任务。
+- 🛡️ **识别被拦截的请求**:自动检测并重试被拦截的请求,也可以自定义处理逻辑。
+- 🚦 **AutoThrottle**:根据网站的响应速度,自动调整每个域名的请求间隔。如果网站拦截请求或限制频率,就将间隔加倍,或遵守 `Retry-After` 指定的等待时间。之后再逐步加快。
+- 🤖 **遵守 robots.txt**:启用 `robots_txt_obey`,即可遵守 `Disallow`、`Crawl-delay` 和 `Request-rate`。规则按域名缓存。
+- 🧪 **开发模式**:首次运行时将响应保存到磁盘,之后直接复用。这样可以修改 `parse()`,而不必再次请求服务器。
+- 🧩 **现成的爬虫模板**:使用 `CrawlSpider` 按规则跟踪链接,使用 `SitemapSpider` 从 sitemap 或 robots.txt 开始爬取,使用 `XMLFeedSpider` 和 `CSVFeedSpider` 读取 XML、RSS 和 CSV 数据源,或使用 `ShopifySpider` 获取公开 Shopify 商店的商品,每个商品变体生成一条数据。
+- 🔗 **提取链接**:`LinkExtractor` 可用模式允许或排除链接,过滤域名和文件扩展名,用 CSS 或 XPath 限定范围,并规范化 URL。它既可配合模板使用,也可单独使用。
+- 📦 **内置导出**:用钩子和自己的处理流程导出数据,或使用内置的 JSON、JSONL、CSV 和 XML 方法:`result.items.to_json()`、`to_jsonl()`、`to_csv()` 和 `to_xml()`。
+
+### 使用会话获取页面 {#advanced-websites-fetching-with-session-support}
+- **HTTP 请求**:用 `Fetcher` 发送快速、隐蔽的 HTTP 请求。支持模拟浏览器的 TLS 指纹和请求头,也支持 HTTP/3。
+- **动态加载**:用 `StealthyFetcher` 的完整浏览器自动化功能抓取动态网站。支持 Playwright 的 Chromium 和 Google Chrome。
+- **绕过反爬检测**:`StealthyFetcher` 隐藏自动化特征并模拟浏览器指纹,能自动处理多种 Cloudflare Turnstile 和 Interstitial 验证。
+- **会话管理**:`FetcherSession` 和 `StealthySession` 可在多次请求之间保留 Cookie 和状态。
+- **代理轮换**:`ProxyRotator` 支持在所有会话类型中按顺序或自定义规则切换代理,也可以为单次请求指定代理。
+- **拦截域名和广告**:拦截指定域名及其子域名的请求,或启用浏览器 Fetcher 的广告拦截功能。内置列表包含约 3,500 个已知广告和跟踪域名。
+- **防止 DNS 泄漏**:启用 DNS-over-HTTPS,通过 Cloudflare 的 DoH 服务发送 DNS 查询,防止使用代理时泄漏 DNS。
+- **远程浏览器**:通过 CDP 和 `cdp_url` 连接已运行的浏览器,包括本机、远程服务器和浏览器服务商提供的浏览器。也可以用 `executable_path` 为任意浏览器 Fetcher 指定自己的 Chromium 程序。
+- **记录后台 API 响应**:在浏览器会话中启用 `record_requests=True`,再用 `session.network.search(limit=None)` 搜索已保存的响应。无需重复请求,即可读取多次页面访问中的 API 数据和 HTTP 错误。历史记录有大小上限,只保存文本响应的内容。
+- **异步支持**:所有 Fetcher 都支持异步操作,并提供专用的异步会话类。
+
+### 解析页面和提取数据 {#parsing-and-data-extraction}
+- 🔄 **重新定位元素**:网站结构改变后,用相似度算法重新找到元素。
+- 🎯 **灵活选择**:支持 CSS、XPath、过滤器、文本、正则表达式等方式。
+- 🔍 **相似元素**:自动查找与已选元素相似的元素。
+
+### AI 功能 {#ai-features}
+- 🤖 **MCP 服务器**:让 Claude、Cursor 等 AI 助手和智能体通过 Scrapling 提取数据。支持 HTTP 请求、浏览器操作、截图、保存的登录状态和后台 API 响应。它使用我们的隐身浏览器,并提供工具,让具备相应能力的模型处理 CAPTCHA,补充内置的 Cloudflare 验证处理功能。它还减少发送给模型的内容、拦截广告,并防护提示词注入。支持通过 CDP 连接远程浏览器,也支持带身份验证选项的 HTTP 连接。([演示视频](https://www.youtube.com/watch?v=qyFk3ZNwOxE))
+- 🧠 **Agent Skill**:可安装的 [Agent Skill](ai/agent-skill.md),帮助编程智能体了解这个库,并编写符合当前 API 的代码。
+- 📚 **用于 RAG 的 Markdown**:用一行代码(`page.markdown()`)将页面转成适合语言模型的整洁 Markdown,或用 `ContentSpider` 模板将整个网站保存为 Markdown 文件。无需语言模型。([文档](ai/building-rag-systems.md))
+
+### 快速且经过实际使用 {#high-performance-battle-tested-architecture}
+- 🚀 **速度快**:经过优化,性能超过大多数 Python 网页抓取库。
+- 🔋 **内存占用低**:使用优化的数据结构,并按需加载。
+- ⚡ **快速输出 JSON**:速度是标准库的 10 倍。
+- 🏗️ **经过实际检验**:测试覆盖率达 92%,全部代码都有类型注解。过去一年中,数百人每天用它提取数据。
+
+### 开发和数据提取工具 {#developerweb-scraper-friendly-experience}
+- 🎯 **交互式 Shell**:可选的 IPython Shell,内置 Scrapling、快捷命令和工具,方便快速开发抓取脚本。可将 curl 请求转成 Scrapling 请求,并在浏览器中查看结果。
+- 🚀 **命令行使用**:无需写代码,就能提取 URL 的内容。
+- 🛠️ **DOM 导航**:访问父元素、同级元素和子元素。
+- 🧬 **文本处理**:支持正则表达式、文本清理和优化的字符串操作。
+- 📝 **生成选择器**:为任意元素生成可靠的 CSS 和 XPath 选择器。
+- 🔌 **熟悉的 API**:与 Scrapy 和 BeautifulSoup 相似,并支持 Scrapy 和 Parsel 使用的伪元素。
+- 🤝 **直接集成 Scrapy**:给回调加上 `scrapling_response` 装饰器,就能用 Scrapling 解析器处理已有的 Scrapy 响应,无需重写程序。
+- 📘 **完整的类型注解**:帮助编辑器检查和补全代码。每次修改都会用 **PyRight** 和 **MyPy** 自动检查全部代码。
+- 🔋 **现成的 Docker 镜像**:每次发布新版本时,自动构建并发布包含所有浏览器的 Docker 镜像。
+
+
+## GitHub 星标 {#star-history}
+下图展示了 Scrapling 自发布以来的 GitHub 星标增长情况。
+
+<div id="chartContainer">
+ <a href="https://github.com/D4Vinci/Scrapling">
+ <img id="chartImage" alt="GitHub 星标增长历史" loading="lazy" src="https://api.star-history.com/svg?repos=D4Vinci/Scrapling&type=Date" height="400"/>
+ </a>
+</div>
+
+<script>
+const observer = new MutationObserver((mutations) => {
+ mutations.forEach((mutation) => {
+ if (mutation.attributeName === 'data-md-color-media') {
+ const colorMedia = document.body.getAttribute('data-md-color-media');
+ const isDarkScheme = document.body.getAttribute('data-md-color-scheme') === 'slate';
+ const chartImg = document.querySelector('#chartImage');
+ const baseUrl = 'https://api.star-history.com/svg?repos=D4Vinci/Scrapling&type=Date';
+
+ if (colorMedia === '(prefers-color-scheme)' ? isDarkScheme : colorMedia.includes('dark')) {
+ chartImg.src = `${baseUrl}&theme=dark`;
+ } else {
+ chartImg.src = baseUrl;
+ }
+ }
+ });
+});
+
+observer.observe(document.body, {
+ attributes: true,
+ attributeFilter: ['data-md-color-media', 'data-md-color-scheme']
+});
+</script>
+
+
+## 安装 {#installation}
+Scrapling 需要 Python 3.10 或更高版本:
+
+```bash
+pip install scrapling
+```
+
+!!! warning "注意"
+
+ 这个命令只安装解析器及其依赖,不包含 Fetcher 或命令行工具。仅安装这些依赖后,像上面的示例那样从 `scrapling.fetchers` 或 `scrapling.spiders` 导入内容,会出现 `ModuleNotFoundError`。要使用 Fetcher 或 Spider,请先按下文安装 Fetcher 的依赖。
+
+### 可选依赖 {#optional-dependencies}
+
+1. 要使用 Fetcher、相关类或下列扩展功能,请先安装 Fetcher 和浏览器的依赖:
+ ```bash
+ pip install "scrapling[fetchers]"
+
+ scrapling install # normal install
+ scrapling install --force # force reinstall
+ ```
+
+ 这会下载所有浏览器、所需的系统依赖,以及修改浏览器指纹的工具。
+
+ 也可以在 Python 代码中安装,无需运行命令:
+ ```python
+ from scrapling.cli import install
+
+ install([], standalone_mode=False) # normal install
+ install(["--force"], standalone_mode=False) # force reinstall
+ ```
+
+2. 扩展功能:
+
+
+ - 安装 MCP 服务器:
+ ```bash
+ pip install "scrapling[ai]"
+ ```
+ - 安装[构建 RAG 系统](ai/building-rag-systems.md)所需的依赖:
+ ```bash
+ pip install "scrapling[rag]"
+ ```
+ - 安装交互式 Shell 和 `extract` 命令:
+ ```bash
+ pip install "scrapling[shell]"
+ ```
+ - 安装所有功能:
+ ```bash
+ pip install "scrapling[all]"
+ ```
+ 如果要使用浏览器 Fetcher,请运行 `scrapling install`。HTTP 请求不需要安装浏览器。
+
+### Docker {#docker}
+也可以从 DockerHub 下载包含所有扩展功能和浏览器的 Docker 镜像:
+```bash
+docker pull pyd4vinci/scrapling
+```
+或从 GitHub 容器仓库下载:
+```bash
+docker pull ghcr.io/d4vinci/scrapling:latest
+```
+镜像基于仓库的主分支构建,由 GitHub Actions 自动发布。
+
+## 文档结构 {#how-the-documentation-is-organized}
+Scrapling 的文档较多,因此采用 [Diátaxis 文档体系](https://diataxis.fr/)来组织内容。
+
+## 支持项目 {#support}
+
+如果你喜欢 Scrapling,并希望支持它的开发:
+
+- ⭐ 给 [GitHub 仓库](https://github.com/D4Vinci/Scrapling)加星标。
+- 🚀 在 [Twitter](https://x.com/Scrapling_dev) 上关注我们,并加入 [Discord 社区](https://discord.gg/EMgGbDceNQ)。
+- 💝 [赞助项目,或请我喝杯咖啡](donate.md)。:wink:
+- 🐛 在 [GitHub Issues](https://github.com/D4Vinci/Scrapling/issues) 报告问题或提出功能建议。
+
+## 许可证 {#license}
+
+本项目使用 BSD-3 许可证。详情请查看 [LICENSE](https://github.com/D4Vinci/Scrapling/blob/main/LICENSE) 文件。
diff --git a/docs/locales/zh/integrations/scrapy.md b/docs/locales/zh/integrations/scrapy.md
new file mode 100644
index 0000000..dc2f585
--- /dev/null
+++ b/docs/locales/zh/integrations/scrapy.md
@@ -0,0 +1,64 @@
+---
+title: "在 Scrapy Spider 中使用 Scrapling 解析"
+description: "将 Scrapy 响应转换为 Scrapling 响应,或为回调添加装饰器。保留 Scrapy 爬虫,同时使用 Scrapling 选择器和自适应解析。"
+---
+
+# 将 Scrapling 集成到 Scrapy {#integrating-scrapling-into-scrapy}
+
+如果已有 Scrapy 项目,无需重写就能使用 Scrapling 的解析 API。这项集成会直接在 Spider 回调中,把 Scrapy 响应转换为 Scrapling [Response](../fetching/choosing.md#response-object) 对象。Scrapy 继续负责爬取,Scrapling 负责解析。
+
+!!! note "安装"
+
+ 这项集成可用于默认的 Scrapling 安装(`pip install scrapling`),无需扩展依赖。它只要求安装 Scrapy,而 Scrapy 项目本身已经满足这一条件。
+
+## 使用方法 {#usage}
+
+为任意 Spider 回调添加 `scrapling_response` 装饰器,回调收到的 `response` 参数就会变成 Scrapling 的 `Response`:
+
+```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()]:
+ card = quote.parent
+ yield {
+ "text": quote.get_all_text(strip=True),
+ "author": card.find("small", class_="author").text,
+ "tags": [tag.text for tag in card.find_all("a", class_="tag")],
+ }
+ next_page = response.css("li.next a::attr(href)").get()
+ if next_page:
+ yield scrapy.Request(response.urljoin(next_page), callback=self.parse)
+```
+
+装饰器支持 Scrapy 的所有回调类型:普通函数、生成器、协程和异步生成器。它会保留回调的类型、名称和文档字符串,因此 Scrapy 的回调检查和 Contracts 仍然正常工作。
+
+也可以向装饰器传入 [Selector](../parsing/main_classes.md#selector) 配置,它会转交给生成的 `Response`:
+
+```python
+ @scrapling_response(adaptive=True, keep_comments=True)
+ def parse_product(self, response):
+ ...
+```
+
+如果在回调之外持有 Scrapy 响应,例如在中间件或 Pipeline 中,可以直接调用转换函数:
+
+```python
+from scrapling.integrations.scrapy import convert_response
+
+scrapling_response = convert_response(scrapy_response, keep_comments=False)
+```
+
+## 注意事项 {#notes}
+
+- 像上面的示例一样,用 yield 输出 `scrapy.Request(response.urljoin(href))` 来访问后续页面。Scrapling 的 `Response.follow()` 创建的是 [Scrapling Spider 系统](../spiders/getting-started.md)的请求,Scrapy 无法处理。
+- 响应的 `meta` 字典会进行浅拷贝,因此其他中间件存入的对象仍然可用。例如,使用 `scrapy-playwright` 时,页面仍保存在 `response.meta["playwright_page"]` 中。
+- Cookie 会从原始 `Set-Cookie` 响应头中解析出来,并存入响应的 `cookies` 字典。
diff --git a/docs/locales/zh/overview.md b/docs/locales/zh/overview.md
new file mode 100644
index 0000000..922cc4c
--- /dev/null
+++ b/docs/locales/zh/overview.md
@@ -0,0 +1,341 @@
+---
+title: "Scrapling 入门:解析页面、HTTP 请求和隐身浏览器"
+description: "通过 CSS、XPath、文本搜索、HTTP 请求和隐身浏览器示例学习 Scrapling。"
+---
+
+# 开始使用 Scrapling {#get-started-with-scrapling}
+
+## 选择起点 {#pick-your-path}
+
+还不知道从哪里开始?根据你的任务选择:
+
+| 我想…… | 从这里开始 |
+|:---|:---|
+| **解析已有的 HTML** | [选择元素](parsing/selection.md):CSS、XPath 和文本搜索 |
+| **快速抓取页面**,试一试想法 | 选择并试用一个 [Fetcher](fetching/choosing.md),或打开[交互式 Shell](cli/interactive-shell.md) |
+| **构建能处理更多页面的爬虫** | [Spider](spiders/getting-started.md):并发爬取、多种会话、暂停和恢复 |
+| **不写代码就提取数据** | 使用[提取命令](cli/extract-commands.md),或将 [MCP 服务器](ai/mcp-server.md)连接到 AI 工具 |
+| **从其他库迁移** | [从 BeautifulSoup 迁移](tutorials/migrating_from_beautifulsoup.md),或查看[与 Scrapy 的对比](spiders/architecture.md#comparison-with-scrapy) |
+
+---
+
+先学习如何解析页面,再学习如何用浏览器获取页面、发送请求并解析响应。
+
+本页示例使用下面这个由 ChatGPT 生成的 HTML 文档:
+```python
+html_doc = """<html>
+ <head>
+ <title>Complex Web Page</title>
+ <style>
+ .hidden { display: none; }
+ </style>
+ </head>
+ <body>
+ <header>
+ <nav>
+ <ul>
+ <li> <a href="#home">Home</a> </li>
+ <li> <a href="#about">About</a> </li>
+ <li> <a href="#contact">Contact</a> </li>
+ </ul>
+ </nav>
+ </header>
+ <main>
+ <section id="products" schema='{"jsonable": "data"}'>
+ <h2>Products</h2>
+ <div class="product-list">
+ <article class="product" data-id="1">
+ <h3>Product 1</h3>
+ <p class="description">This is product 1</p>
+ <span class="price">$10.99</span>
+ <div class="hidden stock">In stock: 5</div>
+ </article>
+
+ <article class="product" data-id="2">
+ <h3>Product 2</h3>
+ <p class="description">This is product 2</p>
+ <span class="price">$20.99</span>
+ <div class="hidden stock">In stock: 3</div>
+ </article>
+
+ <article class="product" data-id="3">
+ <h3>Product 3</h3>
+ <p class="description">This is product 3</p>
+ <span class="price">$15.99</span>
+ <div class="hidden stock">Out of stock</div>
+ </article>
+ </div>
+ </section>
+
+ <section id="reviews">
+ <h2>Customer Reviews</h2>
+ <div class="review-list">
+ <div class="review" data-rating="5">
+ <p class="review-text">Great product!</p>
+ <span class="reviewer">John Doe</span>
+ </div>
+ <div class="review" data-rating="4">
+ <p class="review-text">Good value for money.</p>
+ <span class="reviewer">Jane Smith</span>
+ </div>
+ </div>
+ </section>
+ </main>
+ <script id="page-data" type="application/json">
+ {
+ "lastUpdated": "2024-09-22T10:30:00Z",
+ "totalProducts": 3
+ }
+ </script>
+ </body>
+</html>"""
+```
+先加载上面的 HTML:
+```python
+import re
+from scrapling.parser import Selector
+page = Selector(html_doc)
+page # <data='<html><head><title>Complex Web Page</tit...'>
+```
+获取页面中的全部文本,包括嵌套元素的文本:
+```python
+page.get_all_text(ignore_tags=('script', 'style'))
+# 'Complex Web Page\nHome\nAbout\nContact\nProducts\nProduct 1\nThis is product 1\n$10.99\nIn stock: 5\nProduct 2\nThis is product 2\n$20.99\nIn stock: 3\nProduct 3\nThis is product 3\n$15.99\nOut of stock\nCustomer Reviews\nGreat product!\nJohn Doe\nGood value for money.\nJane Smith'
+```
+
+## 查找元素 {#finding-elements}
+可以组合不同的方法,找到需要的元素。
+
+查找第一个 `section` HTML 元素:
+```python
+section_element = page.find('section')
+# <data='<section id="products" schema='{"jsonabl...' parent='<main><section id="products" schema='{"j...'>
+```
+查找所有 `section` 元素:
+```python
+section_elements = page.find_all('section')
+# [<data='<section id="products" schema='{"jsonabl...' parent='<main><section id="products" schema='{"j...'>, <data='<section id="reviews"><h2>Customer Revie...' parent='<main><section id="products" schema='{"j...'>]
+```
+查找 `id` 属性值为 `products` 的所有 `section` 元素:
+```python
+section_elements = page.find_all('section', {'id':"products"})
+# Same as
+section_elements = page.find_all('section', id="products")
+# [<data='<section id="products" schema='{"jsonabl...' parent='<main><section id="products" schema='{"j...'>]
+```
+查找 `id` 属性值包含 `product` 的所有 `section` 元素:
+```python
+section_elements = page.find_all('section', {'id*':"product"})
+```
+查找文本匹配正则表达式 `Product \d` 的 `h3` 元素:
+```python
+page.find_all('h3', re.compile(r'Product \d'))
+# [<data='<h3>Product 1</h3>' parent='<article class="product" data-id="1"><h3...'>, <data='<h3>Product 2</h3>' parent='<article class="product" data-id="2"><h3...'>, <data='<h3>Product 3</h3>' parent='<article class="product" data-id="3"><h3...'>]
+```
+查找文本匹配正则表达式 `Product` 的 `h3` 和 `h2` 元素:
+```python
+page.find_all(['h3', 'h2'], re.compile(r'Product'))
+# [<data='<h3>Product 1</h3>' parent='<article class="product" data-id="1"><h3...'>, <data='<h3>Product 2</h3>' parent='<article class="product" data-id="2"><h3...'>, <data='<h3>Product 3</h3>' parent='<article class="product" data-id="3"><h3...'>, <data='<h2>Products</h2>' parent='<section id="products" schema='{"jsonabl...'>]
+```
+查找文本正好是 `Products` 的元素,忽略空白字符:
+```python
+page.find_by_text('Products', first_match=False)
+# [<data='<h2>Products</h2>' parent='<section id="products" schema='{"jsonabl...'>]
+```
+也可以查找文本匹配正则表达式 `Product \d` 的元素:
+```python
+page.find_by_regex(r'Product \d', first_match=False)
+# [<data='<h3>Product 1</h3>' parent='<article class="product" data-id="1"><h3...'>, <data='<h3>Product 2</h3>' parent='<article class="product" data-id="2"><h3...'>, <data='<h3>Product 3</h3>' parent='<article class="product" data-id="3"><h3...'>]
+```
+查找与当前元素相似的元素:
+```python
+target_element = page.find_by_regex(r'Product \d', first_match=True)
+# <data='<h3>Product 1</h3>' parent='<article class="product" data-id="1"><h3...'>
+target_element.find_similar()
+# [<data='<h3>Product 2</h3>' parent='<article class="product" data-id="2"><h3...'>, <data='<h3>Product 3</h3>' parent='<article class="product" data-id="3"><h3...'>]
+```
+查找匹配 CSS 选择器的第一个元素:
+```python
+page.css('.product-list [data-id="1"]')[0]
+# <data='<article class="product" data-id="1"><h3...' parent='<div class="product-list"> <article clas...'>
+```
+查找匹配 CSS 选择器的所有元素:
+```python
+page.css('.product-list article')
+# [<data='<article class="product" data-id="1"><h3...' parent='<div class="product-list"> <article clas...'>, <data='<article class="product" data-id="2"><h3...' parent='<div class="product-list"> <article clas...'>, <data='<article class="product" data-id="3"><h3...' parent='<div class="product-list"> <article clas...'>]
+```
+查找匹配 XPath 选择器的第一个元素:
+```python
+page.xpath("//*[@id='products']/div/article")[0]
+# <data='<article class="product" data-id="1"><h3...' parent='<div class="product-list"> <article clas...'>
+```
+查找匹配 XPath 选择器的所有元素:
+```python
+page.xpath("//*[@id='products']/div/article")
+# [<data='<article class="product" data-id="1"><h3...' parent='<div class="product-list"> <article clas...'>, <data='<article class="product" data-id="2"><h3...' parent='<div class="product-list"> <article clas...'>, <data='<article class="product" data-id="3"><h3...' parent='<div class="product-list"> <article clas...'>]
+```
+
+这些是基本用法。后面会介绍各个选择方法的更多选项。
+## 读取元素数据 {#accessing-elements-data}
+可以这样读取数据:
+```pycon
+>>> section_element.tag
+'section'
+>>> print(section_element.attrib)
+{'id': 'products', 'schema': '{"jsonable": "data"}'}
+>>> section_element.attrib['schema'].json() # If an attribute value can be converted to json, then use `.json()` to convert it
+{'jsonable': 'data'}
+>>> section_element.text # Direct text content
+''
+>>> section_element.get_all_text() # All text content recursively
+'Products\nProduct 1\nThis is product 1\n$10.99\nIn stock: 5\nProduct 2\nThis is product 2\n$20.99\nIn stock: 3\nProduct 3\nThis is product 3\n$15.99\nOut of stock'
+>>> section_element.html_content # The HTML content of the element
+'<section id="products" schema=\'{"jsonable": "data"}\'><h2>Products</h2>\n <div class="product-list">\n <article class="product" data-id="1"><h3>Product 1</h3>\n <p class="description">This is product 1</p>\n <span class="price">$10.99</span>\n <div class="hidden stock">In stock: 5</div>\n </article><article class="product" data-id="2"><h3>Product 2</h3>\n <p class="description">This is product 2</p>\n <span class="price">$20.99</span>\n <div class="hidden stock">In stock: 3</div>\n </article><article class="product" data-id="3"><h3>Product 3</h3>\n <p class="description">This is product 3</p>\n <span class="price">$15.99</span>\n <div class="hidden stock">Out of stock</div>\n </article></div>\n </section>'
+>>> print(section_element.prettify()) # The prettified version
+'''
+<section id="products" schema='{"jsonable": "data"}'><h2>Products</h2>
+ <div class="product-list">
+ <article class="product" data-id="1"><h3>Product 1</h3>
+ <p class="description">This is product 1</p>
+ <span class="price">$10.99</span>
+ <div class="hidden stock">In stock: 5</div>
+ </article><article class="product" data-id="2"><h3>Product 2</h3>
+ <p class="description">This is product 2</p>
+ <span class="price">$20.99</span>
+ <div class="hidden stock">In stock: 3</div>
+ </article><article class="product" data-id="3"><h3>Product 3</h3>
+ <p class="description">This is product 3</p>
+ <span class="price">$15.99</span>
+ <div class="hidden stock">Out of stock</div>
+ </article>
+ </div>
+</section>
+'''
+>>> section_element.path # All the ancestors in the DOM tree of this element
+[<data='<main><section id="products" schema='{"j...' parent='<body> <header><nav><ul><li> <a href="#h...'>,
+ <data='<body> <header><nav><ul><li> <a href="#h...' parent='<html><head><title>Complex Web Page</tit...'>,
+ <data='<html><head><title>Complex Web Page</tit...'>]
+>>> section_element.generate_css_selector
+'#products'
+>>> section_element.generate_full_css_selector
+'body > main > #products'
+>>> section_element.generate_xpath_selector
+"//*[@id='products']"
+>>> section_element.generate_full_xpath_selector
+"//body/main/*[@id='products']"
+```
+
+## 导航 {#navigation}
+使用前面找到的元素:
+
+```pycon
+>>> section_element.parent
+<data='<main><section id="products" schema='{"j...' parent='<body> <header><nav><ul><li> <a href="#h...'>
+>>> section_element.parent.tag
+'main'
+>>> section_element.parent.parent.tag
+'body'
+>>> section_element.children
+[<data='<h2>Products</h2>' parent='<section id="products" schema='{"jsonabl...'>,
+ <data='<div class="product-list"> <article clas...' parent='<section id="products" schema='{"jsonabl...'>]
+>>> section_element.siblings
+[<data='<section id="reviews"><h2>Customer Revie...' parent='<main><section id="products" schema='{"j...'>]
+>>> section_element.next # gets the next element, the same logic applies to `quote.previous`.
+<data='<section id="reviews"><h2>Customer Revie...' parent='<main><section id="products" schema='{"j...'>
+>>> section_element.children.css('h2::text').getall()
+['Products']
+>>> page.css('[data-id="1"]')[0].has_class('product')
+True
+```
+除了访问父元素,还可以遍历元素的所有祖先:
+```python
+for ancestor in section_element.iterancestors():
+ print(ancestor.tag)
+```
+也可以查找符合条件的祖先元素。传入一个函数,接收 `Selector` 对象,符合条件时返回 `True`,否则返回 `False`:
+```pycon
+>>> section_element.find_ancestor(lambda ancestor: ancestor.css('nav'))
+<data='<body> <header><nav><ul><li> <a href="#h...' parent='<html><head><title>Complex Web Page</tit...'>
+```
+
+## 获取网页 {#fetching-websites}
+除了将 HTML 传给 Scrapling,还可以通过 HTTP 请求或浏览器获取网站的响应。
+
+根据任务选择合适的 Fetcher。
+
+### HTTP 请求 {#http-requests}
+导入并使用 `Fetcher` 类发送 HTTP 请求:
+```python
+from scrapling.fetchers import Fetcher
+page = Fetcher.get('https://scrapling.requestcatcher.com/get', impersonate="chrome")
+```
+下面展示了不同的 HTTP 方法:
+```python
+from scrapling.fetchers import Fetcher
+page = Fetcher.get('https://scrapling.requestcatcher.com/get', stealthy_headers=True)
+page = Fetcher.post('https://scrapling.requestcatcher.com/post', data={'key': 'value'}, proxy='http://username:password@localhost:8030')
+page = Fetcher.put('https://scrapling.requestcatcher.com/put', data={'key': 'value'})
+page = Fetcher.delete('https://scrapling.requestcatcher.com/delete')
+```
+要使用异步请求,只需修改导入:
+```python
+from scrapling.fetchers import AsyncFetcher
+page = await AsyncFetcher.get('https://scrapling.requestcatcher.com/get', stealthy_headers=True)
+page = await AsyncFetcher.post('https://scrapling.requestcatcher.com/post', data={'key': 'value'}, proxy='http://username:password@localhost:8030')
+page = await AsyncFetcher.put('https://scrapling.requestcatcher.com/put', data={'key': 'value'})
+page = await AsyncFetcher.delete('https://scrapling.requestcatcher.com/delete')
+```
+
+!!! note "说明"
+
+ 1. `stealthy_headers` 生成真实浏览器的请求头,包括 Google Referer,默认启用。
+ 2. `impersonate` 可以模拟指定浏览器版本的 TLS 指纹。
+ 3. `http3` 启用 HTTP/3,让请求更接近真实浏览器。
+
+更多选项请查看 [HTTP 请求指南](fetching/static.md)。
+
+### 动态加载 {#dynamic-loading}
+也可以处理用 JavaScript 加载内容的网站。
+
+`StealthyFetcher` 提供多种选项,通过基于 Chromium 的浏览器获取和加载页面。
+```python
+from scrapling.fetchers import StealthyFetcher
+page = StealthyFetcher.fetch('https://quotes.toscrape.com/js/', disable_resources=True, block_ads=True, wait_selector='.quote')
+print(len(page.css(".quote"))) # -> 10
+
+# The async version of fetch
+page = await StealthyFetcher.async_fetch('https://quotes.toscrape.com/js/', disable_resources=True, block_ads=True, wait_selector='.quote')
+print(len(page.css(".quote"))) # -> 10
+```
+它使用经过修改的 [Playwright](https://playwright.dev/python/),隐藏自动化特征。可以使用自带的 Chromium,通过 `real_chrome=True` 使用已安装的 Google Chrome,或通过 `cdp_url` 连接正在运行的浏览器。
+
+### 反检测功能 {#anti-bot-features}
+
+包括以下功能:
+
+1. 设置 `solve_cloudflare=True`,自动处理多种 Cloudflare Turnstile 和 Interstitial 验证。
+2. 防止 CDP Runtime 和 WebRTC 泄漏。
+3. 隔离 JavaScript 执行环境,移除许多 Playwright 特征,并避免一些常见的机器人行为检测。
+4. 在 Canvas 中加入噪声,防止它被用于识别浏览器指纹。
+5. 修复已知的无头浏览器检测问题,并可防止因时区不一致而被识别。
+6. 提供更多避免检测的选项。
+
+```python
+from scrapling.fetchers import StealthyFetcher
+page = StealthyFetcher.fetch('https://www.browserscan.net/bot-detection') # Running headless by default
+page.status == 200 # -> True
+
+page = StealthyFetcher.fetch('https://nopecha.com/demo/cloudflare', solve_cloudflare=True) # Solve Cloudflare captcha automatically if presented
+page.status == 200 # -> True
+
+page = StealthyFetcher.fetch('https://www.browserscan.net/bot-detection', block_webrtc=True, hide_canvas=True, dns_over_https=True) # and the rest of arguments...
+# The async version of fetch
+page = await StealthyFetcher.async_fetch('https://www.browserscan.net/bot-detection')
+page.status == 200 # -> True
+```
+
+详情和完整参数列表见[浏览器指南](fetching/stealthy.md)。
+
+---
+
+以上是 Scrapling 的基本用法。下一节会介绍更多功能。
diff --git a/docs/locales/zh/parsing/adaptive.md b/docs/locales/zh/parsing/adaptive.md
new file mode 100644
index 0000000..cb18115
--- /dev/null
+++ b/docs/locales/zh/parsing/adaptive.md
@@ -0,0 +1,232 @@
+---
+title: "使用自适应解析跟踪并重新定位 HTML 元素"
+description: "保存元素特征,在 HTML 变化后重新找到元素。了解如何启用自适应解析,以及如何使用 save、retrieve 和 relocate。"
+---
+
+# 自适应抓取 {#adaptive-scraping}
+
+!!! success "前提条件"
+
+ 1. 已阅读[查询元素](../parsing/selection.md),了解如何从 [Selector](../parsing/main_classes.md#selector) 对象中查找和提取元素。
+ 2. 已阅读[主要类](../parsing/main_classes.md),了解 [Selector](../parsing/main_classes.md#selector) 类。
+
+自适应抓取以前称为 automatch,是 Scrapling 最强大的功能之一。它会跟踪并重新定位元素,让爬虫在网站变化后仍能继续工作。
+
+假设要抓取的页面结构如下:
+```html
+<div class="container">
+ <section class="products">
+ <article class="product" id="p1">
+ <h3>Product 1</h3>
+ <p class="description">Description 1</p>
+ </article>
+ <article class="product" id="p2">
+ <h3>Product 2</h3>
+ <p class="description">Description 2</p>
+ </article>
+ </section>
+</div>
+```
+要抓取第一个产品,也就是 ID 为 `p1` 的元素,可能会写出这样的选择器:
+```python
+page.css('#p1')
+```
+如果网站维护者把结构改成这样:
+```html
+<div class="new-container">
+ <div class="product-wrapper">
+ <section class="products">
+ <article class="product new-class" data-id="p1">
+ <div class="product-info">
+ <h3>Product 1</h3>
+ <p class="new-description">Description 1</p>
+ </div>
+ </article>
+ <article class="product new-class" data-id="p2">
+ <div class="product-info">
+ <h3>Product 2</h3>
+ <p class="new-description">Description 2</p>
+ </div>
+ </article>
+ </section>
+ </div>
+</div>
+```
+选择器就无法工作了,需要修改代码。这时就可以用到 Scrapling 的 `adaptive` 功能。
+
+第一次选择元素时,可以启用 `adaptive` 功能。下次使用同一选择器却找不到元素时,Scrapling 会根据之前保存的特征,在网站中寻找相似度最高的元素。整个过程不需要 AI :)
+
+```python
+from scrapling import Selector, Fetcher
+# Before the change
+page = Selector(page_source, adaptive=True, url='example.com')
+# or
+Fetcher.adaptive = True
+page = Fetcher.get('https://example.com')
+# then
+element = page.css('#p1', auto_save=True)
+if not element: # One day website changes?
+ element = page.css('#p1', adaptive=True) # Scrapling still finds it!
+# the rest of your code...
+```
+下面先用一个例子展示这项功能,再详细介绍它的用法和原理。它适用于所有选择方式,不只是 CSS/XPath。
+
+## 实际场景 {#real-world-scenario}
+我们用一个真实网站作为例子,并通过 Fetcher 获取它的源码。理想情况下,要先找到一个即将修改设计或结构的网站,保存源码,再等待它发生变化。当然,除非认识网站维护者,否则几乎不可能提前知道。但那样又像是安排好的测试了,哈哈。
+
+所以,我会使用 [The Web Archive](https://archive.org/) 的 [Wayback Machine](https://web.archive.org/)。这是 [StackOverFlow 网站在 2010 年的副本](https://web.archive.org/web/20100102003420/http://stackoverflow.com/),很老了吧?</br>看看自适应功能能否用同一个选择器,从 2010 年的旧版页面和当前页面中找到同一个按钮 :)
+
+要从旧版页面中提取 Questions 按钮,可以使用这个选择器:`#hmenus > div:nth-child(1) > ul > li:nth-child(1) > a`。它由 Google Chrome 生成,所以对结构的要求很具体。
+
+
+现在,在两个版本中测试同一个选择器:
+```python
+from scrapling import Fetcher
+selector = '#hmenus > div:nth-child(1) > ul > li:nth-child(1) > a'
+old_url = "https://web.archive.org/web/20100102003420/http://stackoverflow.com/"
+new_url = "https://stackoverflow.com/"
+Fetcher.configure(adaptive = True, adaptive_domain='stackoverflow.com')
+page = Fetcher.get(old_url, timeout=30)
+element1 = page.css(selector, auto_save=True)[0]
+# Same selector but used in the updated website
+page = Fetcher.get(new_url)
+element2 = page.css(selector, adaptive=True)[0]
+
+if element1.text == element2.text:
+ print('Scrapling found the same element in the old and new designs!') # Spoiler alert: it does!
+```
+这里新增了一个参数 `adaptive_domain`。因为对 Scrapling 来说,`archive.org` 和 `stackoverflow.com` 是两个不同的域名,它会分别保存它们的 `adaptive` 数据。为告诉 Scrapling 这是同一个网站,需要在保存两边的 `adaptive` 数据时指定同一个自定义域名。
+
+在实际场景中,代码基本相同,只是两次请求使用相同的 URL,因此不需要 `adaptive_domain`。这是我能给出的最接近实际情况的例子,希望这个例子足够清楚 :)
+
+上面的两个例子分别使用了 `Selector` 和 `Fetcher`,说明它们的自适应逻辑相同。
+
+!!! info
+
+ `adaptive_domain` 主要用于网站在修改设计或结构时也更换 URL 的情况。通过它,可以在新 URL 上继续使用之前保存的自适应数据。否则,Scrapling 会把它当成新网站,不再使用旧数据。
+
+## 自适应抓取的原理 {#how-the-adaptive-scraping-feature-works}
+自适应抓取分为两个阶段:
+
+1. **保存阶段**:保存元素的特征。
+2. **匹配阶段**:之后查找具有相似特征的元素。
+
+假设已经通过任意方式选中了一个元素,并希望下次抓取时,即使网站结构或设计变了,库也能找到它。
+
+尽量不涉及复杂细节,整个流程如下:
+
+ 1. 通过下面介绍的方式,让 Scrapling 保存元素的特征。
+ 2. Scrapling 使用配置的数据库,默认为 SQLite,保存每个元素的特征。
+ 3. 网站维护者可以修改或删除元素的任何信息,因此不能把元素本身的某个属性作为数据库中的固定标识。为解决这个问题,存储系统使用两项信息:
+ 1. 当前网站的域名。如果使用 `Selector`,需要在初始化时传入;如果使用 Fetcher,则会自动从 URL 获取。
+ 2. 用于从数据库查询元素特征的 `identifier`。不必每次都手动设置这个标识符,后面会详细说明。
+
+ 之后会结合这两项信息,从数据库中读取元素的特征。
+
+ 4. 网站结构变化后,启用 `adaptive` 来查找元素。Scrapling 会读取已保存的特征,并与页面上的所有元素进行比较,根据相似程度计算得分。比较时会考虑所有特征,后面会具体说明。
+ 5. 返回与目标元素相似度最高的元素。
+
+### 元素特征 {#the-unique-properties}
+既然元素的任何属性都可能被删除或修改,这里所说的特征到底是什么?
+
+Scrapling 使用以下信息:
+
+- 元素的标签名、文本、属性名称和值、同级元素的标签名,以及路径中的标签名。
+- 父元素的标签名、属性名称和值,以及文本。
+
+这些信息不需要完全相同,Scrapling 比较的是相似程度。它会考虑各种细节,包括值的顺序,例如元素类名在变化前后的排列顺序。
+
+## 使用自适应功能 {#how-to-use-adaptive-feature}
+自适应功能可以用于任何已找到的元素。它也作为参数集成在 CSS/XPath 选择方法中,上面的例子已经展示过,稍后会再说明。
+
+首先需要启用 `adaptive`。创建 [Selector](main_classes.md#selector) 时传入 `adaptive=True`,或者在所用的 Fetcher 中启用它,如下所示。
+
+示例:
+```python
+from scrapling import Selector, Fetcher
+page = Selector(html_doc, adaptive=True)
+# OR
+Fetcher.adaptive = True
+page = Fetcher.get('https://example.com')
+```
+使用 [Selector](main_classes.md#selector) 时,需要通过 `url` 传入网站 URL,让 Scrapling 按域名区分各元素保存的特征。
+
+如果不传 URL,保存元素特征时会用 `default` 作为 URL 字段的值。只有在之后对其他网站使用同一个标识符,且仍未传入 URL 时,才会出问题。新的保存操作会覆盖旧数据,`adaptive` 只使用最近保存的特征。
+
+此外还有 `storage` 和 `storage_args`,用于设置数据库连接。默认使用库提供的 SQLite 类。只有需要编写自己的存储系统时才需要关注这两个参数,相关内容在[开发部分的单独页面](../development/adaptive_storage_system.md)中介绍。
+
+全局启用 `adaptive` 后,主要有两种使用方式。
+
+### 通过 CSS/XPath 选择 {#the-cssxpath-selection-way}
+如上面的例子所示,先在选择页面上存在的元素时使用 `auto_save`:
+```python
+element = page.css('#p1', auto_save=True)
+```
+之后找不到元素时,使用相同的选择器并传入 `adaptive`,库就会尝试重新找到它:
+```python
+element = page.css('#p1', adaptive=True)
+```
+很简单吧?
+
+其实背后做了不少工作。还记得用于读取元素特征的标识符吗?为方便使用,`css`/`xpath` 方法会自动把传入的选择器作为标识符 :)
+
+也可以向这些方法传入 `identifier`,自己指定标识符。这在某些场景中很有用,也可以与 `auto_save` 一起使用来保存特征。
+
+### 手动处理 {#the-manual-way}
+也可以手动保存元素、读取特征,再重新定位。如下所示,这些操作同样属于 `adaptive` 功能。这样就能重新定位通过任意方法选中的元素。
+
+假设通过文本找到了一个元素:
+```python
+element = page.find_by_text('Tipping the Velvet', first_match=True)
+```
+使用 `save` 保存它的特征,但需要自己指定标识符。这里选择 `my_special_element`。实际代码中应使用有意义的名称,就像给变量起名一样 :)
+```python
+page.save(element, 'my_special_element')
+```
+之后需要读取特征,并通过 `adaptive` 在页面中重新定位时,可以这样写:
+```python
+>>> element_dict = page.retrieve('my_special_element')
+>>> page.relocate(element_dict, selector_type=True)
+[<data='<a href="catalogue/tipping-the-velvet_99...' parent='<h3><a href="catalogue/tipping-the-velve...'>]
+>>> page.relocate(element_dict, selector_type=True).css('::text').getall()
+['Tipping the Velvet']
+```
+这里使用了 `retrieve` 和 `relocate` 方法。
+
+如果希望保留 `lxml.etree` 对象,不要传入 `selector_type`:
+```python
+>>> page.relocate(element_dict)
+[<Element a at 0x105a2a7b0>]
+```
+
+## 排查问题 {#troubleshooting}
+
+### 找不到匹配元素 {#no-matches-found}
+```python
+# 1. Check if data was saved
+element_data = page.retrieve('identifier')
+if not element_data:
+ print("No data saved for this identifier")
+
+# 2. Try with different identifier
+products = page.css('.product', adaptive=True, identifier='old_selector')
+
+# 3. Save again with new identifier
+products = page.css('.new-product', auto_save=True, identifier='new_identifier')
+```
+
+### 匹配到了错误元素 {#wrong-elements-matched}
+```python
+# Use more specific selectors
+products = page.css('.product-list .product', auto_save=True)
+
+# Or save with more context
+product = page.find_by_text('Product Name').parent
+page.save(product, 'specific_product')
+```
+
+## 已知问题 {#known-issues}
+`adaptive` 保存时只记录选择结果中第一个元素的特征。如果选择器选中了页面上不同位置的多个元素,之后用 `adaptive` 重新定位时只会找回第一个。这不影响组合 CSS 选择器,例如用逗号连接的多个选择器,因为它们会被拆开并分别执行。
+
+## 最后说明 {#final-thoughts}
+要把这项功能讲清楚,又不让内容太复杂,并不容易。如果还有不明白的地方,可以到[讨论区](https://github.com/D4Vinci/Scrapling/discussions)提问,我会尽快回复。也可以使用 Discord 服务器,或直接联系我聊聊 :)
\ No newline at end of file
diff --git a/docs/locales/zh/parsing/main_classes.md b/docs/locales/zh/parsing/main_classes.md
new file mode 100644
index 0000000..547232d
--- /dev/null
+++ b/docs/locales/zh/parsing/main_classes.md
@@ -0,0 +1,573 @@
+---
+title: "Scrapling 的 Selector 和 Selectors:数据与导航"
+description: "了解 Selector 和 Selectors 如何保存 HTML、文本和属性。提取值、解析 URL,并在父元素、子元素和同级元素之间导航。"
+---
+
+# 解析器的主要类 {#parsing-main-classes}
+
+!!! success "前提条件"
+
+ - 已阅读[查询元素](../parsing/selection.md),了解如何从 [Selector](../parsing/main_classes.md#selector) 对象中查找和提取元素。
+
+了解各种元素选择方式后,我们再整体看看 [Selector](#selector) 和其他对象,以便更好地理解解析引擎。
+
+[Selector](#selector) 是 Scrapling 解析引擎的核心,负责解析 HTML 和选择元素。可以通过以下任意方式导入:
+```python
+from scrapling import Selector
+from scrapling.parser import Selector
+```
+然后像[概览](../overview.md)中介绍的那样直接使用:
+```python
+page = Selector(
+ '<html>...</html>',
+ url='https://example.com'
+)
+
+# Then select elements as you like
+elements = page.css('.product')
+```
+传入 HTML 源码或获取网站后,主要操作的就是 [Selector](#selector) 对象。选择、导航等操作只要返回的是页面元素,而不是文本等其他内容,就会返回 [Selector](#selector) 或 [Selectors](#selectors) 对象。
+
+也就是说,整个页面是一个 [Selector](#selector) 对象,里面的各个元素也是 [Selector](#selector) 对象。元素文本和属性值等文本内容是 [TextHandler](#texthandler) 对象。每个元素的属性集合保存在 [AttributesHandler](#attributeshandler) 中。这两个类稍后再讲,先来看 [Selector](#selector)。
+
+## Selector {#selector}
+### 参数说明 {#arguments-explained}
+最重要的参数是 `content`,用于传入要解析的 HTML,支持 `str` 和 `bytes`。
+
+`url` 设置页面 URL,用于解析相对链接,并按域名区分已保存的自适应数据。`adaptive`、`storage` 和 `storage_args` 与[自适应功能](adaptive.md)有关。不使用该功能时,这些参数不会产生影响。
+
+还有一些参数用于调整解析过程,或控制解析时如何处理 HTML:
+
+- **encoding**:解析 HTML 使用的编码,默认为 `UTF-8`。
+- **keep_comments**:解析时是否保留 HTML 注释。默认关闭,因为注释可能以多种方式影响抓取。
+
+这里先不介绍 `huge_tree` 和 `root`,避免让这页变得过于复杂。
+类似的高级功能会暂时略过,因为正常使用库时并不需要了解它们。如果想深入研究,可以阅读开发部分。
+
+页面和元素的大多数属性都采用延迟加载,只有使用时才会初始化,例如页面或元素的文本内容。这也是 Scrapling 速度快的原因之一 :)
+
+### 属性 {#properties}
+[概览](../overview.md)已经展示过不少内容。没看过也不用担心,这里会结合更多方法和用法详细介绍。为了便于阅读,用于遍历的属性放在后面的[遍历](#traversal)部分。
+
+为方便演示,假设要解析以下 HTML 页面:
+```html
+<html>
+ <head>
+ <title>Some page</title>
+ </head>
+ <body>
+ <div class="product-list">
+ <article class="product" data-id="1">
+ <h3>Product 1</h3>
+ <p class="description">This is product 1</p>
+ <span class="price">$10.99</span>
+ <div class="hidden stock">In stock: 5</div>
+ </article>
+
+ <article class="product" data-id="2">
+ <h3>Product 2</h3>
+ <p class="description">This is product 2</p>
+ <span class="price">$20.99</span>
+ <div class="hidden stock">In stock: 3</div>
+ </article>
+
+ <article class="product" data-id="3">
+ <h3>Product 3</h3>
+ <p class="description">This is product 3</p>
+ <span class="price">$15.99</span>
+ <div class="hidden stock">Out of stock</div>
+ </article>
+ </div>
+
+ <script id="page-data" type="application/json">
+ {
+ "lastUpdated": "2024-09-22T10:30:00Z",
+ "totalProducts": 3
+ }
+ </script>
+ </body>
+</html>
+```
+像前面那样直接加载页面:
+```python
+from scrapling import Selector
+page = Selector(html_doc)
+```
+递归获取页面的全部文本,包括嵌套元素中的文本:
+```python
+>>> page.get_all_text()
+'Some page\n\n \n\n \nProduct 1\nThis is product 1\n$10.99\nIn stock: 5\nProduct 2\nThis is product 2\n$20.99\nIn stock: 3\nProduct 3\nThis is product 3\n$15.99\nOut of stock'
+```
+按前面介绍的方法获取第一篇文章,作为接下来的示例:
+```python
+article = page.find('article')
+```
+同样可以递归获取该元素中的全部文本:
+```python
+>>> article.get_all_text()
+'Product 1\nThis is product 1\n$10.99\nIn stock: 5'
+```
+但它的直接文本内容为空,因为上面的 HTML 中,这个元素没有直接文本:
+```python
+>>> article.text
+''
+```
+`get_all_text` 有以下可选参数:
+
+1. **separator**:使用这个分隔符连接所有收集到的字符串,默认为 '\n'。
+2. **strip**:连接前移除字符串首尾的空白,默认关闭。
+3. **ignore_tags**:需要忽略的标签名元组,标签内的所有嵌套元素也会被忽略。默认为 `('script', 'style',)`。
+4. **valid_values**:只收集有实际文本的元素,忽略空文本或只有空白的元素。默认开启。
+
+这里返回的文本不是普通字符串,而是 [TextHandler](#texthandler),后面会详细介绍。如果文本可以解析为 JSON,可以直接调用 `.json()`:
+```python
+>>> script = page.find('script')
+>>> script.json()
+{'lastUpdated': '2024-09-22T10:30:00Z', 'totalProducts': 3}
+```
+接着获取元素的标签名:
+```python
+>>> article.tag
+'article'
+```
+如果直接对页面执行这个操作,得到的是根元素 `html`:
+```python
+>>> page.tag
+'html'
+```
+现在应该已经理解 `page` 和 `element` 的关系,后面就不再重复了。
+
+获取元素的属性集合:
+```python
+>>> print(article.attrib)
+{'class': 'product', 'data-id': '1'}
+```
+通过以下任意方式访问某个属性:
+```python
+article.attrib['class']
+article.attrib.get('class')
+article['class'] # new in v0.3
+```
+通过以下方式检查是否包含指定属性:
+```python
+'class' in article.attrib
+'class' in article # new in v0.3
+```
+获取元素的 HTML 内容:
+```python
+>>> article.html_content
+'<article class="product" data-id="1"><h3>Product 1</h3>\n <p class="description">This is product 1</p>\n <span class="price">$10.99</span>\n <div class="hidden stock">In stock: 5</div>\n </article>'
+```
+获取格式化后的 HTML 内容,使其更易阅读:
+```python
+print(article.prettify())
+```
+```html
+<article class="product" data-id="1"><h3>Product 1</h3>
+ <p class="description">This is product 1</p>
+ <span class="price">$10.99</span>
+ <div class="hidden stock">In stock: 5</div>
+</article>
+```
+使用 `.body` 获取页面的原始内容。从 v0.4 开始,对 Fetcher 返回的 `Response` 对象调用 `.body`,结果始终为 `bytes`。
+```python
+>>> page.body
+'<html>\n <head>\n <title>Some page</title>\n </head>\n ...'
+```
+获取元素在 DOM 树中的所有祖先:
+```python
+>>> article.path
+[<data='<div class="product-list"> <article clas...' parent='<body> <div class="product-list"> <artic...'>,
+ <data='<body> <div class="product-list"> <artic...' parent='<html><head><title>Some page</title></he...'>,
+ <data='<html><head><title>Some page</title></he...'>]
+```
+尽量生成简短的 CSS 选择器,或生成完整选择器:
+```python
+>>> article.generate_css_selector
+'body > div > article'
+>>> article.generate_full_css_selector
+'body > div > article'
+```
+XPath 也一样:
+```python
+>>> article.generate_xpath_selector
+"//body/div/article"
+>>> article.generate_full_xpath_selector
+"//body/div/article"
+```
+
+### 遍历 {#traversal}
+使用上面找到的元素,详细看看如何在页面中移动。
+
+如果还不了解 DOM 树或树形数据结构,下面的内容可能不太容易理解。建议先查阅这些概念。
+
+如果不想另外查找,这里有一个简单说明。<br/>
+`html` 是页面树的根元素,因为每个页面都从 `html` 元素开始。<br/>
+`head` 和 `body` 等元素直接位于它下面,因此是 `html` 的子元素,而 `html` 是它们的父元素。`body` 和 `head` 有同一个父元素,所以互为同级元素。
+
+访问元素的父元素:
+```python
+>>> article.parent
+<data='<div class="product-list"> <article clas...' parent='<body> <div class="product-list"> <artic...'>
+>>> article.parent.tag
+'div'
+```
+可以按需要连续调用。下面介绍的类似属性和方法也支持这种方式。
+```python
+>>> article.parent.parent.tag
+'body'
+```
+获取元素的子元素:
+```python
+>>> article.children
+[<data='<h3>Product 1</h3>' parent='<article class="product" data-id="1"><h3...'>,
+ <data='<p class="description">This is product 1...' parent='<article class="product" data-id="1"><h3...'>,
+ <data='<span class="price">$10.99</span>' parent='<article class="product" data-id="1"><h3...'>,
+ <data='<div class="hidden stock">In stock: 5</d...' parent='<article class="product" data-id="1"><h3...'>]
+```
+获取元素下面的所有元素,相当于递归版本的 `children`:
+```python
+>>> article.below_elements
+[<data='<h3>Product 1</h3>' parent='<article class="product" data-id="1"><h3...'>,
+ <data='<p class="description">This is product 1...' parent='<article class="product" data-id="1"><h3...'>,
+ <data='<span class="price">$10.99</span>' parent='<article class="product" data-id="1"><h3...'>,
+ <data='<div class="hidden stock">In stock: 5</d...' parent='<article class="product" data-id="1"><h3...'>]
+```
+这个元素的子元素没有再嵌套其他元素,所以结果与 `children` 相同。
+
+使用类名为 `product-list` 的元素,可以更清楚地看到 `children` 和 `below_elements` 的区别:
+```python
+>>> products_list = page.css('.product-list')[0]
+>>> products_list.children
+[<data='<article class="product" data-id="1"><h3...' parent='<div class="product-list"> <article clas...'>,
+ <data='<article class="product" data-id="2"><h3...' parent='<div class="product-list"> <article clas...'>,
+ <data='<article class="product" data-id="3"><h3...' parent='<div class="product-list"> <article clas...'>]
+
+>>> products_list.below_elements
+[<data='<article class="product" data-id="1"><h3...' parent='<div class="product-list"> <article clas...'>,
+ <data='<h3>Product 1</h3>' parent='<article class="product" data-id="1"><h3...'>,
+ <data='<p class="description">This is product 1...' parent='<article class="product" data-id="1"><h3...'>,
+ <data='<span class="price">$10.99</span>' parent='<article class="product" data-id="1"><h3...'>,
+ <data='<div class="hidden stock">In stock: 5</d...' parent='<article class="product" data-id="1"><h3...'>,
+ <data='<article class="product" data-id="2"><h3...' parent='<div class="product-list"> <article clas...'>,
+...]
+```
+获取同级元素:
+```python
+>>> article.siblings
+[<data='<article class="product" data-id="2"><h3...' parent='<div class="product-list"> <article clas...'>,
+ <data='<article class="product" data-id="3"><h3...' parent='<div class="product-list"> <article clas...'>]
+```
+获取当前元素的下一个同级元素:
+```python
+>>> article.next
+<data='<article class="product" data-id="2"><h3...' parent='<div class="product-list"> <article clas...'>
+```
+`previous` 用于获取上一个同级元素:
+```python
+>>> article.previous # It's the first child, so it doesn't have a previous element
+>>> second_article = page.css('.product[data-id="2"]')[0]
+>>> second_article.previous
+<data='<article class="product" data-id="1"><h3...' parent='<div class="product-list"> <article clas...'>
+```
+可以快速检查元素是否具有指定类名:
+```python
+>>> article.has_class('product')
+True
+```
+如果只访问父元素还不够,可以遍历元素的所有祖先:
+```python
+for ancestor in article.iterancestors():
+ # do something with it...
+```
+也可以查找满足条件的祖先。传入一个接收 [Selector](#selector) 的函数,条件满足时返回 `True`,否则返回 `False`:
+```python
+>>> article.find_ancestor(lambda ancestor: ancestor.has_class('product-list'))
+<data='<div class="product-list"> <article clas...' parent='<body> <div class="product-list"> <artic...'>
+
+>>> article.find_ancestor(lambda ancestor: ancestor.css('.product-list')) # Same result, different approach
+<data='<div class="product-list"> <article clas...' parent='<body> <div class="product-list"> <artic...'>
+```
+## Selectors {#selectors}
+`Selectors` 是 [Selector](#selector) 的列表版本。它继承 Python 的标准 `List` 类型,保留所有 `List` 属性和方法,并添加一些方法,让操作其中的 [Selector](#selector) 实例更方便。
+
+[Selector](#selector) 中所有返回一组元素的方法和属性,都会返回 [Selectors](#selectors) 实例。
+
+从 v0.4 开始,所有选择方法都统一返回 [Selector](#selector)/[Selectors](#selectors),包括文本节点和属性值。通过 `::text`、`/text()`、`::attr()`、`/@attr` 选出的文本节点也会包装成 [Selector](#selector)。这些对象的 `tag` 是 `"#text"`,`text` 属性返回文本值。仍然可以直接读取文本值,其他属性会返回空值或默认值,不会因此报错。
+
+```python
+page.css('a::text') # -> Selectors (of text node Selectors)
+page.xpath('//a/text()') # -> Selectors
+page.css('a::text').get() # -> TextHandler (the first text value)
+page.css('a::text').getall() # -> TextHandlers (all text values)
+page.css('a::attr(href)') # -> Selectors
+page.xpath('//a/@href') # -> Selectors
+page.css('.price_color') # -> Selectors
+```
+
+### 数据提取方法 {#data-extraction-methods}
+从 v0.4 开始,[Selector](#selector) 和 [Selectors](#selectors) 都提供 `get()`、`getall()` 及其别名 `extract_first` 和 `extract`,遵循 Scrapy 的用法。旧的 `get_all()` 已移除。
+
+**对于 [Selector](#selector) 对象:**
+
+- `get()` 返回 `TextHandler`。对于文本节点,返回文本值;对于 HTML 元素,返回包含元素自身标签的序列化 HTML。
+- `getall()` 返回一个 `TextHandlers` 列表,其中只包含这一个序列化字符串。
+- `extract_first` 是 `get()` 的别名,`extract` 是 `getall()` 的别名。
+
+```python
+>>> page.css('h3')[0].get() # Outer HTML of the element
+'<h3>Product 1</h3>'
+
+>>> page.css('h3::text')[0].get() # Text value of the text node
+'Product 1'
+```
+
+**对于 [Selectors](#selectors) 对象:**
+
+- `get(default=None)` 返回**第一个**元素的序列化字符串。列表为空时返回 `default`。
+- `getall()` 序列化**所有**元素,并返回 `TextHandlers` 列表。
+- `extract_first` 是 `get()` 的别名,`extract` 是 `getall()` 的别名。
+
+```python
+>>> page.css('.price::text').get() # First price text
+'$10.99'
+
+>>> page.css('.price::text').getall() # All price texts
+['$10.99', '$20.99', '$15.99']
+
+>>> page.css('.price::text').get('') # With default value
+'$10.99'
+```
+
+这些方法适用于 CSS、XPath、`find` 等所有选择方式,也是以兼容 Scrapy 的方式提取文本和属性值的推荐方法。
+
+接着看看 [Selectors](#selectors) 还提供了哪些功能。
+### 属性 {#properties_1}
+除了遍历、切片等标准 Python 列表操作,还可以使用以下功能:
+
+直接对包含的 [Selector](#selector) 实例执行 CSS 和 XPath 选择。返回类型与 [Selector](#selector) 的 `css`、`xpath` 相同。参数也类似,但这里不能使用 `adaptive`。这让链式调用很方便。
+```pycon
+>>> page.css('.product h3::text').getall()
+['Product 1', 'Product 2', 'Product 3']
+>>> page.css('.product').css('h3::text').getall()
+['Product 1', 'Product 2', 'Product 3']
+```
+也可以直接调用 `re` 和 `re_first`。它们的参数与 [Selector](#selector) 中相同,后面的 [TextHandler](#texthandler) 部分会详细解释。
+
+不过,这里的 `re_first` 会对每个 [Selector](#selector) 调用 `re`,并返回第一个有结果的匹配。`re` 则照常返回 [TextHandlers](#texthandlers),把所有 [TextHandler](#texthandler) 实例合并到一个 [TextHandlers](#texthandlers) 实例中。
+```pycon
+>>> page.css('.price::text').re(r'[\d.]+')
+['10.99', '20.99', '15.99']
+>>> page.css('.product h3::text').re(r'Product (\d+)')
+['1', '2', '3']
+```
+使用 `search` 可以快速查找包含的 [Selector](#selector) 实例。传入的函数必须接收一个 [Selector](#selector) 作为第一个参数,并返回 True 或 False。方法会返回第一个满足条件的 [Selector](#selector),没有匹配时返回 `None`。
+
+```pycon
+>>> product = page.css('.product').search(lambda p: p.css('.price::text').get() == '$20.99')
+>>> product.css('h3::text').get()
+'Product 2'
+```
+`filter` 也接收与 `search` 类似的函数,但会返回一个 `Selectors`,包含所有满足条件的 [Selector](#selector):
+
+```pycon
+>>> products = page.css('.product').filter(lambda p: float(p.css('.price::text').re_first(r'[\d.]+')) > 15)
+>>> products.css('h3::text').getall()
+['Product 2', 'Product 3']
+```
+可以安全地访问第一个或最后一个元素,不必担心索引错误:
+```python
+>>> page.css('.product').first # First Selector or None
+<data='<article class="product" data-id="1"><h3...'>
+>>> page.css('.product').last # Last Selector or None
+<data='<article class="product" data-id="3"><h3...'>
+>>> page.css('.nonexistent').first # Returns None instead of raising IndexError
+```
+
+如果想用简短的方式获取 [Selectors](#selectors) 中 [Selector](#selector) 实例的数量,可以这样写:
+```python
+page.css('.product').length
+```
+这等同于:
+```python
+len(page.css('.product'))
+```
+没错,就像 JavaScript :)
+
+## TextHandler {#texthandler}
+这个类很重要。所有应返回字符串的方法和属性都会返回 `TextHandler`,应返回字符串列表的则会返回 [TextHandlers](#texthandlers)。
+
+TextHandler 继承标准 Python 字符串,因此普通字符串能做的操作,它也能做。那为什么还需要单独的名称呢?
+
+因为 TextHandler 提供了额外的方法和属性。库中的各个类都使用 TextHandler 返回字符串,所以可以灵活组合这些功能,让代码更短、更清晰。也可以直接导入它,对任意字符串使用,具体会在[后面](../development/scrapling_custom_types.md)介绍。
+### 用法 {#usage}
+切片、索引访问,以及 `split`、`replace`、`strip` 等操作和方法,都会再次返回 `TextHandler`,因此可以继续链式调用。如果发现某个方法或属性返回了普通字符串,而不是 `TextHandler`,请提交 Issue,我们也会调整它。
+
+先介绍 `re` 和 `re_first`。这些方法也存在于 [Selector](#selector)、[Selectors](#selectors) 和 [TextHandlers](#texthandlers) 中,参数相同。
+
+- `re` 的第一个参数可以是字符串或编译后的正则表达式。它查找所有匹配的字符串,并返回 [TextHandlers](#texthandlers)。`re_first` 接收相同参数,行为也类似,但只返回第一个结果,类型为 `TextHandler`。
+
+ 还有以下实用参数:
+
+ - **replace_entities**:默认开启,将字符实体引用替换为对应字符。
+ - **clean_match**:默认关闭,匹配时忽略所有空白,包括连续空格。
+ - **case_sensitive**:默认开启。关闭后,编译正则表达式时会忽略大小写。
+
+ 这些例子前面已经见过。因为调用的是 `re`,所以结果为 [TextHandlers](#texthandlers)。
+ ```pycon
+ >>> page.css('.price::text').re(r'[\d.]+')
+ ['10.99', '20.99', '15.99']
+ >>> page.css('.product h3::text').re(r'Product (\d+)')
+ ['1', '2', '3']
+ ```
+ 为说明其他参数,下面的每个例子使用一个自定义字符串:
+ ```python
+ >>> from scrapling import TextHandler
+ >>> test_string = TextHandler('hi there') # Hence the two spaces
+ >>> test_string.re('hi there')
+ >>> test_string.re('hi there', clean_match=True) # Using `clean_match` will clean the string before matching the regex
+ ['hi there']
+
+ >>> test_string2 = TextHandler('Oh, Hi Mark')
+ >>> test_string2.re_first('oh, hi Mark')
+ >>> test_string2.re_first('oh, hi Mark', case_sensitive=False) # Hence disabling `case_sensitive`
+ 'Oh, Hi Mark'
+
+ # Mixing arguments
+ >>> test_string.re('hi there', clean_match=True, case_sensitive=False)
+ ['hi there']
+ ```
+ 到处使用 `TextHandler` 的另一个好处是,`html_content` 也会返回 `TextHandler`。因此可以直接对 HTML 内容使用正则表达式:
+ ```python
+ >>> page.html_content.re('div class=".*">(.*)</div')
+ ['In stock: 5', 'In stock: 3', 'Out of stock']
+ ```
+
+- `.json()` 会尝试快速把内容转换为 JSON 对象,无法转换时抛出错误:
+ ```python
+ >>> page.css('#page-data::text').get()
+ '\n {\n "lastUpdated": "2024-09-22T10:30:00Z",\n "totalProducts": 3\n }\n '
+ >>> page.css('#page-data::text').get().json()
+ {'lastUpdated': '2024-09-22T10:30:00Z', 'totalProducts': 3}
+ ```
+ 如果选择元素时没有指定文本节点,例如元素文本或属性文本,就会自动使用元素的文本内容:
+ ```python
+ >>> page.css('#page-data')[0].json()
+ {'lastUpdated': '2024-09-22T10:30:00Z', 'totalProducts': 3}
+ ```
+ [Selector](#selector) 还做了额外处理。假设页面如下:
+ ```html
+ <html>
+ <body>
+ <div>
+ <script id="page-data" type="application/json">
+ {
+ "lastUpdated": "2024-09-22T10:30:00Z",
+ "totalProducts": 3
+ }
+ </script>
+ </div>
+ </body>
+ </html>
+ ```
+ 前面介绍的 [Selector](#selector) 方法 `get_all_text` 也会返回 `TextHandler`。<br/><br/>
+ 如果这样调用:
+ ```python
+ >>> page.css('div::text').get().json()
+ ```
+ 就会报错,因为 `div` 标签没有可以解析为 JSON 的直接文本,实际上它完全没有直接文本。<br/><br/>
+ 这时可以使用 `get_all_text`:
+ ```python
+ >>> page.css('div')[0].get_all_text(ignore_tags=[]).json()
+ {'lastUpdated': '2024-09-22T10:30:00Z', 'totalProducts': 3}
+ ```
+ 这里使用 `ignore_tags`,是因为它默认忽略 `('script', 'style',)`。<br/><br/>
+ 使用 Fetcher 时还有一个相关行为。假设获取到这样的 JSON 响应:
+ ```python
+ >>> page = Selector("""{"some_key": "some_value"}""")
+ ```
+ [Selector](#selector) 主要处理 HTML 页面,因此会把它当作不完整的 HTML 并修复。读取 `html_content` 时会得到:
+ ```python
+ >>> page.html_content
+ '<html><body><p>{"some_key": "some_value"}</p></body></html>'
+ ```
+ 不过,直接调用 `json` 仍然有效:
+ ```python
+ >>> page.json()
+ {'some_key': 'some_value'}
+ ```
+ `html` 标签没有直接文本,为什么还能成功呢?<br/>
+ 为处理 JSON 响应等情况,[Selector](#selector) 会保留收到内容的原始副本。调用 `.json()` 时,会先尝试把这个副本解析为 JSON。如果没有副本,例如操作的是单个元素,则检查元素的直接文本;否则会直接使用 `get_all_text`。<br/>
+
+- `.clean()` 会移除空白字符和连续空格,并返回新的 `TextHandler` 实例:
+```python
+>>> TextHandler('\n wonderful idea, \reh?').clean()
+'wonderful idea, eh?'
+```
+还可以传入 `remove_entities`,让 `clean` 把 HTML 实体替换为对应字符。
+
+- `.sort()` 可以像处理列表一样对字符串排序:
+```python
+>>> TextHandler('acb').sort()
+'abc'
+```
+也可以反向排序:
+```python
+>>> TextHandler('acb').sort(reverse=True)
+'cba'
+```
+
+以后会继续添加方法和属性。请记住,库中几乎所有原本返回字符串的地方都会返回这个类。
+
+## TextHandlers {#texthandlers}
+这个类的思路与 [Selectors](#selectors) 和 [Selector](#selector) 类似。它继承标准列表的行为,并增加 `re` 和 `re_first`。
+
+区别在于,这里的 `re_first` 会对每个 [TextHandler](#texthandler) 调用 `re`,返回第一个结果或 `None`。目前没有其他需要说明的内容,以后会继续添加方法。
+
+## AttributesHandler {#attributeshandler}
+这是标准 Python 字典 `dict` 的只读版本,专门保存元素或 [Selector](#selector) 实例的属性。
+```python
+>>> print(page.find('script').attrib)
+{'id': 'page-data', 'type': 'application/json'}
+>>> type(page.find('script').attrib).__name__
+'AttributesHandler'
+```
+因为是只读的,它比标准字典占用更少资源。除修改或覆盖数据的方法外,其他方法和属性与字典相同。
+
+目前还提供两个简单功能:
+
+- `search_values` 方法
+
+ 普通字典可以用 `dict.get("key_name")` 检查键是否存在。如果要按值搜索,通常需要额外代码。这个方法可以直接搜索属性值,并为每个匹配项返回一个字典。
+
+ 简单示例:
+ ```python
+ >>> for i in page.find('script').attrib.search_values('page-data'):
+ print(i)
+ {'id': 'page-data'}
+ ```
+ 还可以通过 `partial` 搜索值的一部分:
+ ```python
+ >>> for i in page.find('script').attrib.search_values('page', partial=True):
+ print(i)
+ {'id': 'page-data'}
+ ```
+ 上面的例子比较简单。更实际的用法是与 `find_all` 配合,查找具有指定属性值的所有元素:
+ ```python
+ >>> page.find_all(lambda element: list(element.attrib.search_values('product')))
+ [<data='<article class="product" data-id="1"><h3...' parent='<div class="product-list"> <article clas...'>,
+ <data='<article class="product" data-id="2"><h3...' parent='<div class="product-list"> <article clas...'>,
+ <data='<article class="product" data-id="3"><h3...' parent='<div class="product-list"> <article clas...'>]
+ ```
+ 这些元素的 `class` 属性值都是 'product'。
+
+ 这里使用 `list`,是因为 `search_values` 返回生成器。如果不转换,对所有元素都会被判断为 `True`。
+
+- `json_string` 属性
+
+ 如果当前属性可以序列化为 JSON,这个属性会将它们转换为 JSON 字符串,否则抛出错误。
+
+ ```python
+ >>>page.find('script').attrib.json_string
+ b'{"id":"page-data","type":"application/json"}'
+ ```
\ No newline at end of file
diff --git a/docs/locales/zh/parsing/selection.md b/docs/locales/zh/parsing/selection.md
new file mode 100644
index 0000000..5f7dd73
--- /dev/null
+++ b/docs/locales/zh/parsing/selection.md
@@ -0,0 +1,521 @@
+---
+title: "使用 CSS、XPath、文本和正则表达式提取 HTML 数据"
+description: "使用 CSS、XPath、文本和正则表达式选择 HTML 元素。通过 Scrapling 代码示例查找相似元素并提取字段。"
+---
+
+# 查询元素 {#querying-elements}
+`Selector` 类解析 HTML,因为自适应功能不支持 XML。对于 XML、RSS 或 Atom Feed,请使用 [XMLFeedSpider](../spiders/generic-templates.md#xmlfeedspider)。它使用 XML 解析器,直接提供每个 Feed 节点。
+
+Scrapling 主要有五种查找元素的方式:
+
+1. CSS3 选择器
+2. XPath 选择器
+3. 根据过滤条件查找
+4. 查找包含指定文本的元素
+5. 查找内容匹配指定正则表达式的元素
+
+还有其他间接查找元素的方式,这里主要介绍上述方法。另外也会介绍 Scrapling 的一项实用功能:查找与已有元素相似的元素。可以[直接跳到该部分](#finding-similar-elements)。
+
+如果刚接触网页抓取,几乎没写过选择器,又想快速开始,建议先学习 `find`/`find_all`,[点这里查看](#filters-based-searching)。
+
+## CSS/XPath 选择器 {#cssxpath-selectors}
+
+### 什么是 CSS 选择器? {#what-are-css-selectors}
+[CSS](https://en.wikipedia.org/wiki/CSS) 用于设置 HTML 文档的样式。它通过选择器,把样式应用到指定的 HTML 元素。
+
+Scrapling 支持 [W3C 规范](http://www.w3.org/TR/2011/REC-css3-selectors-20110929/)中的 CSS3 选择器。底层使用 `cssselect`,建议查看它[支持的选择器](https://cssselect.readthedocs.io/en/latest/#supported-selectors)、伪函数和伪元素。
+
+Scrapling 还提供一些非标准伪元素:
+
+* 使用 ``::text`` 选择文本节点。
+* 使用 ``::attr(name)`` 选择属性值,其中 name 是要读取的属性名。
+
+如果用过 Scrapy 或 Parsel,这里的选择器逻辑会很熟悉,无需另学一套方式 :)
+
+使用 `css` 通过 CSS 选择器选择元素,返回值为 `Selectors`。用 `[0]` 获取第一个元素,或用 `.get()` / `.getall()` 从文本或属性伪选择器中提取文本值。
+
+### 什么是 XPath 选择器? {#what-are-xpath-selectors}
+[XPath](https://en.wikipedia.org/wiki/XPath) 是一种选择 XML 节点的语言,也可以用于 HTML。这份[速查表](https://devhints.io/xpath)可以帮助学习 [XPath](https://en.wikipedia.org/wiki/XPath)。Scrapling 直接通过 [lxml](https://lxml.de/) 提供 XPath 支持。
+
+和 CSS 一样,这里的逻辑与 Scrapy、Parsel 相同。不过,Scrapling 没有实现它们的 XPath 扩展函数 `has-class`,而是提供 `has_class` 方法,可以对找到的元素执行同样的检查。
+
+使用 `xpath` 方法通过 XPath 选择元素,其逻辑与上面的 CSS 方法相同。
+
+> `css` 和 `xpath` 还有一些用于自适应功能的参数。这里暂不展开,后面会用单独的页面详细介绍。
+
+### 选择器示例 {#selectors-examples}
+下面对照展示 CSS 和 XPath 的用法。
+
+选择所有类名为 `product` 的元素:
+```python
+products = page.css('.product')
+products = page.xpath('//*[@class="product"]')
+```
+!!! info "注意:"
+
+ 如果元素还有其他类名,这个 XPath 就不能准确匹配。**按类名选择时,优先使用 CSS。**
+
+选择第一个类名为 `product` 的元素:
+```python
+product = page.css('.product')[0]
+product = page.xpath('//*[@class="product"]')[0]
+```
+获取第一个 `h1` 元素的文本:
+```python
+title = page.css('h1::text').get()
+title = page.xpath('//h1//text()').get()
+```
+这等同于:
+```python
+title = page.css('h1')[0].text
+title = page.xpath('//h1')[0].text
+```
+获取第一个 `a` 元素的 `href` 属性:
+```python
+link = page.css('a::attr(href)').get()
+link = page.xpath('//a/@href').get()
+```
+获取第一个符合以下条件的 `h1` 元素的文本:包含 `Phone`,且位于类名为 `product` 的元素内。
+```python
+title = page.css('.product h1:contains("Phone")::text').get()
+title = page.xpath('//*[@class="product"]//h1[contains(text(),"Phone")]/text()').get()
+```
+只要选择器返回结果,就可以按需要嵌套和链式调用:
+```python
+page.css('.product')[0].css('h1:contains("Phone")::text').get()
+page.xpath('//*[@class="product"]')[0].xpath('.//h1[contains(text(),"Phone")]/text()').get()
+page.xpath('//*[@class="product"]')[0].css('h1:contains("Phone")::text').get()
+```
+使用 `.//` 表示相对于当前元素的 XPath。以 `//` 开头会搜索整个文档,即使前面已经选中了某个产品。
+
+再看一个例子:
+
+查找 'href' 属性中包含 'image' 的所有链接:
+```python
+links = page.css('a[href*="image"]')
+links = page.xpath('//a[contains(@href, "image")]')
+for index, link in enumerate(links):
+ link_value = link.attrib['href'] # Cleaner than link.css('::attr(href)').get()
+ link_text = link.text
+ print(f'Link number {index} points to this url {link_value} with text content as "{link_text}"')
+```
+
+## 按文本内容选择 {#text-content-selection}
+Scrapling 支持根据元素的直接文本内容进行选择,有两种方式:
+
+1. 使用 `find_by_text` 查找直接文本中包含指定内容的元素,并通过参数调整行为。
+2. 使用 `find_by_regex` 查找直接文本匹配指定正则表达式的元素,也提供多种选项。
+
+如果熟悉正则表达式,`find_by_text` 能完成的搜索也都可以用 `find_by_regex` 实现。提供两种方法,是为了让不同用户都能方便地使用。
+
+`find_by_text` 的第一个参数是文本,`find_by_regex` 的第一个参数是正则表达式。两者共有以下参数:
+
+* **first_match**:为 `True` 时只返回第一个结果,默认如此。
+* **case_sensitive**:为 `True` 时区分大小写。
+* **clean_match**:为 `True` 时,在匹配前把空白字符和连续空格替换为一个空格。
+
+默认情况下,`find_by_text` 要求完整匹配,元素文本必须与传入文本完全相同。它还提供一个额外参数来改变这一点:
+
+* **partial**:启用后,`find_by_text` 会返回包含指定文本的元素,不再要求完整匹配。
+
+!!! abstract "注意:"
+
+ `find_by_regex` 的第一个参数可以是普通字符串,也可以是编译后的正则表达式,下面会展示示例。
+
+### 查找相似元素 {#finding-similar-elements}
+Scrapling 可以根据已有元素查找相似元素。这项功能的灵感来自 AutoScraper,但在 Scrapling 中,无论使用哪种方式找到元素,都可以调用它。它经常用于按文本找到元素之后,因此放在这里介绍。
+
+它是如何工作的?
+
+假设已经通过标题找到了一个产品,现在想提取同一表格或容器中的其他产品。对已有元素调用 `.find_similar()` 后,Scrapling 会执行以下操作:
+
+1. 查找 DOM 树中与该元素深度相同的所有元素。
+2. 检查这些元素,剔除标签名、父元素标签名或祖父元素标签名不一致的元素。
+3. 此时找到的元素大约有 99% 的概率就是目标元素。最后再通过模糊匹配,剔除属性不够相似的元素。这个步骤有一个相似度阈值,建议仅在默认配置无法找到目标元素时调整。
+
+说明有些长,但这些细节很重要。下一部分会给出示例,先看看这个方法接受的参数:
+
+* **similarity_threshold**:步骤 3 中比较元素属性的阈值,默认为 0.2,也就是两者的属性至少有 20% 相似度。设为 0 可以关闭这项检查,相当于跳过步骤 3。不过,建议先了解其他参数。
+* **ignore_attributes**:最后比较属性时忽略的属性名。默认为 `('href', 'src',)`,因为不同元素的 URL 可能相差很大,不适合作为可靠依据。
+* **match_text**:为 `True` 时,在步骤 3 中也比较元素文本。一般不建议启用,具体取决于使用场景。
+
+接下来看看示例。
+
+### 示例 {#examples}
+以下示例展示如何通过文本和正则表达式查找元素。
+
+示例使用 `Fetcher` 类,它的详细用法会在后面介绍。
+```python
+from scrapling.fetchers import Fetcher
+page = Fetcher.get('https://books.toscrape.com/index.html')
+```
+查找第一个文本完全匹配的元素:
+```python
+>>> page.find_by_text('Tipping the Velvet')
+<data='<a href="catalogue/tipping-the-velvet_99...' parent='<h3><a href="catalogue/tipping-the-velve...'>
+```
+结合 `page.urljoin`,把相对 `href` 转换为完整 URL:
+```python
+>>> page.find_by_text('Tipping the Velvet').attrib['href']
+'catalogue/tipping-the-velvet_999/index.html'
+>>> page.urljoin(page.find_by_text('Tipping the Velvet').attrib['href'])
+'https://books.toscrape.com/catalogue/tipping-the-velvet_999/index.html'
+```
+如果有多个匹配,获取所有结果,返回值是列表:
+```python
+>>> page.find_by_text('Tipping the Velvet', first_match=False)
+[<data='<a href="catalogue/tipping-the-velvet_99...' parent='<h3><a href="catalogue/tipping-the-velve...'>]
+```
+获取所有包含 `the` 的元素,即部分匹配:
+```python
+>>> results = page.find_by_text('the', partial=True, first_match=False)
+>>> [i.text for i in results]
+['A Light in the ...',
+ 'Tipping the Velvet',
+ 'The Requiem Red',
+ 'The Dirty Little Secrets ...',
+ 'The Coming Woman: A ...',
+ 'The Boys in the ...',
+ 'The Black Maria',
+ 'Mesaerion: The Best Science ...',
+ "It's Only the Himalayas"]
+```
+搜索默认不区分大小写,所以结果既包含 `The`,也包含 `the`。下面限制为只有小写 `the` 的元素:
+```python
+>>> results = page.find_by_text('the', partial=True, first_match=False, case_sensitive=True)
+>>> [i.text for i in results]
+['A Light in the ...',
+ 'Tipping the Velvet',
+ 'The Boys in the ...',
+ "It's Only the Himalayas"]
+```
+获取第一个文本匹配价格正则表达式的元素:
+```python
+>>> page.find_by_regex(r'£[\d\.]+')
+<data='<p class="price_color">£51.77</p>' parent='<div class="product_price"> <p class="pr...'>
+>>> page.find_by_regex(r'£[\d\.]+').text
+'£51.77'
+```
+传入编译后的正则表达式也一样,Scrapling 会识别类型并处理:
+```python
+>>> import re
+>>> regex = re.compile(r'£[\d\.]+')
+>>> page.find_by_regex(regex)
+<data='<p class="price_color">£51.77</p>' parent='<div class="product_price"> <p class="pr...'>
+>>> page.find_by_regex(regex).text
+'£51.77'
+```
+获取所有匹配正则表达式的元素:
+```python
+>>> page.find_by_regex(r'£[\d\.]+', first_match=False)
+[<data='<p class="price_color">£51.77</p>' parent='<div class="product_price"> <p class="pr...'>,
+ <data='<p class="price_color">£53.74</p>' parent='<div class="product_price"> <p class="pr...'>,
+ <data='<p class="price_color">£50.10</p>' parent='<div class="product_price"> <p class="pr...'>,
+ <data='<p class="price_color">£47.82</p>' parent='<div class="product_price"> <p class="pr...'>,
+ ...]
+```
+以此类推。
+
+查找位置和属性与当前元素相似的所有元素。在本例中,比较时忽略 'title' 属性:
+```python
+>>> element = page.find_by_text('Tipping the Velvet')
+>>> element.find_similar(ignore_attributes=['title'])
+[<data='<a href="catalogue/a-light-in-the-attic_...' parent='<h3><a href="catalogue/a-light-in-the-at...'>,
+ <data='<a href="catalogue/soumission_998/index....' parent='<h3><a href="catalogue/soumission_998/in...'>,
+ <data='<a href="catalogue/sharp-objects_997/ind...' parent='<h3><a href="catalogue/sharp-objects_997...'>,
+...]
+```
+结果有 19 个而不是 20 个,因为当前元素本身不会包含在结果中。
+```python
+>>> len(element.find_similar(ignore_attributes=['title']))
+19
+```
+获取所有相似元素的 `href` 属性:
+```python
+>>> [
+ element.attrib['href']
+ for element in element.find_similar(ignore_attributes=['title'])
+]
+['catalogue/a-light-in-the-attic_1000/index.html',
+ 'catalogue/soumission_998/index.html',
+ 'catalogue/sharp-objects_997/index.html',
+ ...]
+```
+再复杂一点,假设希望以这个元素为起点,提取所有图书的数据:
+```python
+>>> first_product = element.parent.parent
+>>> for product in [first_product, *first_product.find_similar()]:
+ print({
+ "name": product.css('h3 a::text').get(),
+ "price": product.css('.price_color')[0].re_first(r'[\d\.]+'),
+ "stock": product.css('.availability::text').getall()[-1].clean()
+ })
+{'name': 'Tipping the Velvet', 'price': '53.74', 'stock': 'In stock'}
+{'name': 'A Light in the ...', 'price': '51.77', 'stock': 'In stock'}
+{'name': 'Soumission', 'price': '50.10', 'stock': 'In stock'}
+{'name': 'Sharp Objects', 'price': '47.82', 'stock': 'In stock'}
+...
+```
+### 进阶示例 {#advanced-examples}
+下面是一些更接近实际任务的 `find_similar` 用法。
+
+提取电商产品
+```python
+def extract_product_grid(page):
+ # Find the first product card
+ first_product = page.find_by_text('Add to Cart').find_ancestor(
+ lambda e: e.has_class('product-card')
+ )
+
+ # Find similar product cards
+ products = [first_product, *first_product.find_similar()]
+
+ return [
+ {
+ 'name': p.css('h3::text').get(),
+ 'price': p.css('.price::text').re_first(r'\d+\.\d{2}'),
+ 'stock': 'In stock' in p.get_all_text(),
+ 'rating': p.css('.rating')[0].attrib.get('data-rating')
+ }
+ for p in products
+ ]
+```
+提取表格行
+```python
+def extract_table_data(page):
+ # Find the first data row
+ first_row = page.css('table tbody tr')[0]
+
+ # Find similar rows
+ rows = [first_row, *first_row.find_similar()]
+
+ return [
+ {
+ 'column1': row.css('td:nth-child(1)::text').get(),
+ 'column2': row.css('td:nth-child(2)::text').get(),
+ 'column3': row.css('td:nth-child(3)::text').get()
+ }
+ for row in rows
+ ]
+```
+提取表单字段
+```python
+def extract_form_fields(page):
+ # Find first form field container
+ first_field = page.css('input')[0].find_ancestor(
+ lambda e: e.has_class('form-field')
+ )
+
+ # Find similar field containers
+ fields = [first_field, *first_field.find_similar()]
+
+ return [
+ {
+ 'label': f.css('label::text').get(),
+ 'type': f.css('input')[0].attrib.get('type'),
+ 'required': 'required' in f.css('input')[0].attrib
+ }
+ for f in fields
+ ]
+```
+提取网站评论
+```python
+def extract_reviews(page):
+ # Find first review
+ first_review = page.find_by_text('Great product!')
+ review_container = first_review.find_ancestor(
+ lambda e: e.has_class('review')
+ )
+
+ # Find similar reviews
+ all_reviews = [review_container, *review_container.find_similar()]
+
+ return [
+ {
+ 'text': r.css('.review-text::text').get(),
+ 'rating': r.attrib.get('data-rating'),
+ 'author': r.css('.reviewer::text').get()
+ }
+ for r in all_reviews
+ ]
+```
+## 基于过滤条件搜索 {#filters-based-searching}
+这种方式功能强大,而且比编写选择器更容易上手,通常是 Scrapling 中查找元素的最佳选择。
+
+受 BeautifulSoup 的 `find_all` 启发,Scrapling 提供 `find_all` 和 `find`。它们支持多个过滤条件,查找同时满足所有条件的元素。
+
+具体规则如下:
+
+* 字符串作为标签名。
+* List、Tuple、Set 等可迭代对象作为一组标签名。
+* 字典表示 HTML 元素的属性名称及对应值。
+* 正则表达式按内容过滤元素,类似 `find_by_regex`。
+* 函数用于按自定义条件过滤元素。
+* 关键字参数表示 HTML 元素的属性名称及对应值。
+
+所有参数会被收集起来,每个过滤步骤把结果传给下一步,逐步缩小范围。
+
+当前页面或元素中的所有元素按以下顺序过滤:
+
+1. 收集标签名匹配的元素。
+2. 收集满足所有属性条件的元素。如果已执行上一步,则只过滤上一步的结果。
+3. 收集匹配所有正则表达式的元素。如果已执行前面的步骤,则只过滤已有结果。
+4. 收集满足所有函数条件的元素。如果已执行前面的步骤,则只过滤已有结果。
+
+!!! note "注意事项:"
+
+ 1. 过滤从上述顺序中第一个实际传入的条件开始。例如,没有传标签名但传了属性条件,就从步骤 2 开始。
+ 2. 传入参数的先后顺序不影响过滤顺序,始终按上面的规则执行。
+
+看看示例就更清楚了 :)
+
+### 示例 {#examples_1}
+```python
+from scrapling.fetchers import Fetcher
+page = Fetcher.get('https://quotes.toscrape.com/')
+```
+查找所有 `div` 元素:
+```python
+>>> page.find_all('div')
+[<data='<div class="container"> <div class="row...' parent='<body> <div class="container"> <div clas...'>,
+ <data='<div class="row header-box"> <div class=...' parent='<div class="container"> <div class="row...'>,
+...]
+```
+查找类名恰好为 `quote` 的所有 div 元素:
+```python
+>>> page.find_all('div', class_='quote')
+[<data='<div class="quote" itemscope itemtype="h...' parent='<div class="col-md-8"> <div class="quote...'>,
+ <data='<div class="quote" itemscope itemtype="h...' parent='<div class="col-md-8"> <div class="quote...'>,
+...]
+```
+另一种等价写法:
+```python
+>>> page.find_all('div', {'class': 'quote'})
+[<data='<div class="quote" itemscope itemtype="h...' parent='<div class="col-md-8"> <div class="quote...'>,
+ <data='<div class="quote" itemscope itemtype="h...' parent='<div class="col-md-8"> <div class="quote...'>,
+...]
+```
+查找类名恰好为 `quote` 的所有元素:
+```python
+>>> page.find_all({'class': 'quote'})
+[<data='<div class="quote" itemscope itemtype="h...' parent='<div class="col-md-8"> <div class="quote...'>,
+ <data='<div class="quote" itemscope itemtype="h...' parent='<div class="col-md-8"> <div class="quote...'>,
+...]
+```
+查找类名为 `quote` 的 div 元素,其中包含 `.text` 元素,且该元素的文本中含有 'world':
+```python
+>>> page.find_all('div', {'class': 'quote'}, lambda e: "world" in e.css('.text::text').get())
+[<data='<div class="quote" itemscope itemtype="h...' parent='<div class="col-md-8"> <div class="quote...'>]
+```
+查找所有具有子元素的元素:
+```python
+>>> page.find_all(lambda element: len(element.children) > 0)
+[<data='<html lang="en"><head><meta charset="UTF...'>,
+ <data='<head><meta charset="UTF-8"><title>Quote...' parent='<html lang="en"><head><meta charset="UTF...'>,
+ <data='<body> <div class="container"> <div clas...' parent='<html lang="en"><head><meta charset="UTF...'>,
+...]
+```
+查找内容中包含 'world' 的所有元素:
+```python
+>>> page.find_all(lambda element: "world" in element.text)
+[<data='<span class="text" itemprop="text">“The...' parent='<div class="quote" itemscope itemtype="h...'>,
+ <data='<a class="tag" href="/tag/world/page/1/"...' parent='<div class="tags"> Tags: <meta class="ke...'>]
+```
+查找匹配指定正则表达式的所有 span 元素:
+```python
+>>> page.find_all('span', re.compile(r'world'))
+[<data='<span class="text" itemprop="text">“The...' parent='<div class="quote" itemscope itemtype="h...'>]
+```
+查找类名为 'quote' 的所有 div 和 span 元素。这里没有符合条件的 span,所以只返回 div:
+```python
+>>> page.find_all(['div', 'span'], {'class': 'quote'})
+[<data='<div class="quote" itemscope itemtype="h...' parent='<div class="col-md-8"> <div class="quote...'>,
+ <data='<div class="quote" itemscope itemtype="h...' parent='<div class="col-md-8"> <div class="quote...'>,
+...]
+```
+混合使用多种条件:
+```python
+>>> page.find_all({'itemtype':"http://schema.org/CreativeWork"}, 'div').css('.author::text').getall()
+['Albert Einstein',
+ 'J.K. Rowling',
+...]
+```
+还有一个实用技巧:查找 `href` 属性值以 'Einstein' 结尾的所有元素。
+```python
+>>> page.find_all({'href$': 'Einstein'})
+[<data='<a href="/author/Albert-Einstein">(about...' parent='<span>by <small class="author" itemprop=...'>,
+ <data='<a href="/author/Albert-Einstein">(about...' parent='<span>by <small class="author" itemprop=...'>,
+ <data='<a href="/author/Albert-Einstein">(about...' parent='<span>by <small class="author" itemprop=...'>]
+```
+另一个技巧:查找 `href` 属性值中包含 '/author/' 的所有元素。
+```python
+>>> page.find_all({'href*': '/author/'})
+[<data='<a href="/author/Albert-Einstein">(about...' parent='<span>by <small class="author" itemprop=...'>,
+ <data='<a href="/author/J-K-Rowling">(about)</a...' parent='<span>by <small class="author" itemprop=...'>,
+ <data='<a href="/author/Albert-Einstein">(about...' parent='<span>by <small class="author" itemprop=...'>,
+...]
+```
+以此类推。
+
+## 生成选择器 {#generating-selectors}
+可以为任意元素生成 CSS/XPath 选择器,之后在 Scrapling 或其他地方复用。无论最初如何找到这个元素,都可以生成选择器。
+
+为 `url_element` 生成简短的 CSS 选择器;如果无法简化,则生成完整选择器:
+```python
+>>> url_element = page.find({'href*': '/author/'})
+>>> url_element.generate_css_selector
+'body > div > div:nth-of-type(2) > div > div > span:nth-of-type(2) > a'
+```
+为 `url_element` 生成从页面根部开始的完整 CSS 选择器:
+```python
+>>> url_element.generate_full_css_selector
+'body > div > div:nth-of-type(2) > div > div > span:nth-of-type(2) > a'
+```
+为 `url_element` 生成简短的 XPath 选择器;如果无法简化,则生成完整选择器:
+```python
+>>> url_element.generate_xpath_selector
+'//body/div/div[2]/div/div/span[2]/a'
+```
+为 `url_element` 生成从页面根部开始的完整 XPath 选择器:
+```python
+>>> url_element.generate_full_xpath_selector
+'//body/div/div[2]/div/div/span[2]/a'
+```
+!!! abstract "注意:"
+
+ 生成简短选择器时,Scrapling 会寻找可唯一识别的元素作为起点,例如具有 `id` 属性的元素。本例没有这样的元素,所以简短选择器和完整选择器相同。
+
+## 结合选择器与正则表达式 {#using-selectors-with-regular-expressions}
+与 `parsel`/`scrapy` 类似,`re` 和 `re_first` 可以用正则表达式提取数据。不同的是,Scrapling 几乎在所有类中都提供这些方法,包括 `Selector`/`Selectors`/`TextHandler` 和 `TextHandlers`。因此,即使没有先选择文本节点,也可以直接对元素调用。
+
+介绍 [TextHandler](main_classes.md#texthandler) 时会详细说明。基本用法如下:
+```python
+>>> page.css('.price_color')[0].re_first(r'[\d\.]+')
+'51.77'
+
+>>> page.css('.price_color').re_first(r'[\d\.]+')
+'51.77'
+
+>>> page.css('.price_color').re(r'[\d\.]+')
+['51.77',
+ '53.74',
+ '50.10',
+ '47.82',
+ '54.23',
+...]
+
+>>> page.css('.product_pod h3 a::attr(href)').re(r'catalogue/(.*)/index.html')
+['a-light-in-the-attic_1000',
+ 'tipping-the-velvet_999',
+ 'soumission_998',
+ 'sharp-objects_997',
+...]
+
+>>> filtering_function = lambda e: e.parent.tag == 'h3' and e.parent.parent.has_class('product_pod') # As above selector
+>>> page.find('a', filtering_function).attrib['href'].re(r'catalogue/(.*)/index.html')
+['a-light-in-the-attic_1000']
+
+>>> page.find_by_text('Tipping the Velvet').attrib['href'].re(r'catalogue/(.*)/index.html')
+['tipping-the-velvet_999']
+```
+以此类推。下一页会结合 [TextHandler](main_classes.md#texthandler) 更详细地介绍。
\ No newline at end of file
diff --git a/docs/locales/zh/spiders/advanced.md b/docs/locales/zh/spiders/advanced.md
new file mode 100644
index 0000000..71d0542
--- /dev/null
+++ b/docs/locales/zh/spiders/advanced.md
@@ -0,0 +1,430 @@
+---
+title: "抓取控制:AutoThrottle、检查点、缓存和流式输出"
+description: "控制抓取速度和并发。了解响应缓存、暂停与恢复、数据项流式输出,以及检查点保存的状态。"
+---
+
+# 高级用法 {#advanced-usages}
+
+## 简介 {#introduction}
+
+!!! success "前提条件"
+
+ 1. 已阅读[入门](getting-started.md),知道如何创建并运行一个简单的 Spider。
+
+本页介绍 Spider 系统的高级功能:并发控制、暂停与恢复、流式输出、生命周期钩子、统计信息和日志。
+
+## 并发控制 {#concurrency-control}
+
+Spider 系统通过以下类属性控制抓取强度:
+
+| 属性 | 默认值 | 说明 |
+|------|--------|------|
+| `concurrent_requests` | `4` | 同时处理的最大请求数 |
+| `concurrent_requests_per_domain` | `0` | 每个域名的最大并发请求数,0 表示不单独限制域名 |
+| `download_delay` | `0.0` | 每次请求前等待的秒数 |
+| `robots_txt_obey` | `False` | 遵守 robots.txt 规则,包括 Disallow、Crawl-delay 和 Request-rate |
+
+```python
+class PoliteSpider(Spider):
+ name = "polite"
+ start_urls = ["https://example.com"]
+
+ # Be gentle with the server
+ concurrent_requests = 4
+ concurrent_requests_per_domain = 2
+ download_delay = 1.0 # Wait 1 second between requests
+
+ async def parse(self, response: Response):
+ yield {"title": response.css("title::text").get("")}
+```
+
+设置 `concurrent_requests_per_domain` 后,每个域名除了受全局限制,还会有自己的并发限制。同时抓取多个域名时,这样既能保持较高的总并发量,又不会给单个域名带来太大压力。
+
+!!! tip
+
+ `download_delay` 会在每次请求前加入固定等待时间,不考虑域名。可以用它做简单的频率限制。
+
+## AutoThrottle {#autothrottle}
+
+固定的 `download_delay` 只能靠估计。太小容易被封锁,太大又可能让抓取持续一整晚。AutoThrottle 会观察网站实际的响应速度,然后单独调整每个域名的延迟。服务器响应快就加速,响应慢或出现封锁就减速。
+
+| 属性 | 默认值 | 说明 |
+|------|--------|------|
+| `autothrottle_enabled` | `False` | 启用自动调整延迟 |
+| `autothrottle_start_delay` | `5.0` | 首次请求某个域名时使用的延迟 |
+| `autothrottle_max_delay` | `60.0` | 允许的最大延迟 |
+| `autothrottle_target_concurrency` | `None` | 每个域名的目标并发请求数,详见下文 |
+| `autothrottle_block_backoff` | `True` | 每次被封锁时,将该域名的延迟翻倍 |
+
+```python
+class AdaptiveSpider(Spider):
+ name = "adaptive"
+ start_urls = ["https://example.com"]
+
+ concurrent_requests = 8
+ concurrent_requests_per_domain = 1
+
+ autothrottle_enabled = True
+ autothrottle_start_delay = 2.0
+ autothrottle_max_delay = 30.0
+
+ async def parse(self, response: Response):
+ yield {"title": response.css("title::text").get("")}
+```
+
+每次响应后,延迟都会向服务器实际的响应时间靠近。例如,网站用 0.5 秒响应,延迟会稳定在 0.5 秒左右,大致相当于同一时间有一个请求正在处理。每个域名的目标并发数按以下顺序确定:已设置的 `autothrottle_target_concurrency`,否则使用 `concurrent_requests_per_domain`,再否则使用 1。通常无需额外设置目标值,因为已经配置的域名并发上限会作为目标,延迟也会除以这个值。响应时间突然升高时会立即生效,不会先取平均。因此,服务器一旦开始吃力,Spider 就会减速,而提速只会逐步进行。
+
+### 遇到封锁时减速 {#backing-off-when-blocked}
+
+只看响应时间无法识别频率限制。`429`、`403` 或验证码页面通常比正常内容返回得*更快*。如果只看时间,反而会认为可以加速。因此,异常响应会让该域名的延迟**翻倍**,包括非 2xx 状态码,以及被 `is_blocked()` 判定为封锁的响应:
+
+```
+0.5s -> 1s -> 2s -> 4s -> 8s ... (up to autothrottle_max_delay)
+```
+
+只要网站继续拒绝请求,Spider 就会继续减速。当正常响应恢复后,平均计算会逐渐降低延迟,让它重新接近服务器的实际速度,无需重启。
+
+如果网站在 `429` 或 `503` 响应中,通过 `Retry-After` 响应头明确给出等待时间,就会使用该值,而不是将延迟翻倍。支持数字形式(`Retry-After: 120`)和 HTTP 日期形式。
+
+设置 `autothrottle_block_backoff = False` 可关闭这一行为,回到只根据响应时间调整延迟的方式。此时,封锁只能阻止 Spider 继续加速。
+
+可以在统计信息中查看每个域名最终的延迟:
+
+```python
+result = AdaptiveSpider().start()
+print(result.stats.autothrottle_delays) # {'example.com': 0.62}
+```
+
+!!! note "注意事项"
+
+ * `download_delay` 和 robots.txt 要求的延迟构成下限,但 `autothrottle_max_delay` 仍会限制这个下限。最大值至少应达到已配置或 robots.txt 要求的等待时间。<br/>
+ * `concurrent_requests_per_domain` 在这里有两个作用:限制每个域名正在处理的请求数,并作为 AutoThrottle 的目标值。因此,通常无需单独配置目标。建议设置这个限制,因为等待中的请求也会占用全局并发名额。如果不限制单个域名,这些等待请求可能占满其他域名也需要使用的名额。<br/>
+ * 测量的响应时间包括整个获取过程,也包括内部重试。对于浏览器会话,还包括页面渲染时间。<br/>
+ * `autothrottle_max_delay` 限制所有延迟,包括 `Retry-After`。如果网站要求的等待时间超过上限,请提高 `autothrottle_max_delay`,以遵守该要求。<br/>
+ * 自动计算出的延迟不会保存到检查点。暂停后恢复时,每个域名都从 `autothrottle_start_delay` 重新开始。
+
+## 使用 uvloop {#using-uvloop}
+
+`start()` 方法支持 `use_uvloop` 参数,用于在可用时使用更快的 [uvloop](https://github.com/MagicStack/uvloop)/[winloop](https://github.com/nicktimko/winloop) 事件循环实现:
+
+```python
+result = MySpider().start(use_uvloop=True)
+```
+
+这可以提升以 I/O 操作为主的抓取任务的吞吐量。需要单独安装 `uvloop`(Linux/macOS)或 `winloop`(Windows)。
+
+## 暂停与恢复 {#pause-resume}
+
+Spider 通过检查点支持正常暂停和恢复。向 Spider 构造函数传入 `crawldir` 目录即可启用:
+
+```python
+spider = MySpider(crawldir="crawl_data/my_spider")
+result = spider.start()
+
+if result.paused:
+ print("Crawl was paused. Run again to resume.")
+else:
+ print("Crawl completed!")
+```
+
+### 工作方式 {#how-it-works}
+
+1. **暂停**:抓取时按 `Ctrl+C`。Spider 会等待所有运行中的请求完成,保存检查点(待处理请求和已访问请求的指纹集合),然后退出。
+2. **强制停止**:再次按 `Ctrl+C`,不等待正在运行的任务,立即停止。
+3. **恢复**:使用同一个 `crawldir` 再次运行 Spider。它会发现检查点,恢复队列和已访问指纹集合,跳过 `start_requests()`,从上次停止的位置继续。
+4. **清理**:抓取正常完成而非暂停后,检查点文件会自动删除。
+
+**抓取过程中也会定期保存检查点,默认每 5 分钟一次。**
+
+可以这样修改保存间隔:
+
+```python
+# Save checkpoint every 2 minutes
+spider = MySpider(crawldir="crawl_data/my_spider", interval=120.0)
+```
+
+磁盘写入采用原子操作,避免产生不完整的文件。
+
+!!! tip
+
+ 使用 `start()` 时,即使没有启用检查点系统,抓取中按 `Ctrl+C` 也会让 Spider 正常关闭。若还没关闭就再次按下,会强制立即关闭。
+
+### 判断是否正在恢复 {#knowing-if-youre-resuming}
+
+`on_start()` 钩子会接收 `resuming` 标志:
+
+```python
+async def on_start(self, resuming: bool = False):
+ if resuming:
+ self.logger.info("Resuming from checkpoint!")
+ else:
+ self.logger.info("Starting fresh crawl")
+```
+
+## 开发模式 {#development-mode}
+
+反复调整 Spider 的 `parse()` 逻辑时,每次都请求目标服务器既慢,又会产生不必要的请求。开发模式会在第一次运行时将所有响应缓存到磁盘,后续运行直接读取缓存。因此,可以修改选择器并反复运行 Spider,而无需再次获取这些页面。
+
+在 Spider 中设置 `development_mode = True` 即可启用:
+
+```python
+class MySpider(Spider):
+ name = "my_spider"
+ start_urls = ["https://example.com"]
+ development_mode = True
+
+ async def parse(self, response: Response):
+ yield {"title": response.css("title::text").get("")}
+```
+
+第一次运行会正常获取页面,并将每个响应存到磁盘。后续运行中,相同请求会直接使用缓存,跳过页面获取。如果设置了 `robots_txt_obey=True`,会先检查 robots.txt 规则,再查询缓存。
+
+### 缓存位置 {#cache-location}
+
+默认缓存目录是相对于当前工作目录的 `.scrapling_cache/{spider.name}/`。当前工作目录是运行 Spider 命令的位置,**不是** Spider 脚本所在的位置。可以用 `development_cache_dir` 指定其他目录:
+
+```python
+class MySpider(Spider):
+ name = "my_spider"
+ start_urls = ["https://example.com"]
+ development_mode = True
+ development_cache_dir = "/tmp/my_spider_cache"
+```
+
+### 工作方式 {#how-it-works_1}
+
+1. **缓存键**:每个响应以请求指纹为键。修改影响指纹的属性(`fp_include_kwargs`、`fp_include_headers`、`fp_keep_fragments`)后,会重新获取页面。
+2. **存储格式**:每个响应一个 JSON 文件,名称为 `{fingerprint_hex}.json`。响应体使用 Base64 编码,确保二进制内容完整保留。写入采用原子操作,先写临时文件再重命名。
+3. **重用缓存**:命中缓存时,引擎会跳过页面获取,包括 `download_delay`、频率限制以及 `is_blocked()` 重试流程。缓存响应会直接交给回调。
+4. **统计信息**:缓存请求仍会计入 `requests_count`、`response_bytes` 和各状态码的计数,因此统计输出与正常抓取一致。额外的 `cache_hits` 和 `cache_misses` 计数器可以显示缓存的使用情况。
+
+### 清空缓存 {#clearing-the-cache}
+
+缓存不会自动过期。如需强制重新抓取,请删除缓存目录,或直接调用管理器的 `clear()` 方法。
+
+!!! warning
+
+ 开发模式用于开发,不适合生产环境。缓存响应永不过期,读取缓存会跳过频率限制和封锁重试。不要将带有 `development_mode = True` 的 Spider 用于生产环境。
+
+## 流式输出 {#streaming}
+
+对于长时间运行的 Spider,或需要实时获取数据项的应用,请使用 `stream()`,而不是 `start()`:
+
+```python
+import anyio
+
+async def main():
+ spider = MySpider()
+ async for item in spider.stream():
+ print(f"Got item: {item}")
+ # Access real-time stats
+ print(f"Items so far: {spider.stats.items_scraped}")
+ print(f"Requests made: {spider.stats.requests_count}")
+
+anyio.run(main)
+```
+
+与 `start()` 的主要区别:
+
+- `stream()` 必须在异步上下文中调用。
+- 数据项会在提取后逐个产出,而不是收集到列表中。
+- 遍历过程中,可以通过 `spider.stats` 查看实时统计信息。
+
+!!! abstract
+
+ `spider.stats` 支持的完整统计信息列表见[下文](#results-statistics)。
+
+流式输出也可以与检查点系统一起使用。这样便于在 Spider 之上构建界面,显示实时数据,并支持暂停和恢复。
+
+```python
+import anyio
+
+async def main():
+ spider = MySpider(crawldir="crawl_data/my_spider")
+ async for item in spider.stream():
+ print(f"Got item: {item}")
+ # Access real-time stats
+ print(f"Items so far: {spider.stats.items_scraped}")
+ print(f"Requests made: {spider.stats.requests_count}")
+
+anyio.run(main)
+```
+在上例中,也可以使用 `spider.pause()` 从代码中停止 Spider。如果没有启用检查点系统,它只会结束抓取。
+
+## 生命周期钩子 {#lifecycle-hooks}
+
+Spider 提供了多个可重写的钩子,用于在抓取的不同阶段添加自定义行为:
+
+### on_start {#on_start}
+
+抓取开始前调用。可用于加载数据、初始化资源等准备工作:
+
+```python
+async def on_start(self, resuming: bool = False):
+ self.logger.info("Spider starting up")
+ # Load seed URLs from a database, initialize counters, etc.
+```
+
+### on_close {#on_close}
+
+抓取结束后调用,无论是完成还是暂停。可用于清理资源:
+
+```python
+async def on_close(self):
+ self.logger.info("Spider shutting down")
+ # Close database connections, flush buffers, etc.
+```
+
+### on_error {#on_error}
+
+请求因异常失败时调用。可用于记录错误或自定义恢复逻辑:
+
+```python
+async def on_error(self, request: Request, error: Exception):
+ self.logger.error(f"Failed: {request.url} - {error}")
+ # Log to error tracker, save failed URL for later, etc.
+```
+
+### on_scraped_item {#on_scraped_item}
+
+每个数据项加入结果前都会调用。返回原数据项或修改后的数据项即可保留它;返回 `None` 则丢弃:
+
+```python
+async def on_scraped_item(self, item: dict) -> dict | None:
+ # Drop items without a title
+ if not item.get("title"):
+ return None
+
+ # Modify items (e.g., add timestamps)
+ item["scraped_at"] = "2026-01-01"
+ return item
+```
+
+!!! tip
+
+ 也可以通过此钩子将数据项交给自己的处理流水线,并从 Spider 的结果中移除。
+
+### start_requests {#start_requests}
+
+重写 `start_requests()`,可以自行生成初始请求,不再使用 `start_urls`:
+
+```python
+async def start_requests(self):
+ # POST request to log in first
+ yield Request(
+ "https://example.com/login",
+ method="POST",
+ data={"user": "admin", "pass": "secret"},
+ callback=self.after_login,
+ )
+
+async def after_login(self, response: Response):
+ # Now crawl the authenticated pages
+ yield response.follow("/dashboard", callback=self.parse)
+```
+
+## 结果与统计信息 {#results-statistics}
+
+`start()` 返回的 `CrawlResult` 同时包含提取的数据项和详细统计信息:
+
+```python
+result = MySpider().start()
+
+# Items
+print(f"Total items: {len(result.items)}")
+result.items.to_json("output.json", indent=True)
+
+# Did the crawl complete?
+print(f"Completed: {result.completed}")
+print(f"Paused: {result.paused}")
+
+# Statistics
+stats = result.stats
+print(f"Requests: {stats.requests_count}")
+print(f"Failed: {stats.failed_requests_count}")
+print(f"Blocked: {stats.blocked_requests_count}")
+print(f"Offsite filtered: {stats.offsite_requests_count}")
+print(f"Robots.txt disallowed: {stats.robots_disallowed_count}")
+print(f"Cache hits: {stats.cache_hits}")
+print(f"Cache misses: {stats.cache_misses}")
+print(f"Items scraped: {stats.items_scraped}")
+print(f"Items dropped: {stats.items_dropped}")
+print(f"Response bytes: {stats.response_bytes}")
+print(f"Duration: {stats.elapsed_seconds:.1f}s")
+print(f"Speed: {stats.requests_per_second:.1f} req/s")
+```
+
+### 详细统计信息 {#detailed-stats}
+
+`CrawlStats` 对象记录详细信息:
+
+```python
+stats = result.stats
+
+# Status code distribution
+print(stats.response_status_count)
+# {'status_200': 150, 'status_404': 3, 'status_403': 1}
+
+# Bytes downloaded per domain
+print(stats.domains_response_bytes)
+# {'example.com': 1234567, 'api.example.com': 45678}
+
+# Requests per session
+print(stats.sessions_requests_count)
+# {'http': 120, 'stealth': 34}
+
+# Proxies used during the crawl
+print(stats.proxies)
+# ['http://proxy1:8080', 'http://proxy2:8080']
+
+# Log level counts
+print(stats.log_levels_counter)
+# {'debug': 200, 'info': 50, 'warning': 3, 'error': 1, 'critical': 0}
+
+# Timing information
+print(stats.start_time) # Unix timestamp when crawl started
+print(stats.end_time) # Unix timestamp when crawl finished
+print(stats.download_delay) # The download delay used (seconds)
+
+# Concurrency settings used
+print(stats.concurrent_requests) # Global concurrency limit
+print(stats.concurrent_requests_per_domain) # Per-domain concurrency limit
+
+# AutoThrottle
+print(stats.autothrottle_enabled) # Whether the adaptive delay was on
+print(stats.autothrottle_delays) # Final delay per domain, {'example.com': 0.62}
+
+# Custom stats (set by your spider code)
+print(stats.custom_stats)
+# {'login_attempts': 3, 'pages_with_errors': 5}
+
+# Export everything as a dict
+print(stats.to_dict())
+```
+
+## 日志 {#logging}
+
+Spider 内置日志记录器,可通过 `self.logger` 使用。它已配置好 Spider 名称,并支持以下选项:
+
+| 属性 | 默认值 | 说明 |
+|------|--------|------|
+| `logging_level` | `logging.DEBUG` | 最低日志级别 |
+| `logging_format` | `"[%(asctime)s]:({spider_name}) %(levelname)s: %(message)s"` | 日志消息格式 |
+| `logging_date_format` | `"%Y-%m-%d %H:%M:%S"` | 日志中的日期格式 |
+| `log_file` | `None` | 日志文件路径,除控制台输出外也写入文件 |
+
+```python
+import logging
+
+class MySpider(Spider):
+ name = "my_spider"
+ start_urls = ["https://example.com"]
+ logging_level = logging.INFO
+ log_file = "logs/my_spider.log"
+
+ async def parse(self, response: Response):
+ self.logger.info(f"Processing {response.url}")
+ yield {"title": response.css("title::text").get("")}
+```
+
+如果日志文件的目录不存在,会自动创建。控制台和文件输出使用相同格式。
diff --git a/docs/locales/zh/spiders/architecture.md b/docs/locales/zh/spiders/architecture.md
new file mode 100644
index 0000000..f7ad9fb
--- /dev/null
+++ b/docs/locales/zh/spiders/architecture.md
@@ -0,0 +1,107 @@
+---
+title: "Scrapling 网络爬虫的工作方式"
+description: "了解 Spider、请求、会话、调度器和抓取引擎如何协作。对比 Scrapy 的工作流程,选择适合的入门方式。"
+---
+
+# Spider 架构 {#spiders-architecture}
+
+!!! success "前提条件"
+
+ 1. 已阅读 [Fetcher 基础](../fetching/choosing.md),了解不同 Fetcher 的类型和适用场景。
+ 2. 已阅读[主要类](../parsing/main_classes.md),了解 [Selector](../parsing/main_classes.md#selector) 和 [Response](../fetching/choosing.md#response-object) 类。
+
+Scrapling 的 Spider 系统是一个受 Scrapy 启发的异步抓取框架,支持并发请求、多会话以及暂停和恢复。它将 Scrapling 的解析引擎和 Fetcher 整合到统一的抓取 API 中,并提供请求调度、并发控制和检查点功能。
+
+如果熟悉 Scrapy,你会很快上手。如果不熟悉也不用担心,这个系统的设计很直观。
+
+## 数据流 {#data-flow}
+
+下图展示了抓取过程中数据在 Spider 系统中的流转方式:
+
+<img src="../assets/spider_architecture.png" title="@TrueSkills 绘制的 Spider 架构图" alt="@TrueSkills 绘制的 Spider 架构图" style="width: 70%;"/>
+
+运行 Spider 时,主要流程如下:
+
+1. **Spider** 生成第一批 `Request` 对象。默认会为 `start_urls` 中的每个 URL 创建一个请求,也可以重写 `start_requests()` 来定义自己的逻辑。
+2. **调度器**接收请求,将其放入优先级队列,并创建请求指纹。优先级较高的请求先出队。
+3. **抓取引擎**向**调度器**请求下一个待处理请求,同时遵守全局和每个域名的并发限制,以及下载延迟。如果启用了 `robots_txt_obey`,引擎会先检查该域名的 robots.txt 规则,静默丢弃不允许的请求。**抓取引擎**收到请求后,将其交给**会话管理器**。后者根据请求的 `sid`(会话 ID)选择对应会话。
+4. **会话**获取页面,并向**抓取引擎**返回 [Response](../fetching/choosing.md#response-object) 对象。引擎记录统计信息,并检查响应是否被封锁。如果被封锁,会重试请求,最多 `max_blocked_retries` 次。封锁检测和重试逻辑都可以自定义。
+5. **抓取引擎**将 [Response](../fetching/choosing.md#response-object) 传给请求的回调。回调可以产出一个字典,作为提取的数据项;也可以产出后续请求,由调度器加入队列。
+6. 从第 2 步开始重复,直到调度器为空且没有正在运行的任务,或者 Spider 被暂停。
+7. 如果启动 Spider 时设置了 `crawldir`,**抓取引擎**会定期将检查点保存到磁盘,其中包含待处理请求和已访问 URL 的集合。正常关闭时(Ctrl+C),还会保存最后一个检查点。下次使用同一个 `crawldir` 运行时,Spider 会恢复调度器状态,跳过 `start_requests()`,从上次停止的位置继续。
+
+
+## 组件 {#components}
+
+### Spider {#spider}
+
+这是主要使用的类。创建 `Spider` 的子类,定义 `start_urls` 和 `parse()` 方法,并按需配置会话、重写生命周期钩子。
+
+```python
+from scrapling.spiders import Spider, Response, Request
+
+class MySpider(Spider):
+ name = "my_spider"
+ start_urls = ["https://example.com"]
+
+ async def parse(self, response: Response):
+ for link in response.css("a::attr(href)").getall():
+ yield response.follow(link, callback=self.parse_page)
+
+ async def parse_page(self, response: Response):
+ yield {"title": response.css("h1::text").get("")}
+```
+
+### 抓取引擎 {#crawler-engine}
+
+引擎负责整个抓取流程。它管理主循环,执行并发限制,通过会话管理器发送请求,并处理回调结果。无需直接操作引擎,`Spider.start()` 和 `Spider.stream()` 会代为处理。
+
+### 调度器 {#scheduler}
+
+这是一个内置 URL 去重功能的优先级队列。请求指纹由 URL、HTTP 方法、请求体和会话 ID 生成。调度器通过 `snapshot()` 和 `restore()` 支持检查点系统,用于保存和恢复抓取状态。
+
+### 会话管理器 {#session-manager}
+
+管理一个或多个有名称的会话实例。每个会话可以是以下类型之一:
+
+- [FetcherSession](../fetching/static.md)
+- [AsyncStealthySession](../fetching/stealthy.md)
+
+收到请求后,会话管理器会根据请求的 `sid` 字段,将请求交给对应会话。会话默认随 Spider 启动,也可以延迟到第一次使用时启动。
+
+### 检查点系统 {#checkpoint-system}
+
+这是一个可选系统。启用后,会将爬虫状态(待处理请求和已访问 URL 的指纹集合)保存为磁盘上的 pickle 文件。写入采用原子操作,先写入临时文件再重命名,以防文件损坏。检查点会按可配置的时间间隔保存,也会在正常关闭时保存。抓取成功完成而非暂停后,检查点文件会自动清理。
+
+### 响应缓存 {#response-cache}
+
+这是一个可选缓存。启用开发模式后,它会将所有获取的响应保存到磁盘,并在后续运行中重用。每个响应以请求指纹为键,保存为 JSON。响应体使用 Base64 编码,保留二进制内容。它用于反复调整 `parse()` 逻辑,避免重复请求目标服务器,不适合生产环境。
+
+### 输出 {#output}
+
+提取的数据项收集在 `ItemList` 中。它是 list 的子类,提供 `to_json()`、`to_jsonl()`、`to_csv()` 和 `to_xml()` 导出方法。抓取统计信息记录在 `CrawlStats` 数据类中,包含许多实用信息。
+
+
+## 与 Scrapy 对比 {#comparison-with-scrapy}
+
+如果从 Scrapy 转过来,可以参考下面的对应关系:
+
+| 概念 | Scrapy | Scrapling |
+|------|--------|-----------|
+| 定义 Spider | `scrapy.Spider` 子类 | `scrapling.spiders.Spider` 子类 |
+| 初始请求 | `start_requests()` | `async start_requests()` |
+| 回调 | `def parse(self, response)` | `async def parse(self, response)` |
+| 跟随链接 | `response.follow(url)` | `response.follow(url)` |
+| 输出数据项 | `yield dict` 或 `yield Item` | `yield dict` |
+| 请求调度 | 调度器 + Dupefilter | 内置去重功能的调度器 |
+| 下载 | 下载器 + 中间件 | 支持多会话的会话管理器 |
+| 数据项处理 | Item Pipelines | `on_scraped_item()` 钩子 |
+| 封锁检测 | 自定义中间件 | 内置 `is_blocked()` + `retry_blocked_request()` 钩子 |
+| 并发 | `CONCURRENT_REQUESTS` 设置 | `concurrent_requests` 类属性 |
+| 域名过滤 | `allowed_domains` | `allowed_domains` |
+| robots.txt | `ROBOTSTXT_OBEY` 设置 | `robots_txt_obey` 类属性 |
+| 暂停与恢复 | `JOBDIR` 设置 | 构造函数参数 `crawldir` |
+| 导出 | Feed 导出 | `result.items.to_json()` / `to_jsonl()` / `to_csv()` / `to_xml()`,或通过钩子自定义 |
+| 运行 | `scrapy crawl spider_name` | `MySpider().start()` |
+| 流式输出 | 不支持 | `async for item in spider.stream()` |
+| 多会话 | 不支持 | 每个 Spider 可使用多个不同类型的会话 |
diff --git a/docs/locales/zh/spiders/generic-templates.md b/docs/locales/zh/spiders/generic-templates.md
new file mode 100644
index 0000000..f3aaa32
--- /dev/null
+++ b/docs/locales/zh/spiders/generic-templates.md
@@ -0,0 +1,278 @@
+---
+title: "用于链接、Sitemap、Feed 和 Markdown 的 Spider 模板"
+description: "选择 CrawlSpider、SitemapSpider、XMLFeedSpider、CSVFeedSpider 或 ContentSpider。设置规则,收集页面、Feed 数据行或 Markdown 文档集。"
+---
+
+# 通用 Spider 模板 {#generic-spider-templates}
+
+大多数抓取任务属于两种模式之一:“跟随符合指定模式的链接”,或“抓取网站 Sitemap 中列出的所有 URL”。Scrapling 为这两种情况提供了模板,避免每次都重写相同的 `parse()` 基础代码。
+
+`CrawlSpider` 和 `SitemapSpider` 都基于 `LinkExtractor`。它能从 `Response` 中提取 URL,也能通过 `matches()` 过滤单个 URL。`SitemapSpider` 还会在内部解析 sitemap.xml 和 sitemap_index.xml 的内容,无论是否经过 gzip 压缩。
+
+也可以在普通的 `Spider.parse()` 中直接使用 `LinkExtractor`。模板只是帮你省去连接这些组件的工作。
+
+## CrawlSpider {#crawlspider}
+
+`CrawlSpider` 会根据声明的规则自动跟随链接。
+
+```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+/")), # follow pagination, no callback
+ ]
+
+ async def parse_author(self, response):
+ yield {
+ '.author-title': response.css('.author-title::text').get(),
+ "birthday": response.css('.author-born-date::text').get(),
+ "url": response.url,
+ }
+
+result = QuotesSpider().start()
+```
+
+一条 `CrawlRule` 将 `LinkExtractor` 与可选的 `callback` 配对。回调是 Spider 上的绑定方法。规则还可包含 `priority`,用于覆盖生成的 `Request` 的优先级,以及 `process_request`,用于在产出每个 `Request` 前修改它,后者也是一个绑定方法。默认的 `parse()` 会对每个响应应用所有规则,并为每个匹配的 URL 产出一个 `Request`。
+
+如果规则没有回调,匹配的 URL 会交给 Spider 默认的 `parse()`。这很适合分页:提取下一页链接即可继续抓取,无需单独编写处理方法。
+
+### 抓取顺序 {#crawl-order}
+
+在 `CrawlSpider` 或其子类(包括 `ContentSpider`)中设置 `crawl_strategy`,可以选择下一条待处理请求:
+
+| `crawl_strategy` | `Request.priority` 相同时的顺序 |
+|------------------|--------------------------------|
+| `"bfs"`(默认) | 最早入队的请求优先 |
+| `"dfs"` | 最晚入队的请求优先 |
+
+调度器始终先处理 `Request.priority` 较高的请求。这个策略只决定优先级相同的请求之间的顺序。
+
+设置 `concurrent_requests = 1`,即可按所选队列顺序逐个处理请求。重复 URL 仍会被过滤;再次发现同一个 URL 不会改变其请求在队列中的位置。并发请求可能以不同顺序完成,不同层级或分支也可能同时处理。
+
+从检查点恢复时,请保持相同的 `crawl_strategy`。
+
+### 将规则与自定义逻辑结合 {#combining-rules-with-custom-logic}
+
+重写 `parse()` 并调用 `super().parse(response)`,即可同时使用规则和自己的产出逻辑:
+
+```python
+class MySpider(CrawlSpider):
+ def rules(self):
+ return [CrawlRule(LinkExtractor(allow=r"/posts/"), callback=self.parse_post)]
+
+ async def parse(self, response):
+ yield {"page_url": response.url}
+ async for req in super().parse(response):
+ yield req
+```
+
+### 用 `process_request` 修改请求 {#mutating-requests-with-process_request}
+
+```python
+def add_priority(self, request, response):
+ request.priority = 10
+ return request
+
+def rules(self):
+ return [CrawlRule(
+ LinkExtractor(allow=r"/posts/"),
+ callback=self.parse_post,
+ process_request=self.add_priority,
+ )]
+```
+
+## SitemapSpider {#sitemapspider}
+
+`SitemapSpider` 从 sitemap.xml 中的 URL 开始抓取。它使用与 `CrawlSpider` 相同的 `rules()` API,因此用法也相同。
+
+```python
+from scrapling.spiders import SitemapSpider, CrawlRule, LinkExtractor
+
+class MySitemap(SitemapSpider):
+ name = "sm"
+ sitemap_urls = ["https://example.com/sitemap.xml"]
+
+ def rules(self):
+ return [
+ CrawlRule(LinkExtractor(allow=r"/posts/"), callback=self.parse_post),
+ CrawlRule(LinkExtractor(allow=r"/products/"), callback=self.parse_product),
+ ]
+
+ async def parse_post(self, response):
+ yield {"title": response.css("h1::text").get()}
+
+ async def parse_product(self, response):
+ yield {"sku": response.css(".sku::text").get()}
+
+result = MySitemap().start()
+```
+
+### URL 的分配方式 {#how-urls-are-dispatched}
+
+对于 Sitemap 中的每个 URL,`SitemapSpider` 会依次检查各规则的 `LinkExtractor.matches(url)`。第一条匹配的规则生效,并产出使用该规则回调的 `Request`。如果没有规则匹配,且 `rules()` 非空,该 URL 会被丢弃。如果 `rules()` 返回空列表,所有 URL 都会交给 Spider 的 `parse()` 方法。若未重写此方法,它默认会抛出 `NotImplementedError`。
+
+### Sitemap 索引 {#sitemap-indexes}
+
+遇到 `<sitemapindex>`,也就是列出其他 Sitemap 的索引时,`SitemapSpider` 会自动进入每个子 Sitemap。可以将 `sitemap_follow` 设为一个 `LinkExtractor`,过滤要跟随的子 Sitemap:
+
+```python
+class MySitemap(SitemapSpider):
+ name = "sm"
+ sitemap_urls = ["https://example.com/sitemap.xml"]
+ sitemap_follow = LinkExtractor(allow=r"/posts-sitemap-\d+\.xml") # only post sitemaps
+```
+
+### robots.txt 支持 {#robotstxt-support}
+
+将 `robots.txt` 的 URL 直接放入 `sitemap_urls`,`SitemapSpider` 会自动识别它,提取其中列出的所有 Sitemap,并逐个跟随:
+
+```python
+class MySitemap(SitemapSpider):
+ name = "sm"
+ sitemap_urls = ["https://example.com/robots.txt"]
+```
+
+### 其他语言的 URL {#alternate-language-urls}
+
+设置 `sitemap_alternate_links = True`,也会通过你的规则处理 `<xhtml:link rel="alternate" hreflang="...">` 中的 URL。
+
+## XMLFeedSpider {#xmlfeedspider}
+
+`XMLFeedSpider` 遍历 XML Feed 中的节点,例如 RSS、Atom 和商品 Feed。将 `itertag` 设为需要的节点名称,默认为 `"item"`,并重写 `parse_node()`。每个匹配节点都会调用一次此方法:
+
+```python
+from scrapling.spiders import XMLFeedSpider
+
+class RSSSpider(XMLFeedSpider):
+ name = "rss"
+ start_urls = ["https://example.com/feed.xml"]
+ itertag = "item"
+
+ async def parse_node(self, response, node):
+ yield {
+ "title": node.findtext("title"),
+ "link": node.findtext("link"),
+ "date": node.findtext("pubDate"),
+ }
+
+result = RSSSpider().start()
+```
+
+与其他回调一样,`parse_node()` 也可以产出 `Request` 对象,例如 `response.follow(node.findtext("link"), callback=self.parse_post)`,以抓取 Feed 链接指向的页面。
+
+### 节点匹配与解析 {#how-nodes-are-matched-and-parsed}
+
+传给 `parse_node()` 的每个节点都是去除了所有命名空间的 `lxml` 元素。因此,`node.findtext("title")`、`node.find("thumbnail").get("url")` 和区分大小写的 `node.xpath(...)` 都能直接使用,无需命名空间映射。简单的 `itertag`,例如 `"entry"`,会按节点名称匹配,不考虑命名空间。这适合 Atom 和大多数带命名空间的 Feed。若要匹配某个特定命名空间中的节点,请使用带前缀的 `itertag`,并在 `namespaces` 中定义该前缀:
+
+```python
+class ThumbnailSpider(XMLFeedSpider):
+ name = "thumbs"
+ start_urls = ["https://example.com/feed.xml"]
+ itertag = "media:thumbnail"
+ namespaces = (("media", "http://search.yahoo.com/mrss/"),)
+
+ async def parse_node(self, response, node):
+ yield {"thumbnail": node.get("url")}
+```
+
+gzip 压缩的 Feed(`.xml.gz`,或使用 gzip 内容类型返回的 Feed)会自动解压,并采用与 Sitemap Spider 相同的保护措施。格式错误的 XML 只会记录警告,不会导致抓取崩溃。
+
+## CSVFeedSpider {#csvfeedspider}
+
+`CSVFeedSpider` 遍历 CSV Feed 中的数据行。重写 `parse_row()`,它会接收每一行对应的字典,键为列名:
+
+```python
+from scrapling.spiders import CSVFeedSpider
+
+class PriceSpider(CSVFeedSpider):
+ name = "prices"
+ start_urls = ["https://example.com/products.csv"]
+
+ async def parse_row(self, response, row):
+ yield {"product": row["title"], "price": float(row["price"])}
+
+result = PriceSpider().start()
+```
+
+默认使用 Feed 的第一行作为表头。如果没有表头,可自行通过 `headers` 指定列名。对于不使用标准逗号格式的 Feed,可以设置 `delimiter`/`quotechar`:
+
+```python
+class PriceSpider(CSVFeedSpider):
+ name = "prices"
+ start_urls = ["https://example.com/products.csv"]
+ headers = ["title", "price", "url"]
+ delimiter = ";"
+```
+
+这里也会自动解压 gzip 格式的 Feed,与上面的 **XMLFeedSpider** 相同。
+
+<a id="sitetomarkdownspider"></a>
+
+## ContentSpider {#contentspider}
+
+`ContentSpider` 基于 **CrawlSpider**,抓取网站并将每个页面转换为适合 LLM 使用的干净 Markdown。每个页面产出一个数据项,还可以选择为每页写入一个 Markdown 文件:
+
+```python
+from scrapling.spiders import ContentSpider
+
+class DocsSpider(ContentSpider):
+ name = "docs"
+ start_urls = ["https://example.com/docs/"]
+ allowed_domains = {"example.com"}
+ output_dir = "docs_markdown"
+
+result = DocsSpider().start()
+```
+
+它要求设置 `allowed_domains`,以将抓取范围限制在目标网站内。完整指南、所有选项以及如何将输出交给 RAG 流水线,详见[构建 RAG 系统](../ai/building-rag-systems.md)。
+
+## 直接使用 `LinkExtractor` {#using-linkextractor-directly}
+
+不一定要使用模板。`LinkExtractor` 可以在任何普通 `Spider` 中使用:
+
+```python
+from scrapling.spiders import Spider, LinkExtractor
+
+class CustomSpider(Spider):
+ name = "custom"
+ start_urls = ["https://example.com"]
+
+ def __init__(self):
+ super().__init__()
+ self._links = LinkExtractor(allow=r"/posts/", deny_domains="ads.example.com")
+
+ async def parse(self, response):
+ for url in self._links.extract(response):
+ yield response.follow(url, callback=self.parse_post)
+
+ async def parse_post(self, response):
+ yield {"title": response.css("h1::text").get()}
+```
+
+## LinkExtractor 参数参考 {#linkextractor-reference}
+
+| 参数 | 默认值 | 说明 |
+|------|--------|------|
+| `allow` | `()` | 要保留的 URL 模式。为空表示全部匹配。可传字符串、编译后的 `Pattern`,或包含这两者的可迭代对象。 |
+| `deny` | `()` | 要丢弃的 URL 模式,始终优先于 `allow`。 |
+| `allow_domains` | `()` | 要保留的主机名,自动匹配子域名(`example.com` 也匹配 `api.example.com`)。 |
+| `deny_domains` | `()` | 要丢弃的主机名。 |
+| `restrict_css` | `()` | 将 DOM 提取范围限制在指定区域的 CSS 选择器。 |
+| `restrict_xpath` | `()` | 将 DOM 提取范围限制在指定区域的 XPath 选择器。 |
+| `tags` | `("a", "area")` | 要从中查找链接的元素标签。 |
+| `attrs` | `("href",)` | 从这些标签的哪些属性中读取 URL。 |
+| `canonicalize` | `True` | 排序查询参数,并规范化路径。 |
+| `strip` | `True` | 去除所提取 URL 两端的空白。 |
+| `keep_fragment` | `False` | 规范化时保留 `#fragment`。 |
+| `deny_extensions` | `IGNORED_EXTENSIONS` | 要丢弃的文件扩展名,例如 PDF、ZIP、图片和视频。 |
+| `process` | `None` | 过滤前对每个提取的 URL 调用的可选函数。返回假值(falsy)时丢弃该 URL。 |
+
+`LinkExtractor.extract(response)` 返回一个 `list[str]`,其中包含已过滤且去重的绝对 URL。
+
+`LinkExtractor.matches(url)` 返回 `bool`,只根据 URL 的允许与拒绝规则、域名和扩展名进行过滤。`SitemapSpider` 用它在没有 `Response` 的情况下分配 URL。
diff --git a/docs/locales/zh/spiders/getting-started.md b/docs/locales/zh/spiders/getting-started.md
new file mode 100644
index 0000000..6d6f173
--- /dev/null
+++ b/docs/locales/zh/spiders/getting-started.md
@@ -0,0 +1,199 @@
+---
+title: "用 Scrapling 创建第一个 Python 网络爬虫"
+description: "创建一个能提取数据、跟随分页链接并导出结果的 Spider。了解起始 URL、回调、域名限制和 robots.txt 设置。"
+---
+
+# 入门 {#getting-started}
+
+## 简介 {#introduction}
+
+!!! success "前提条件"
+
+ 1. 已阅读 [Fetcher 基础](../fetching/choosing.md),了解不同 Fetcher 的类型和适用场景。
+ 2. 已阅读[主要类](../parsing/main_classes.md),了解 [Selector](../parsing/main_classes.md#selector) 和 [Response](../fetching/choosing.md#response-object) 类。
+ 3. 已阅读[架构](architecture.md),大致了解 Spider 系统的工作方式。
+
+Spider 系统只需几行代码,就能创建并发抓取多个页面的爬虫。如果用过 Scrapy,你会很熟悉这些用法。如果没有,本指南会介绍入门所需的内容。
+
+## 第一个 Spider {#your-first-spider}
+
+Spider 是一个类,用来定义如何抓取网站并提取数据。下面是最简单的 Spider:
+
+```python
+from scrapling.spiders import Spider, Response
+
+class QuotesSpider(Spider):
+ name = "quotes"
+ start_urls = ["https://quotes.toscrape.com"]
+
+ async def parse(self, response: Response):
+ for quote in response.css("div.quote"):
+ yield {
+ "text": quote.css("span.text::text").get(""),
+ "author": quote.css("small.author::text").get(""),
+ }
+```
+
+每个 Spider 都需要三个部分:
+
+1. **`name`**:Spider 的唯一名称。
+2. **`start_urls`**:开始抓取的 URL 列表。
+3. **`parse()`**:处理每个响应并产出结果的异步生成器方法。
+
+主要的处理逻辑写在 `parse()` 方法中。这里使用的选择方法与 Scrapling 的 [Selector](../parsing/main_classes.md#selector)/[Response](../fetching/choosing.md#response-object) 相同,并通过 `yield` 输出字典形式的数据项。
+
+## 运行 Spider {#running-the-spider}
+
+创建实例并调用 `start()`,即可运行 Spider:
+
+```python
+result = QuotesSpider().start()
+```
+
+`start()` 方法会在内部处理所有异步操作,无需自行管理事件循环。Spider 运行时,所有活动都会记录到终端。抓取结束后,还会提供详细的统计信息。
+
+这些统计信息都在返回的 `CrawlResult` 对象中:
+
+```python
+result = QuotesSpider().start()
+
+# Access scraped items
+for item in result.items:
+ print(item["text"], "-", item["author"])
+
+# Check statistics
+print(f"Scraped {result.stats.items_scraped} items")
+print(f"Made {result.stats.requests_count} requests")
+print(f"Took {result.stats.elapsed_seconds:.1f} seconds")
+
+# Did the crawl finish or was it paused?
+print(f"Completed: {result.completed}")
+```
+
+## 跟随链接 {#following-links}
+
+大多数抓取任务需要跟随链接访问多个页面。使用 `response.follow()` 创建后续请求:
+
+```python
+from scrapling.spiders import Spider, Response
+
+class QuotesSpider(Spider):
+ name = "quotes"
+ start_urls = ["https://quotes.toscrape.com"]
+
+ async def parse(self, response: Response):
+ # Extract items from the current page
+ for quote in response.css("div.quote"):
+ yield {
+ "text": quote.css("span.text::text").get(""),
+ "author": quote.css("small.author::text").get(""),
+ }
+
+ # Follow the "next page" link
+ next_page = response.css("li.next a::attr(href)").get()
+ if next_page:
+ yield response.follow(next_page, callback=self.parse)
+```
+
+`response.follow()` 会自动将相对 URL 与当前页面的 URL 合并。默认情况下,它还会将当前页面的 URL 设为 `Referer` 请求头。
+
+对于不同类型的页面,可以让后续请求使用不同的回调方法:
+
+```python
+async def parse(self, response: Response):
+ for link in response.css("a.product-link::attr(href)").getall():
+ yield response.follow(link, callback=self.parse_product)
+
+async def parse_product(self, response: Response):
+ yield {
+ "name": response.css("h1::text").get(""),
+ "price": response.css(".price::text").get(""),
+ }
+```
+
+!!! note
+
+ 所有回调方法都必须是异步生成器,也就是使用 `async def` 和 `yield`。
+
+## 导出数据 {#exporting-data}
+
+`result.items` 返回的 `ItemList` 提供了内置导出方法:
+
+```python
+result = QuotesSpider().start()
+
+# Export as JSON
+result.items.to_json("quotes.json")
+
+# Export as JSON with pretty-printing
+result.items.to_json("quotes.json", indent=True)
+
+# Export as JSON Lines (one JSON object per line)
+result.items.to_jsonl("quotes.jsonl")
+
+# Export as CSV or XML
+result.items.to_csv("quotes.csv")
+result.items.to_xml("quotes.xml")
+```
+
+如果父目录不存在,这些方法都会自动创建。
+
+`to_csv()` 会为所有数据项中出现的每个键创建一列。因此,即使数据项的键不同,也能正常导出,缺少的单元格会留空。传入 `fields=[...]` 可自行选择列及其顺序,传入 `delimiter="\t"` 可生成 TSV 文件。`to_xml()` 会将每个数据项放在 `<item>` 元素中,并以 `<items>` 为根元素。可以通过 `root_tag` 和 `item_tag` 修改这两个名称。
+
+这两种格式都会将非简单标量值,例如嵌套字典或列表,写成 JSON,避免数据被悄悄丢弃。
+
+## 限制域名 {#filtering-domains}
+
+使用 `allowed_domains` 将 Spider 限制在指定域名内,避免意外跟随链接访问外部网站:
+
+```python
+class MySpider(Spider):
+ name = "my_spider"
+ start_urls = ["https://example.com"]
+ allowed_domains = {"example.com"}
+
+ async def parse(self, response: Response):
+ for link in response.css("a::attr(href)").getall():
+ # Links to other domains are silently dropped
+ yield response.follow(link, callback=self.parse)
+```
+
+子域名会自动匹配。例如,设置 `allowed_domains = {"example.com"}` 后,也会允许 `sub.example.com`、`blog.example.com` 等子域名。
+
+被过滤掉的请求会计入 `stats.offsite_requests_count`,方便查看丢弃了多少请求。
+
+## 遵守 robots.txt {#robotstxt-compliance}
+
+设置 `robots_txt_obey = True`,让 Spider 在抓取任何域名前先遵守其 robots.txt 规则:
+
+```python
+class PoliteSpider(Spider):
+ name = "polite"
+ start_urls = ["https://example.com"]
+ robots_txt_obey = True
+
+ async def parse(self, response: Response):
+ for link in response.css("a::attr(href)").getall():
+ yield response.follow(link, callback=self.parse)
+```
+
+启用后,Spider 会:
+
+1. **提前获取 robots.txt**:抓取开始前,并发获取 `start_urls` 中所有域名的 robots.txt。
+2. **检查每个请求**:根据域名的 robots.txt 中的 `Disallow` 规则检查请求。不允许的请求会被静默丢弃,并计入 `stats.robots_disallowed_count`。
+3. **遵守 `Crawl-delay` 和 `Request-rate` 指令**:取指令要求的延迟与配置的 `download_delay` 中较大的值。robots.txt 只会在需要时增加等待时间,不会缩短已配置的等待时间。启用 AutoThrottle 后,其最大延迟也会限制这个值。请将 `autothrottle_max_delay` 设得足够大,以满足规定的等待时间。
+
+robots.txt 文件通过 Spider 的默认会话获取,并按域名缓存到本次抓取结束。对于抓取过程中才发现、不在 `start_urls` 中的域名,会在首次请求该域名时获取其 robots.txt。
+
+**注意:**为了避免意外行为,`robots_txt_obey` 默认关闭。启用它不会改变并发设置(`concurrent_requests`、`concurrent_requests_per_domain`),只会调整请求之间的等待时间。
+
+如果不想手动选择 `download_delay`,可以设置 `autothrottle_enabled = True`。Spider 会根据各域名的响应速度自动调整等待时间,并在遇到封锁时降低速度。详见 [AutoThrottle](advanced.md#autothrottle)。
+
+## 下一步 {#whats-next}
+
+掌握基础后,可以继续阅读:
+
+- [请求与响应](requests-responses.md):了解请求优先级、去重、元数据等。
+- [会话](sessions.md):在同一个 Spider 中使用 HTTP、浏览器和隐身浏览器等不同类型的 Fetcher。
+- [代理管理与封锁处理](proxy-blocking.md):在请求之间轮换代理,并处理 Spider 遇到的封锁。
+- [高级功能](advanced.md):并发控制、AutoThrottle、暂停与恢复、流式输出、生命周期钩子和日志。
diff --git a/docs/locales/zh/spiders/platform-templates.md b/docs/locales/zh/spiders/platform-templates.md
new file mode 100644
index 0000000..52c18e6
--- /dev/null
+++ b/docs/locales/zh/spiders/platform-templates.md
@@ -0,0 +1,59 @@
+---
+title: "用 Python 抓取 Shopify 商品数据"
+description: "用 ShopifySpider 抓取 Shopify 商店的商品目录。设置商店 URL,收集商品变体,并了解每个数据项的字段。"
+---
+
+# 平台专用 Spider 模板 {#platform-spider-templates}
+
+通用模板针对抓取*模式*,例如跟随链接、遍历 Sitemap。平台模板针对的是*平台*:这些建站平台会在许多独立网站中提供相同的机器可读结构,因此 Spider 已经知道数据在哪里。只需指定域名即可。
+
+## ShopifySpider {#shopifyspider}
+
+`ShopifySpider` 通过 Shopify 的 JSON API 提取商店中的所有商品,不读取网站的 HTML。
+
+```python
+from scrapling.spiders import ShopifySpider
+
+class MyStore(ShopifySpider):
+ target_website = "example.com"
+
+result = MyStore().start()
+print(result.items[0])
+```
+
+将 `target_website` 设为商店域名。如果为空,Spider 会先尝试 `start_urls` 中的第一个条目,再尝试 `allowed_domains` 中的第一个条目。如果三者都为空,则抛出 `ValueError`。完整 URL 会自动转换为域名。
+
+### 工作方式 {#how-it-works}
+
+1. 逐页获取 `https://<store>/collections.json`,每页最多 250 个商品集合,这是平台规定的上限。
+2. 对于每个包含商品的集合,逐页获取 `/collections/<handle>/products.json`。
+3. 每个商品变体产出一个数据项。出现在多个集合中的同一变体只输出一次。
+
+### 数据项字段 {#item-fields}
+
+| 字段 | 来源 |
+|------|------|
+| `name` | 商品标题;如果变体标题不是默认值,还会附加变体标题 |
+| `price` | 变体价格,保留 Shopify 返回的原始字符串 |
+| `category` | 商品集合的 handle,也就是 URL 中的标识,并将每个词的首字母大写(`summer-sale` 变为 `Summer Sale`) |
+| `brand` | 商品供应商 |
+| `identifier` | 变体 ID |
+| `sku` | 变体 SKU;商店未设置时为 `""` |
+| `stock` | 变体有货时为 `None`,缺货时为 `0` |
+| `image_url` | 第一张商品图片,或 `""` |
+| `url` | 商品在该集合中的页面 |
+| `description` | 去除 HTML 标签后的商品 `body_html` |
+| `old_price` | 如果 `compare_at_price` 是真实的促销前价格,则使用该值,否则为 `""` |
+| `barcode` | 变体条码,或 `""`(大多数商店不会在这些接口中提供条码) |
+
+这些字段不是固定要求。可以在子类中重写 `_process_product()`,修改数据项结构,或从商品数据中提取其他字段。
+
+### 注意事项与限制 {#notes-and-limits}
+
+- JSON 接口只返回发布到在线商店渠道的商品。因此,集合的 `products_count` 可能大于实际能获取的数量。Spider 只用它判断是否需要获取该集合:非零就获取,不会把它当作预期总数。
+- 如果商店有额外防护或密码保护,这个模板很可能无法使用。即使能用,也通常需要自行重写许多方法。
+- `Spider` 的所有功能仍然适用,包括并发设置、延迟、robots.txt 规则、检查点和生命周期钩子。
+
+### 什么样的平台适合添加模板 {#what-qualifies-as-a-platform-template}
+
+只有像 Shopify 这样,在许多独立网站上提供统一、机器可读结构的平台,才适合加入平台模板。针对单个网站的 Spider 不会加入本库,无论该网站多受欢迎。
diff --git a/docs/locales/zh/spiders/proxy-blocking.md b/docs/locales/zh/spiders/proxy-blocking.md
new file mode 100644
index 0000000..0ee4e54
--- /dev/null
+++ b/docs/locales/zh/spiders/proxy-blocking.md
@@ -0,0 +1,249 @@
+---
+title: "轮换代理并重试被封锁的抓取请求"
+description: "在 Scrapling Spider 中使用代理和轮换策略。检测被封锁的响应、重试请求,并从 HTTP 会话切换到浏览器会话。"
+---
+
+# 代理管理与封锁处理 {#proxy-management-and-handling-blocks}
+
+## 简介 {#introduction}
+
+!!! success "前提条件"
+
+ 1. 已阅读[入门](getting-started.md),知道如何创建并运行一个简单的 Spider。
+ 2. 已阅读[会话](sessions.md),了解如何配置会话。
+
+大规模抓取时,通常需要在多个代理之间轮换,以避免频率限制和封锁。Scrapling 的 `ProxyRotator` 让这件事更简单。它支持所有会话类型,并能与 Spider 的封锁重试系统配合使用。
+
+如果还不了解代理,或不知道如何选择合适的代理,可以阅读[这篇指南](https://substack.thewebscraping.club/p/everything-about-proxies)。
+
+## ProxyRotator {#proxyrotator}
+
+`ProxyRotator` 类管理一个代理列表,并自动轮换使用。通过 `proxy_rotator` 参数,可以将它传给任意会话类型:
+
+```python
+from scrapling.spiders import Spider, Response
+from scrapling.fetchers import FetcherSession, ProxyRotator
+
+class MySpider(Spider):
+ name = "my_spider"
+ start_urls = ["https://example.com"]
+
+ def configure_sessions(self, manager):
+ rotator = ProxyRotator([
+ "http://proxy1:8080",
+ "http://proxy2:8080",
+ "http://user:pass@proxy3:8080",
+ ])
+ manager.add("default", FetcherSession(proxy_rotator=rotator))
+
+ async def parse(self, response: Response):
+ # Check which proxy was used
+ print(f"Proxy used: {response.meta.get('proxy')}")
+ yield {"title": response.css("title::text").get("")}
+```
+
+每个请求都会自动分配到轮换中的下一个代理。使用的代理保存在 `response.meta["proxy"]` 中,方便追踪每个页面由哪个代理获取。
+
+
+在浏览器会话中使用时,需要做一些调整:
+
+```python
+from scrapling.fetchers import AsyncStealthySession, ProxyRotator
+
+# String proxies work for all session types
+rotator = ProxyRotator([
+ "http://proxy1:8080",
+ "http://proxy2:8080",
+])
+
+# Dict proxies (Playwright format) work for browser sessions
+rotator = ProxyRotator([
+ {"server": "http://proxy1:8080", "username": "user", "password": "pass"},
+ {"server": "http://proxy2:8080"},
+])
+
+# Then inside the spider
+def configure_sessions(self, manager):
+ rotator = ProxyRotator(["http://proxy1:8080", "http://proxy2:8080"])
+ manager.add("browser", AsyncStealthySession(proxy_rotator=rotator))
+```
+
+!!! info
+
+ 1. 同一个会话中,不能同时使用 `proxy_rotator` 与固定的 `proxy` 或 `proxies` 参数。配置会话时选择其中一种方式,之后仍可为单个请求覆盖代理,后文会介绍。
+ 2. 默认情况下,浏览器会话使用一个持久浏览器上下文和一个标签页池。但浏览器无法为每个标签页设置独立代理。因此,使用 `ProxyRotator` 时,Fetcher 会为每个代理自动创建单独的上下文,每个上下文只有一个标签页。任务完成后,标签页和上下文都会关闭。
+
+## 自定义轮换策略 {#custom-rotation-strategies}
+
+`ProxyRotator` 默认循环轮换,按顺序使用代理,到列表末尾后再从头开始。
+
+可以提供自定义策略函数来改变这一行为,但函数必须符合以下签名:
+
+```python
+from scrapling.core._types import ProxyType
+
+def my_strategy(proxies: list, current_index: int) -> tuple[ProxyType, int]:
+ ...
+```
+
+它接收代理列表和当前索引,必须返回所选代理及下一个索引。
+
+下面是几个自定义轮换策略的例子。
+
+### 随机轮换 {#random-rotation}
+
+```python
+import random
+from scrapling.fetchers import ProxyRotator
+
+def random_strategy(proxies, current_index):
+ idx = random.randint(0, len(proxies) - 1)
+ return proxies[idx], idx
+
+rotator = ProxyRotator(
+ ["http://proxy1:8080", "http://proxy2:8080", "http://proxy3:8080"],
+ strategy=random_strategy,
+)
+```
+
+### 加权轮换 {#weighted-rotation}
+
+```python
+import random
+
+def weighted_strategy(proxies, current_index):
+ # First proxy gets 60% of traffic, others split the rest
+ weights = [60] + [40 // (len(proxies) - 1)] * (len(proxies) - 1)
+ proxy = random.choices(proxies, weights=weights, k=1)[0]
+ return proxy, current_index # Index doesn't matter for weighted
+
+rotator = ProxyRotator(proxies, strategy=weighted_strategy)
+```
+
+
+## 为单个请求指定代理 {#per-request-proxy-override}
+
+传入关键字参数 `proxy=`,可以为单个请求覆盖轮换器的选择:
+
+```python
+async def parse(self, response: Response):
+ # This request uses the rotator's next proxy
+ yield response.follow("/page1", callback=self.parse_page)
+
+ # This request uses a specific proxy, bypassing the rotator
+ yield response.follow(
+ "/special-page",
+ callback=self.parse_page,
+ proxy="http://special-proxy:8080",
+ )
+```
+
+当某些页面需要特定代理时,这很有用。例如,使用指定地区的代理获取该地区的内容。
+
+## 处理被封锁的请求 {#blocked-request-handling}
+
+Spider 内置封锁检测和重试功能。默认将以下 HTTP 状态码视为封锁:`401`、`403`、`407`、`429`、`444`、`500`、`502`、`503`、`504`。
+
+重试流程如下:
+
+1. 收到响应后,Spider 调用 `is_blocked(response)`。
+2. 如果被封锁,就复制请求并调用 `retry_blocked_request()`,让你在重试前修改请求。
+3. 重试请求以 `dont_filter=True` 重新加入队列,跳过去重,并降低优先级,避免立即重试。
+4. 最多重复 `max_blocked_retries` 次,默认 3 次。
+
+!!! tip
+
+ 1. 重试时,请求中原有的 `proxy`/`proxies` 参数会自动清除,让轮换器分配新的代理。
+ 2. `max_blocked_retries` 与会话自身的重试不同,两者不共用计数器。
+
+### 自定义封锁检测 {#custom-block-detection}
+
+重写 `is_blocked()` 可以添加自己的检测逻辑:
+
+```python
+class MySpider(Spider):
+ name = "my_spider"
+ start_urls = ["https://example.com"]
+
+ async def is_blocked(self, response: Response) -> bool:
+ # Check status codes (default behavior)
+ if response.status in {403, 429, 503}:
+ return True
+
+ # Check response content
+ body = response.body.decode("utf-8", errors="ignore")
+ if "access denied" in body.lower() or "rate limit" in body.lower():
+ return True
+
+ return False
+
+ async def parse(self, response: Response):
+ yield {"title": response.css("title::text").get("")}
+```
+
+### 自定义重试 {#customizing-retries}
+
+重写 `retry_blocked_request()` 可以在重试前修改请求。`max_blocked_retries` 控制被封锁请求的最大重试次数,默认 3 次:
+
+```python
+from scrapling.spiders import Spider, SessionManager, Request, Response
+from scrapling.fetchers import FetcherSession, AsyncStealthySession
+
+
+class MySpider(Spider):
+ name = "my_spider"
+ start_urls = ["https://example.com"]
+ max_blocked_retries = 5
+
+ def configure_sessions(self, manager: SessionManager) -> None:
+ manager.add('requests', FetcherSession(impersonate=['chrome', 'firefox', 'safari']))
+ manager.add('stealth', AsyncStealthySession(block_webrtc=True), lazy=True)
+
+ async def retry_blocked_request(self, request: Request, response: Response) -> Request:
+ request.sid = "stealth"
+ self.logger.info(f"Retrying blocked request: {request.url}")
+ return request
+
+ async def parse(self, response: Response):
+ yield {"title": response.css("title::text").get("")}
+```
+
+上例保留了原有的封锁检测逻辑。Spider 主要使用 HTTP 请求,遇到封锁后才切换到隐身浏览器。
+
+
+将这些功能组合起来:
+
+```python
+from scrapling.spiders import Spider, SessionManager, Request, Response
+from scrapling.fetchers import FetcherSession, AsyncStealthySession, ProxyRotator
+
+
+cheap_proxies = ProxyRotator([ "http://proxy1:8080", "http://proxy2:8080"])
+
+# A format acceptable by the browser
+expensive_proxies = ProxyRotator([
+ {"server": "http://residential_proxy1:8080", "username": "user", "password": "pass"},
+ {"server": "http://residential_proxy2:8080", "username": "user", "password": "pass"},
+ {"server": "http://mobile_proxy1:8080", "username": "user", "password": "pass"},
+ {"server": "http://mobile_proxy2:8080", "username": "user", "password": "pass"},
+])
+
+
+class MySpider(Spider):
+ name = "my_spider"
+ start_urls = ["https://example.com"]
+ max_blocked_retries = 5
+
+ def configure_sessions(self, manager: SessionManager) -> None:
+ manager.add('requests', FetcherSession(impersonate=['chrome', 'firefox', 'safari'], proxy_rotator=cheap_proxies))
+ manager.add('stealth', AsyncStealthySession(block_webrtc=True, proxy_rotator=expensive_proxies), lazy=True)
+
+ async def retry_blocked_request(self, request: Request, response: Response) -> Request:
+ request.sid = "stealth"
+ self.logger.info(f"Retrying blocked request: {request.url}")
+ return request
+
+ async def parse(self, response: Response):
+ yield {"title": response.css("title::text").get("")}
+```
+上例的逻辑是:先用数据中心代理等便宜的代理发送请求,遇到封锁后,再用住宅代理或移动代理等质量更高的代理重试。
diff --git a/docs/locales/zh/spiders/requests-responses.md b/docs/locales/zh/spiders/requests-responses.md
new file mode 100644
index 0000000..0df0ed7
--- /dev/null
+++ b/docs/locales/zh/spiders/requests-responses.md
@@ -0,0 +1,207 @@
+---
+title: "Spider 请求、回调与 Response.follow"
+description: "创建抓取请求、传递元数据,并用 response.follow 跟随链接。了解回调、优先级和请求去重。"
+---
+
+# 请求与响应 {#requests-responses}
+
+!!! success "前提条件"
+
+ 1. 已阅读[入门](getting-started.md),知道如何创建并运行一个简单的 Spider。
+
+本页详细介绍 `Request` 对象:如何创建请求、在回调之间传递数据、控制优先级和去重,以及用 `response.follow()` 跟随链接。
+
+## Request 对象 {#the-request-object}
+
+`Request` 表示一个待获取的 URL。可以直接创建请求,也可以通过 `response.follow()` 创建:
+
+```python
+from scrapling.spiders import Request
+
+# Direct construction
+request = Request(
+ "https://example.com/page",
+ callback=self.parse_page,
+ priority=5,
+)
+
+# Via response.follow (preferred in callbacks)
+request = response.follow("/page", callback=self.parse_page)
+```
+
+`Request` 支持以下参数:
+
+| 参数 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `url` | `str` | *必填* | 要获取的 URL |
+| `sid` | `str` | `""` | 会话 ID,将请求交给指定会话,详见[会话](sessions.md) |
+| `callback` | `callable` | `None` | 处理响应的异步生成器方法,默认为 `parse()` |
+| `priority` | `int` | `0` | 值越大,越先处理 |
+| `dont_filter` | `bool` | `False` | 为 `True` 时跳过去重,允许重复请求 |
+| `meta` | `dict` | `{}` | 传递给响应的任意元数据 |
+| `**kwargs` | | | 传给会话获取方法的其他关键字参数,例如 `headers`、`method`、`data` |
+
+额外的关键字参数会直接传给底层会话。例如,发送 POST 请求:
+
+```python
+yield Request(
+ "https://example.com/api",
+ method="POST",
+ data={"key": "value"},
+ callback=self.parse_result,
+)
+```
+
+## Response.follow() {#responsefollow}
+
+建议在回调中使用 `response.follow()` 创建后续请求。相比直接创建 `Request` 对象,它有以下优点:
+
+- **相对 URL** 会自动根据当前页面 URL 解析。
+- **Referer 请求头**默认设为当前页面 URL。
+- **会话参数**会从原请求继承,包括请求头、代理设置等,但不包括 `method`、`params`、`data`、`json`、`files` 和 `multipart`。因此,跟随链接时会发送普通 GET 请求。
+- **回调、会话 ID 和优先级**如果未指定,会从原请求继承。
+
+```python
+async def parse(self, response: Response):
+ # Minimal - inherits callback, sid, priority from current request
+ yield response.follow("/next-page")
+
+ # Override specific fields
+ yield response.follow(
+ "/product/123",
+ callback=self.parse_product,
+ priority=10,
+ )
+
+ # Pass additional metadata to
+ yield response.follow(
+ "/details",
+ callback=self.parse_details,
+ meta={"category": "electronics"},
+ )
+```
+
+| 参数 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `url` | `str` | *必填* | 要跟随的 URL,可为绝对或相对 URL |
+| `sid` | `str` | `""` | 会话 ID,为空时继承原请求的值 |
+| `callback` | `callable` | `None` | 回调方法,为 `None` 时继承原请求的值 |
+| `priority` | `int` | `None` | 优先级,为 `None` 时继承原请求的值 |
+| `dont_filter` | `bool` | `False` | 跳过去重 |
+| `meta` | `dict` | `None` | 与响应现有元数据合并的元数据 |
+| **`referer_flow`** | `bool` | `True` | 将当前 URL 设为 Referer 请求头 |
+| `**kwargs` | | | 与原请求的会话参数合并 |
+
+### 关闭 Referer 传递 {#disabling-referer-flow}
+
+默认情况下,`response.follow()` 会将 `Referer` 请求头设为当前页面 URL。可以这样关闭:
+
+```python
+yield response.follow("/page", referer_flow=False)
+```
+
+## 回调 {#callbacks}
+
+回调是 Spider 中用于处理响应的异步生成器方法。它必须通过 `yield` 产出以下三种类型之一:
+
+- **`dict`**:提取的数据项,会加入结果。
+- **`Request`**:后续请求,会加入队列。
+- **`None`**:静默忽略。
+
+```python
+class MySpider(Spider):
+ name = "my_spider"
+ start_urls = ["https://example.com"]
+
+ async def parse(self, response: Response):
+ # Yield items (dicts)
+ yield {"url": response.url, "title": response.css("title::text").get("")}
+
+ # Yield follow-up requests
+ for link in response.css("a::attr(href)").getall():
+ yield response.follow(link, callback=self.parse_page)
+
+ async def parse_page(self, response: Response):
+ yield {"content": response.css("article::text").get("")}
+```
+
+!!! tip "注意"
+
+ 所有回调方法都必须使用 `async def` 定义,并使用 `yield`,不能用 `return` 代替。即使回调只产出数据项,不创建后续请求,也必须是异步生成器。
+
+## 请求优先级 {#request-priority}
+
+优先级值较大的请求会先处理。如果某些页面需要优先处理,可以这样设置:
+
+```python
+async def parse(self, response: Response):
+ # High priority - process product pages first
+ for link in response.css("a.product::attr(href)").getall():
+ yield response.follow(link, callback=self.parse_product, priority=10)
+
+ # Low priority - pagination links processed after products
+ next_page = response.css("a.next::attr(href)").get()
+ if next_page:
+ yield response.follow(next_page, callback=self.parse, priority=0)
+```
+
+使用 `response.follow()` 时,如果没有指定新的优先级,就会继承原请求的优先级。
+
+## 去重 {#deduplication}
+
+Spider 会根据 URL、HTTP 方法、请求体和会话 ID 计算指纹,自动去除重复请求。如果两个请求的指纹相同,第二个请求会被静默丢弃。
+
+设置 `dont_filter=True` 可以允许重复请求,例如登录后再次访问同一页面:
+
+```python
+yield Request("https://example.com/dashboard", dont_filter=True, callback=self.parse_dashboard)
+
+# Or with response.follow
+yield response.follow("/dashboard", dont_filter=True, callback=self.parse_dashboard)
+```
+
+通过 Spider 的类属性,可以更精确地控制指纹包含的内容:
+
+| 属性 | 默认值 | 作用 |
+|------|--------|------|
+| `fp_include_kwargs` | `False` | 将额外的请求参数纳入指纹,也就是传给会话获取方法的参数,例如请求头 |
+| `fp_keep_fragments` | `False` | 计算指纹时保留 URL 片段(`#section`) |
+| `fp_include_headers` | `False` | 将请求头纳入指纹 |
+
+例如,需要将 `https://example.com/page#section1` 和 `https://example.com/page#section2` 视为不同 URL 时:
+
+```python
+class MySpider(Spider):
+ name = "my_spider"
+ fp_keep_fragments = True
+ # ...
+```
+
+## 请求元数据 {#request-meta}
+
+`meta` 字典可以在回调之间传递任意数据。当处理一个页面需要用到另一个页面的信息时,这很有用:
+
+```python
+async def parse(self, response: Response):
+ for product in response.css("div.product"):
+ category = product.css("span.category::text").get("")
+ link = product.css("a::attr(href)").get()
+ if link:
+ yield response.follow(
+ link,
+ callback=self.parse_product,
+ meta={"category": category},
+ )
+
+async def parse_product(self, response: Response):
+ yield {
+ "name": response.css("h1::text").get(""),
+ "price": response.css(".price::text").get(""),
+ # Access meta from the request
+ "category": response.meta.get("category", ""),
+ }
+```
+
+使用 `response.follow()` 时,当前响应的元数据会与新传入的元数据合并,新值优先。
+
+Spider 系统也会自动保存一些元数据。例如,启用代理轮换后,可以通过 `response.meta["proxy"]` 获取该请求使用的代理。
diff --git a/docs/locales/zh/spiders/sessions.md b/docs/locales/zh/spiders/sessions.md
new file mode 100644
index 0000000..14f7ab9
--- /dev/null
+++ b/docs/locales/zh/spiders/sessions.md
@@ -0,0 +1,231 @@
+---
+title: "在同一个爬虫中使用 HTTP 和浏览器会话"
+description: "设置有名称的会话,让 Spider 请求使用 HTTP 或浏览器 Fetcher。复用 Cookie、按需启动会话,并查看 API 历史记录。"
+---
+
+# Spider 会话 {#spiders-sessions}
+
+!!! success "前提条件"
+
+ 1. 已阅读[入门](getting-started.md),知道如何创建并运行一个简单的 Spider。
+ 2. 熟悉 [Fetcher 基础](../fetching/choosing.md),了解 HTTP 会话和 Stealthy 会话的区别。
+
+一个 Spider 可以同时使用多个 Fetcher 会话。例如,用快速的 HTTP 会话获取简单页面,用隐身浏览器会话获取受保护页面。本页介绍如何配置和使用会话。
+
+## 什么是会话? {#what-are-sessions}
+
+会话是一个预先配置好的 Fetcher 实例,会在整个抓取过程中保持运行。Spider 会复用会话,而不是为每个请求创建新连接或浏览器。这样速度更快,也更节省资源。
+
+默认情况下,每个 Spider 都会创建一个 [FetcherSession](../fetching/static.md)。重写 `configure_sessions()` 可以添加更多会话,或替换默认会话。这里只能使用各会话的异步版本,如下表所示:
+
+
+| 会话类型 | 适用场景 |
+|----------|----------|
+| [FetcherSession](../fetching/static.md) | 快速 HTTP 请求,不运行 JavaScript |
+| [AsyncStealthySession](../fetching/stealthy.md) | JavaScript、浏览器自动化、绕过反机器人保护 |
+
+
+## 配置会话 {#configuring-sessions}
+
+在 Spider 中重写 `configure_sessions()` 来配置会话。参数 `manager` 是一个 `SessionManager` 实例。使用 `manager.add()` 注册会话:
+
+```python
+from scrapling.spiders import Spider, Response
+from scrapling.fetchers import FetcherSession
+
+class MySpider(Spider):
+ name = "my_spider"
+ start_urls = ["https://example.com"]
+
+ def configure_sessions(self, manager):
+ manager.add("default", FetcherSession())
+
+ async def parse(self, response: Response):
+ yield {"title": response.css("title::text").get("")}
+```
+
+`manager.add()` 方法支持以下参数:
+
+| 参数 | 类型 | 默认值 | 说明 |
+|------|------|--------|------|
+| `session_id` | `str` | *必填* | 在请求中引用此会话的名称 |
+| `session` | `Session` | *必填* | 会话实例 |
+| `default` | `bool` | `False` | 将此会话设为默认会话 |
+| `lazy` | `bool` | `False` | 第一次使用时才启动会话 |
+
+!!! note "注意事项"
+
+ 1. 如果请求没有指定会话,就会使用默认会话。默认会话通过以下两种方式之一确定:
+ 1. 第一个加入管理器的会话会自动成为默认会话。
+ 2. 添加会话时传入 `default=True`。
+ 2. 不需要自行提前启动传入的会话实例。Spider 会检查所有会话,并启动尚未运行的会话。
+ 3. 如果希望某个会话只在需要时启动,添加时使用 `lazy` 参数即可。例如,让浏览器在真正需要时才启动,而不是随 Spider 一起启动。
+
+## 多会话 Spider {#multi-session-spider}
+
+下面是一个实际例子:用快速 HTTP 会话获取列表页,用隐身浏览器获取有反机器人保护的详情页:
+
+```python
+from scrapling.spiders import Spider, Response
+from scrapling.fetchers import FetcherSession, AsyncStealthySession
+
+class ProductSpider(Spider):
+ name = "products"
+ start_urls = ["https://shop.example.com/products"]
+
+ def configure_sessions(self, manager):
+ # Fast HTTP for listing pages (default)
+ manager.add("http", FetcherSession())
+
+ self.browser_session = AsyncStealthySession(
+ headless=True,
+ network_idle=True,
+ record_requests=True,
+ )
+ manager.add("stealth", self.browser_session)
+
+ async def parse(self, response: Response):
+ for link in response.css("a.product::attr(href)").getall():
+ # Route product pages through the stealth session
+ yield response.follow(link, sid="stealth", callback=self.parse_product)
+
+ next_page = response.css("a.next::attr(href)").get()
+ if next_page:
+ yield response.follow(next_page)
+
+ async def parse_product(self, response: Response):
+ yield {
+ "name": response.css("h1::text").get(""),
+ "price": response.css(".price::text").get(""),
+ }
+
+ async def on_close(self):
+ for api_response in self.browser_session.network.search(
+ url_pattern=r"https://api\.shop\.example\.com/.*", limit=None
+ ):
+ self.logger.info(f"Saved API response: {api_response.url} ({api_response.status})")
+```
+
+示例保留了浏览器实例,并在会话关闭前,通过 `on_close()` 读取一次已保存的 API 历史记录。记录涵盖所有商品页面,关闭后仍可读取。尚未完成的记录不会被等待,记录数量限制仍然有效。
+
+关键是 `sid` 参数,它告诉 Spider 每个请求应该使用哪个会话。调用 `response.follow()` 时如果未指定 `sid`,就会继承原请求的会话 ID。
+
+会话不必来自不同的类。也可以使用同一个类的多个实例,并为它们设置不同的配置:
+
+```python
+from scrapling.spiders import Spider, Response
+from scrapling.fetchers import FetcherSession
+
+class ProductSpider(Spider):
+ name = "products"
+ start_urls = ["https://shop.example.com/products"]
+
+ def configure_sessions(self, manager):
+ chrome_requests = FetcherSession(impersonate="chrome")
+ firefox_requests = FetcherSession(impersonate="firefox")
+
+ manager.add("chrome", chrome_requests)
+ manager.add("firefox", firefox_requests)
+
+ async def parse(self, response: Response):
+ for link in response.css("a.product::attr(href)").getall():
+ yield response.follow(link, callback=self.parse_product)
+
+ next_page = response.css("a.next::attr(href)").get()
+ if next_page:
+ yield response.follow(next_page, sid="firefox")
+
+ async def parse_product(self, response: Response):
+ yield {
+ "name": response.css("h1::text").get(""),
+ "price": response.css(".price::text").get(""),
+ }
+```
+
+也可以为某类请求保留一个独立会话,让它保有自己的 Cookie 和状态。
+
+## 会话参数 {#session-arguments}
+
+传给 `Request` 或通过 `response.follow(**kwargs)` 传入的额外关键字参数,会交给会话的获取方法。这样就能单独调整请求,而不必改变会话配置:
+
+```python
+async def parse(self, response: Response):
+ # Pass extra headers for this specific request
+ yield Request(
+ "https://api.example.com/data",
+ headers={"Authorization": "Bearer token123"},
+ callback=self.parse_api,
+ )
+
+ # Use a different HTTP method
+ yield Request(
+ "https://example.com/submit",
+ method="POST",
+ data={"field": "value"},
+ sid="firefox",
+ callback=self.parse_result,
+ )
+```
+
+!!! warning
+
+ 通常使用 `FetcherSession`、`Fetcher` 或 `AsyncFetcher` 时,会通过 `.get()`、`.post()` 等方法选择 HTTP 方法。但在 Spider 中使用 `FetcherSession` 时不能这样做。请求默认为 _HTTP GET_;若要使用其他 HTTP 方法,必须通过 `method` 参数指定,如上例所示。这是为了让所有会话类型使用统一的 `Request` 接口。
+
+对于上面多会话示例中注册的 `"stealth"` 会话(`AsyncStealthySession`),可以传入 `wait_selector`、`page_action` 或 `extra_headers` 等浏览器专用参数:
+
+```python
+async def parse(self, response: Response):
+ # Use Cloudflare solver with the `AsyncStealthySession` we configured above
+ yield Request(
+ "https://nopecha.com/demo/cloudflare",
+ sid="stealth",
+ callback=self.parse_result,
+ solve_cloudflare=True,
+ block_webrtc=True,
+ hide_canvas=True,
+ google_search=True,
+ )
+
+ yield response.follow(
+ "/dynamic-page",
+ sid="stealth",
+ callback=self.parse_dynamic,
+ wait_selector="div.loaded",
+ network_idle=True,
+ )
+```
+
+!!! warning
+
+ `response.follow()` 会继承原请求的会话参数(**kwargs),但不包括 `method`、`params`、`data`、`json`、`files` 和 `multipart`。因此,POST 请求之后跟随链接时,会发送普通 GET 请求。新传入的参数优先于继承的参数。
+
+```python
+from scrapling.spiders import Spider, Response
+from scrapling.fetchers import FetcherSession
+
+class ProductSpider(Spider):
+ name = "products"
+ start_urls = ["https://shop.example.com/products"]
+
+ def configure_sessions(self, manager):
+ manager.add("http", FetcherSession(impersonate='chrome'))
+
+ async def parse(self, response: Response):
+ # I don't want the follow request to impersonate a desktop Chrome like the previous request, but a mobile one
+ # so I override it like this
+ for link in response.css("a.product::attr(href)").getall():
+ yield response.follow(link, impersonate="chrome131_android", callback=self.parse_product)
+
+ next_page = response.css("a.next::attr(href)").get()
+ if next_page:
+ yield response.follow(next_page)
+
+ async def parse_product(self, response: Response):
+ yield {
+ "name": response.css("h1::text").get(""),
+ "price": response.css(".price::text").get(""),
+ }
+```
+!!! info
+
+ Spider 关闭时,管理器会自动检查是否还有运行中的会话,并在 Spider 结束前关闭它们。
diff --git a/docs/locales/zh/stylesheets b/docs/locales/zh/stylesheets
new file mode 120000
index 0000000..02c6ba6
--- /dev/null
+++ b/docs/locales/zh/stylesheets
@@ -0,0 +1 @@
+../../stylesheets
\ No newline at end of file
diff --git a/docs/locales/zh/tutorials/migrating_from_beautifulsoup.md b/docs/locales/zh/tutorials/migrating_from_beautifulsoup.md
new file mode 100644
index 0000000..8585a45
--- /dev/null
+++ b/docs/locales/zh/tutorials/migrating_from_beautifulsoup.md
@@ -0,0 +1,99 @@
+---
+title: "从 BeautifulSoup 迁移到 Scrapling"
+description: "将 BeautifulSoup 中常用的选择、文本、属性和导航操作对应到 Scrapling,通过实际示例了解 API 差异。"
+---
+
+# 从 BeautifulSoup 迁移到 Scrapling {#migrating-from-beautifulsoup-to-scrapling}
+
+如果已经熟悉 BeautifulSoup,使用 Scrapling 会很容易上手。Scrapling 速度更快,提供相同的解析能力,还增加了 BeautifulSoup 没有的解析方法,以及获取和处理现代网页的功能。本指南帮助你将现有 BeautifulSoup 代码快速改为使用 Scrapling。
+
+下表列出了网页抓取中最常见的操作。每一行展示了 BeautifulSoup 的写法和 Scrapling 中对应的方法。
+
+BeautifulSoup 的某些快捷写法在 Scrapling 中不存在,这也是 BeautifulSoup 更慢的原因之一。如果一个功能已经能用简短的一行代码实现,就没必要为了再缩短一点而牺牲性能 :)
+
+| 任务 | BeautifulSoup 代码 | Scrapling 代码 |
+|-----------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------|
+| 导入 Parser | `from bs4 import BeautifulSoup` | `from scrapling.parser import Selector` |
+| 解析字符串中的 HTML | `soup = BeautifulSoup(html, 'html.parser')` | `page = Selector(html)` |
+| 查找单个元素 | `element = soup.find('div', class_='example')` | `element = page.find('div', class_='example')` |
+| 查找多个元素 | `elements = soup.find_all('div', class_='example')` | `elements = page.find_all('div', class_='example')` |
+| 查找单个元素(示例 2) | `element = soup.find('div', attrs={"class": "example"})` | `element = page.find('div', {"class": "example"})` |
+| 查找单个元素(示例 3) | `element = soup.find(re.compile("^b"))` | `element = page.find(lambda e: re.search(r"^b", e.tag) is not None)` |
+| 查找单个元素(示例 4) | `element = soup.find(lambda e: len(list(e.children)) > 0)` | `element = page.find(lambda e: len(e.children) > 0)` |
+| 查找单个元素(示例 5) | `element = soup.find(["a", "b"])` | `element = page.find(["a", "b"])` |
+| 按文本内容查找元素 | `element = soup.find(text="some text")` | `element = page.find_by_text("some text", partial=False)` |
+| 用 CSS 选择器查找第一个匹配元素 | `elements = soup.select_one('div.example')` | `elements = page.css('div.example').first` |
+| 用 CSS 选择器查找所有匹配元素 | `elements = soup.select('div.example')` | `elements = page.css('div.example')` |
+| 获取格式化后的页面或元素源码 | `prettified = soup.prettify()` | `prettified = page.prettify()` |
+| 获取未格式化的页面或元素源码 | `source = str(soup)` | `source = page.html_content` |
+| 获取元素的标签名 | `name = element.name` | `name = element.tag` |
+| 提取元素的文本内容 | `string = element.string` | `string = element.text` |
+| 提取文档或标签下的全部文本 | `text = soup.get_text(strip=True)` | `text = page.get_all_text(strip=True)` |
+| 访问属性字典 | `attrs = element.attrs` | `attrs = element.attrib` |
+| 提取属性 | `attr = element['href']` | `attr = element['href']` |
+| 访问父元素 | `parent = element.parent` | `parent = element.parent` |
+| 获取元素的所有祖先 | `parents = list(element.parents)` | `parents = list(element.iterancestors())` |
+| 在祖先中查找一个元素 | `target_parent = element.find_parent("a")` | `target_parent = element.find_ancestor(lambda p: p.tag == 'a')` |
+| 获取所有兄弟元素 | 不支持 | `siblings = element.siblings` |
+| 获取下一个兄弟元素 | `next_element = element.next_sibling` | `next_element = element.next` |
+| 在兄弟元素中查找一个元素 | `target_sibling = element.find_next_sibling("a")`<br/>`target_sibling = element.find_previous_sibling("a")` | `target_sibling = element.siblings.search(lambda s: s.tag == 'a')` |
+| 在兄弟元素中查找多个元素 | `target_sibling = element.find_next_siblings("a")`<br/>`target_sibling = element.find_previous_siblings("a")` | `target_sibling = element.siblings.filter(lambda s: s.tag == 'a')` |
+| 在后续元素中查找一个元素 | `target_parent = element.find_next("a")` | `target_parent = element.below_elements.search(lambda p: p.tag == 'a')` |
+| 在后续元素中查找多个元素 | `target_parent = element.find_all_next("a")` | `target_parent = element.below_elements.filter(lambda p: p.tag == 'a')` |
+| 在祖先中查找一个元素 | `target_parent = element.find_previous("a")` ¹ | `target_parent = element.path.search(lambda p: p.tag == 'a')` |
+| 在祖先中查找多个元素 | `target_parent = element.find_all_previous("a")` ¹ | `target_parent = element.path.filter(lambda p: p.tag == 'a')` |
+| 获取上一个兄弟元素 | `prev_element = element.previous_sibling` | `prev_element = element.previous` |
+| 访问子元素 | `children = list(element.children)` | `children = element.children` |
+| 获取所有后代元素 | `children = list(element.descendants)` | `children = element.below_elements` |
+| 选择 story 类段落内的链接 | `group = soup.select('p.story a')` | `group = page.css('p.story a')` |
+
+直接传给 Scrapling `find()` 或 `find_all()` 的已编译正则表达式,匹配的是元素文本,而不是标签名。要匹配标签名,使用表中的 lambda;要直接匹配文本,可以使用 `page.find_by_regex(r"^b")`。
+
+¹ **注意:** BS4 的 `find_previous`/`find_all_previous` 会按文档顺序搜索所有先前元素,而 Scrapling 的 `path` 只返回祖先,也就是父元素链。它们并非完全等价,但祖先搜索能覆盖最常见的场景。
+
+**一个重要区别**:BeautifulSoup 提供了在解析后修改页面的功能。Scrapling 更专注于快速提取数据,然后交给用户自行处理。两者都能用于网页抓取,但其中一个专门为此设计 :)
+
+### 完整示例 {#putting-it-all-together}
+
+下面分别使用 BeautifulSoup 和 Scrapling,提取页面中的所有链接。
+
+**使用 BeautifulSoup:**
+
+```python
+import requests
+from bs4 import BeautifulSoup
+
+url = 'https://example.com'
+response = requests.get(url)
+soup = BeautifulSoup(response.text, 'html.parser')
+
+links = soup.find_all('a')
+for link in links:
+ print(link['href'])
+```
+
+**使用 Scrapling:**
+
+```python
+from scrapling import Fetcher
+
+url = 'https://example.com'
+page = Fetcher.get(url)
+
+links = page.css('a::attr(href)').getall()
+for link in links:
+ print(link)
+```
+
+Scrapling 将获取和解析合为一步,让代码更简洁、效率更高。
+
+!!! abstract "**补充说明:**"
+
+ - **不同的 Parser**:BeautifulSoup 允许选择解析引擎,例如 `lxml`。Scrapling 出于性能考虑,默认使用 `lxml` 库。
+ - **元素类型**:BeautifulSoup 中的元素是 `Tag` 对象,Scrapling 中的是 `Selector` 对象。它们提供类似的导航和数据提取方法及属性。
+ - **错误处理**:找不到元素时,两者都返回 `None`,例如 `soup.find()` 或 `page.find()`。Scrapling 的 `page.css()` 在没有匹配元素时返回空的 `Selectors` 列表。可以用 `page.css('.foo').first` 安全地获取第一个结果或 `None`。访问属性前,先检查结果是否为 `None` 或为空。
+ - **文本提取**:Scrapling 通过 `TextHandler` 提供更多文本处理方法,例如 `clean()`,可以帮助移除多余空白、连续空格或不需要的字符。完整列表请查看文档。
+
+文档会更详细地介绍 Scrapling 的功能,并列出各方法支持的全部参数。
+
+希望本指南能让从 BeautifulSoup 到 Scrapling 的迁移更顺利。祝抓取顺利!
diff --git a/docs/locales/zh/tutorials/replacing_ai.md b/docs/locales/zh/tutorials/replacing_ai.md
new file mode 100644
index 0000000..e0a9c2f
--- /dev/null
+++ b/docs/locales/zh/tutorials/replacing_ai.md
@@ -0,0 +1,121 @@
+---
+title: "可靠网页抓取的免费 AI 替代方案"
+description: "Scrapling 可以应对页面变化、不稳定的选择器、反爬保护和分页,无需为每个页面调用 LLM。"
+---
+
+# Scrapling:可靠网页抓取的免费 AI 替代方案 {#scrapling-a-free-alternative-to-ai-for-robust-web-scraping}
+
+网页抓取长期用于提取数据、建立索引和准备数据集等任务。但有经验的用户仍会遇到一些反复出现的问题,影响工作效率。最近,越来越多人开始使用 AI 抓取网页,因为它有望解决其中一些难题。
+
+本文会介绍这些常见问题、企业转向 AI 的原因、这种方案的不足,以及 Scrapling 如何在无需承担 AI 成本的情况下提供帮助。
+
+## 常见问题和更难的目标 {#common-issues-and-challenging-goals}
+
+如果做过一段时间网页抓取,应该遇到过这些问题:
+
+1. **网站结构经常变化**:网站会更新 DOM,导致固定的 XPath 或 CSS 选择器失效。
+2. **选择器不稳定**:类名和 ID 经常变化,或使用随机值,导致抓取代码失效或更难编写。
+3. **反爬措施越来越复杂**:CAPTCHA、浏览器指纹和行为分析让传统抓取方式更难奏效。
+
+还有其他问题。即便只针对已知网站抓取、可以为每个网站编写专用代码,也会遇到这些情况。
+
+如果目标更大,要从许多不同的网站抓取数据,也就是常说的 Broad Scraping 或 Generic Web Scraping,上述问题会更严重,还会出现新的难题:
+
+1. **网站差异很大**:通用抓取程序要处理各种 HTML 结构、CSS 用法、JavaScript 框架和后端技术。
+2. **识别有用数据**:面对从未见过的页面,抓取程序怎么知道哪些数据重要?
+3. **分页方式不同**:无限滚动、传统分页和“加载更多”按钮,都需要不同的处理方法。
+
+问题还不止这些。如何手动解决?这里说的是没有共同技术基础的不同网站。
+
+## AI 能帮忙,但成本很高 {#ai-to-the-rescue-but-at-a-high-cost}
+
+AI 能理解页面源码,找出需要的字段,或者为它们生成选择器,因此可以解决很多问题。当然,这要建立在已经使用其他工具处理好反爬保护的前提下 :)
+
+我很喜欢这种方案,也觉得 AI,尤其是生成式 AI,很有意思。可能需要花很多时间编写和调整提示词。如果可以接受这一点,很快就会遇到这个场景中使用 AI 的真正问题。
+
+很多页面包含大量内容,需要以某种方式传给 AI。这样会快速消耗 token,费用也会不断增加。
+
+除非完全不在意预算,否则就会开始寻找更便宜的方案。这正是 Scrapling 能帮忙的地方 :smile:
+
+## Scrapling 可以帮忙 {#scrapling-got-you-covered}
+
+Scrapling 可以处理网页抓取中几乎所有常见问题,接下来的更新还会逐步覆盖其余情况。
+
+### 解决 T1:网站结构经常变化 {#solving-issue-t1-rapidly-changing-website-structures}
+
+这就是 [adaptive](../parsing/adaptive.md) 功能存在的原因。没错,还是要讲到它 :)
+
+启用 `adaptive` 后,可以保存元素的特有属性。即使网站结构改变,也能在之后重新找到它。困难在于,元素的任何部分都可能变化,不一定有稳定属性可依赖。
+
+这项功能会保存元素的全部特征。网站结构变化后,它返回与原元素相似度最高的元素。
+
+我已经通过多个示例详细介绍过它,可以[在这里继续阅读](../parsing/adaptive.md#how-the-adaptive-scraping-feature-works)。
+
+### 解决 T2:选择器不稳定 {#solving-issue-t2-unstable-selectors}
+
+如果做过较长时间网页抓取,可能遇到过这样的页面:只有原始 HTML,没有 ID 或类名;类名随机生成;或者没有其他稳定特征可以用来选择元素。
+
+此时,传统的 CSS 或 XPath 选择器不一定是最佳方案。因此,Scrapling 提供了另外三种选择方式:
+
+1. [按元素内容选择](../parsing/selection.md#text-content-selection):用 `find_by_text` 查找文本,或用 `find_by_regex` 通过正则表达式匹配文本。
+2. [选择与另一元素相似的元素](../parsing/selection.md#finding-similar-elements):先找到一个元素,其余交给 Scrapling。
+3. [按条件筛选元素](../parsing/selection.md#filters-based-searching):指定元素需要满足的条件或过滤规则,让 Scrapling 来查找。
+
+打开这些链接,就能了解各个场景的处理方式。
+
+### 解决 T3:反爬措施越来越复杂 {#solving-issue-t3-increasingly-complex-anti-bot-measures}
+
+面对受保护的网站,仅靠代理和模拟人的操作可能不够。[StealthyFetcher](../fetching/stealthy.md) 将浏览器自动化、指纹调整和反爬处理选项结合起来。启用 `solve_cloudflare=True`,即可处理 Cloudflare Turnstile 和 Interstitial 验证。
+
+### 解决 B1 和 B2:网站差异与有用数据识别 {#solving-issues-b1-b2-extreme-website-diversity-identifying-relevant-data}
+
+这个问题很难,但 Scrapling 的灵活性让它有了解法。
+
+我曾和一位用户交流,他用 AI 从不同网站提取价格。他只关心价格和标题,所以让 AI 帮他定位价格。
+
+我告诉他,这里不一定需要 AI,并给出了这个示例:
+```python
+price_element = page.find_by_regex(r'£[\d\.,]+', first_match=True) # Get the first element that contains a text that matches price regex eg. £10.50
+# If you want the container/element that contains the price element
+price_element_container = price_element.parent or price_element.find_ancestor(lambda ancestor: ancestor.has_class('product')) # or other methods...
+target_element_selector = price_element_container.generate_css_selector or price_element_container.generate_full_css_selector # or xpath
+```
+他又问,如果是下面这种情况呢:
+```html
+<span class='currency'> $ </span> <span class='a-price'> 45,000 </span>
+```
+于是我调整了代码:
+```python
+price_element_container = page.find_by_regex(r'[\d,]+', first_match=True).parent # Adjusted the regex for this example
+full_price_data = price_element_container.get_all_text(separator="", strip=True) # Returns '$45,000' in this case
+```
+这些代码已经满足了他的需求。可以先尝试第一个正则表达式,找不到结果再换下一个。先覆盖最常见的模式,再逐步覆盖其他模式。
+这可能有些繁琐,但比 AI 便宜得多。
+
+这个例子想说明的是:不是所有问题都需要 AI。有时换一种思路,就能节省很多费用。
+
+### 解决 B3:分页方式不同 {#solving-issue-b3-pagination-variations}
+
+Scrapling 目前没有直接自动识别分页链接的方法。它的 Spider 使用 `response.follow()` 跟随分页链接。
+
+不过,只要查找常见模式,就能覆盖很多网站。例如 `page.find_by_text('Next')['href']`、`page.find_by_text('load more')['href']`,或 `'a[href*="?page="]'`、`'a[href*="/page/"]'` 这样的选择器。思路就是如此。
+
+## 成本对比与节省 {#cost-comparison-and-savings}
+
+下面是一个简单对比:
+
+| 方面 | Scrapling | AI 工具,例如 Browse AI、Oxylabs |
+|---|---|---|
+| 成本 | 免费,使用库不按次数收费 | 付费套餐,价格取决于服务商和用量 |
+| 设置 | 需要少量技术知识和手动设置 | 通常无需代码,对非技术用户更简单 |
+| 使用方式 | 代码、终端或 MCP 服务器 | 通常是图形界面或 API,取决于服务商提供的方案 |
+| 扩展到大规模 | 取决于用户的实现 | 托管服务内置大规模处理支持 |
+| 适应变化 | 依靠 `adaptive` 和无需 CSS/XPath 选择器的方法,适应性强 | AI 自动处理,适应性强,但频繁变化时费用较高 |
+
+最新价格请参阅 [Browse AI](https://www.browse.ai/pricing) 和 [Oxylabs Web Scraper API](https://oxylabs.io/products/scraper-api/web/pricing)。
+
+## 总结 {#conclusion}
+
+AI 功能强大,但费用可能超出许多网页抓取任务的预算。Scrapling 提供可靠、灵活且低成本的工具,既能针对已知网站抓取,也能应对多种不同网站,往往可以避免使用昂贵的 AI 方案。借助 `adaptive`、多种选择方法和高级 Fetcher,可以更高效地编写能应对变化的抓取程序。
+
+继续阅读文档,看看 Scrapling 如何简化接下来的网页抓取项目!
diff --git a/docs/overrides/api/python/material/languages/zh.html.jinja b/docs/overrides/api/python/material/languages/zh.html.jinja
new file mode 100644
index 0000000..921817e
--- /dev/null
+++ b/docs/overrides/api/python/material/languages/zh.html.jinja
@@ -0,0 +1,17 @@
+{% macro t(key) %}{{ {
+ "ATTRIBUTE": "属性", "Attributes": "属性", "Attributes:": "属性:",
+ "BOUND:": "上界:", "Bound or Constraints": "上界或约束",
+ "Classes": "类", "Classes:": "类:", "CLASS": "类",
+ "Class Type Parameters:": "类的类型参数:", "CLASS TYPE PARAMETER": "类的类型参数",
+ "CONSTRAINTS:": "约束:", "DEFAULT:": "默认值:", "Default": "默认值", "default:": "默认值:",
+ "DESCRIPTION": "说明", "Description": "说明", "Examples:": "示例:",
+ "Functions": "函数", "Functions:": "函数:", "FUNCTION": "函数",
+ "Init Type Parameters:": "初始化类型参数:", "INIT TYPE PARAMETER": "初始化类型参数",
+ "Methods:": "方法:", "METHOD": "方法", "Modules": "模块", "Modules:": "模块:", "MODULE": "模块",
+ "Name": "名称", "Other Parameters:": "其他参数:", "PARAMETER": "参数", "Parameters:": "参数:",
+ "RAISES": "抛出异常", "Raises:": "抛出异常:", "RECEIVES": "接收", "Receives:": "接收:",
+ "required": "必填", "RETURNS": "返回", "Returns:": "返回:", "Source code in": "源代码位于",
+ "TYPE:": "类型:", "Type": "类型", "Type Aliases": "类型别名", "Type Aliases:": "类型别名:",
+ "TYPE ALIAS": "类型别名", "Type Parameters:": "类型参数:", "TYPE PARAMETER": "类型参数",
+ "WARNS": "警告", "Warns:": "警告:", "YIELDS": "产出", "Yields:": "产出:"
+}.get(key, "") }}{% endmacro %}
diff --git a/docs/overrides/api/python/material/translations/zh.html.jinja b/docs/overrides/api/python/material/translations/zh.html.jinja
new file mode 100644
index 0000000..c6aab21
--- /dev/null
+++ b/docs/overrides/api/python/material/translations/zh.html.jinja
@@ -0,0 +1,369 @@
+{% set translations = {
+ "<p>This class is returned by all engines as a way to unify the response type between different libraries.</p>": "<p>所有引擎都返回此类,用于统一不同库的响应类型。</p>",
+ "<p>HTTP status code.</p>": "<p>HTTP 状态码。</p>",
+ "<p>HTTP status message.</p>": "<p>HTTP 状态消息。</p>",
+ "<p>Response cookies.</p>": "<p>响应中的 Cookie。</p>",
+ "<p>Response headers.</p>": "<p>响应头。</p>",
+ "<p>Request headers sent with the request.</p>": "<p>随请求发送的请求头。</p>",
+ "<p>List of redirect responses, if any.</p>": "<p>重定向响应列表,如果有的话。</p>",
+ "<p>Metadata dictionary (e.g., proxy used).</p>": "<p>元数据字典,例如使用的代理。</p>",
+ "<p>Associated spider Request object (set by crawler, in the spiders framework).</p>": "<p>关联的 Spider Request 对象,由 Spider 框架中的爬虫设置。</p>",
+ "<p>The main class that works as a wrapper for the HTML input data. Using this class, you can search for elements\nwith expressions in CSS, XPath, or with simply text. Check the docs for more info.</p>": "<p>封装输入 HTML 数据的主要类。可以用 CSS、XPath 表达式或简单文本查找元素。更多信息请查看文档。</p>",
+ "<p>Here we try to extend module <code>lxml.html.HtmlElement</code> while maintaining a simpler interface, We are not\ninheriting from the <code>lxml.html.HtmlElement</code> because it's not pickleable, which makes a lot of reference jobs\nnot possible. You can test it here and see code explodes with <code>AssertionError: invalid Element proxy at...</code>.\nIt's an old issue with lxml, see <code>this entry &lt;https://bugs.launchpad.net/lxml/+bug/736708&gt;</code></p>": "<p>此类扩展了 <code>lxml.html.HtmlElement</code> 的功能,同时提供更简单的接口。它不继承 <code>lxml.html.HtmlElement</code>,因为该类型无法通过 pickle 序列化,会使许多依赖引用的操作无法完成。尝试这样做会出现 <code>AssertionError: invalid Element proxy at...</code>。这是 lxml 的一个老问题,详见 <code>this entry &lt;https://bugs.launchpad.net/lxml/+bug/736708&gt;</code>。</p>",
+ "<p>HTML content as either string or bytes.</p>": "<p>字符串或 bytes 形式的 HTML 内容。</p>",
+ "<p>It allows storing a URL with the HTML data for retrieving later.</p>": "<p>允许将 URL 与 HTML 数据一起保存,供以后读取。</p>",
+ "<p>The encoding type that will be used in HTML parsing, default is <code>UTF-8</code></p>": "<p>解析 HTML 时使用的编码,默认为 <code>UTF-8</code>。</p>",
+ "<p>Enabled by default, should always be enabled when parsing large HTML documents. This controls\nthe libxml2 feature that forbids parsing certain large documents to protect from possible memory exhaustion.</p>": "<p>默认启用,解析大型 HTML 文档时应始终启用。它控制 libxml2 的一项功能,该功能会禁止解析某些大型文档,以避免内存耗尽。</p>",
+ "<p>Used internally to pass etree objects instead of text/body arguments, it takes the highest priority.\nDon't use it unless you know what you are doing!</p>": "<p>内部用于传入 etree 对象,代替文本或响应体参数,优先级最高。只有了解其影响时才应使用。</p>",
+ "<p>While parsing the HTML body, drop comments or not. Disabled by default for obvious reasons</p>": "<p>解析 HTML 时是否保留注释,默认关闭。</p>",
+ "<p>Globally turn off the adaptive feature in all functions, this argument takes higher\npriority over all adaptive related arguments/functions in the class.</p>": "<p>在所有方法中全局关闭自适应功能。此参数的优先级高于类中所有与自适应有关的参数和方法。</p>",
+ "<p>The storage class to be passed for adaptive functionalities, see <code>Docs</code> for more info.</p>": "<p>自适应功能使用的存储类。更多信息请查看 <code>Docs</code>。</p>",
+ "<p>A dictionary of <code>argument-&gt;value</code> pairs to be passed for the storage class.\nIf empty, default values will be used.</p>": "<p>传给存储类的 <code>argument-&gt;value</code> 键值对字典。为空时使用默认值。</p>",
+ "<p>Return the raw body of the current <code>Selector</code> without any processing. Useful for binary and non-HTML requests.</p>": "<p>返回当前 <code>Selector</code> 未经处理的原始响应体,适用于二进制和非 HTML 内容。</p>",
+ "<p>Return the raw body of the response as bytes.</p>": "<p>以 bytes 形式返回响应的原始响应体。</p>",
+ "<p>Generate a CSS selector for the current element</p>": "<p>为当前元素生成 CSS 选择器。</p>",
+ "<p>A string of the generated selector.</p>": "<p>包含所生成选择器的字符串。</p>",
+ "<p>Generate a complete CSS selector for the current element</p>": "<p>为当前元素生成完整的 CSS 选择器。</p>",
+ "<p>Generate an XPath selector for the current element</p>": "<p>为当前元素生成 XPath 选择器。</p>",
+ "<p>Generate a complete XPath selector for the current element</p>": "<p>为当前元素生成完整的 XPath 选择器。</p>",
+ "<p>Get the tag name of the element</p>": "<p>获取元素的标签名。</p>",
+ "<p>Get text content of the element</p>": "<p>获取元素的文本内容。</p>",
+ "<p>Get attributes of the element</p>": "<p>获取元素的属性。</p>",
+ "<p>Return the inner HTML code of the element</p>": "<p>返回元素内部的 HTML 代码。</p>",
+ "<p>Return the direct parent of the element or <code>None</code> otherwise</p>": "<p>返回元素的直接父元素,如果没有则返回 <code>None</code>。</p>",
+ "<p>Return all elements under the current element in the DOM tree</p>": "<p>返回 DOM 树中当前元素下方的所有元素。</p>",
+ "<p>Return the children elements of the current element or empty list otherwise</p>": "<p>返回当前元素的子元素,如果没有则返回空列表。</p>",
+ "<p>Return other children of the current element's parent or empty list otherwise</p>": "<p>返回当前元素的父元素下的其他子元素,如果没有则返回空列表。</p>",
+ "<p>Returns a list of type <code>Selectors</code> that contains the path leading to the current element from the root.</p>": "<p>返回 <code>Selectors</code> 类型的列表,包含从根节点到当前元素的路径。</p>",
+ "<p>Returns the next element of the current element in the children of the parent or <code>None</code> otherwise.</p>": "<p>返回同一父元素下,当前元素之后的下一个元素,如果没有则返回 <code>None</code>。</p>",
+ "<p>Returns the previous element of the current element in the children of the parent or <code>None</code> otherwise.</p>": "<p>返回同一父元素下,当前元素之前的上一个元素,如果没有则返回 <code>None</code>。</p>",
+ "<p>Convert the response content to clean Markdown.</p>": "<p>将响应内容转换为干净的 Markdown。</p>",
+ "<p>Scripts, styles, and hidden/prompt-injection content are always removed before conversion, which is\nthe same cleaning the MCP server does. Requires the \"markdownify\" package (<code>pip install \"scrapling[rag]\"</code>).</p>": "<p>转换前会始终移除脚本、样式、隐藏内容和提示词注入内容,与 MCP 服务器使用的清理方式相同。需要安装 \"markdownify\" 包(<code>pip install \"scrapling[rag]\"</code>)。</p>",
+ "<p>CSS selector to convert only the matching elements. All matches are concatenated.</p>": "<p>用于限定转换范围的 CSS 选择器。只转换匹配的元素,并合并所有结果。</p>",
+ "<p>Convert only the content inside the <code>&lt;body&gt;</code> tag.</p>": "<p>只转换 <code>&lt;body&gt;</code> 标签内的内容。</p>",
+ "<p>Create a Request to follow a URL.</p>": "<p>创建一个 Request 来跟随 URL。</p>",
+ "<p>This is a helper method for spiders to easily follow links found in pages.</p>": "<p>这是一个辅助方法,方便 Spider 跟随页面中的链接。</p>",
+ "<p><strong>IMPORTANT</strong>: The below arguments if left empty, the corresponding value from the previous request will be used. The only exception is <code>dont_filter</code>.</p>": "<p><strong>重要</strong>:下列参数如果留空,会使用前一个请求的对应值。唯一例外是 <code>dont_filter</code>。</p>",
+ "<p>The session kwargs of the previous request are inherited as well, except <code>method</code>, <code>params</code>, <code>data</code>, <code>json</code>, <code>files</code>, and <code>multipart</code>, so a followed link is a plain GET unless you pass them again.</p>": "<p>前一个请求的会话参数也会继承,但不包括 <code>method</code>、<code>params</code>、<code>data</code>、<code>json</code>、<code>files</code> 和 <code>multipart</code>。因此,除非再次传入这些参数,否则跟随链接时会发送普通 GET 请求。</p>",
+ "<p>The URL to follow (can be relative, will be joined with current URL)</p>": "<p>要跟随的 URL。可以是相对 URL,会与当前 URL 合并。</p>",
+ "<p>The session id to use</p>": "<p>要使用的会话 ID。</p>",
+ "<p>Spider callback method to use</p>": "<p>要使用的 Spider 回调方法。</p>",
+ "<p>The priority number to use, the higher the number, the higher priority to be processed first.</p>": "<p>优先级数值,值越大,越先处理。</p>",
+ "<p>If this request has been done before, disable the filter to allow it again.</p>": "<p>关闭过滤,让已经发送过的请求也能再次执行。</p>",
+ "<p>Additional meta data to included in the request</p>": "<p>要加入请求的额外元数据。</p>",
+ "<p>Enabled by default, set the current response url as referer for the new request url.</p>": "<p>默认启用,将当前响应的 URL 设为新请求的 Referer。</p>",
+ "<p>Additional Request arguments</p>": "<p>额外的 Request 参数。</p>",
+ "<p>Request object ready to be yielded</p>": "<p>可以通过 yield 产出的 Request 对象。</p>",
+ "<p>Get all child strings of this element, concatenated using the given separator.</p>": "<p>获取此元素下的所有字符串,并用指定分隔符连接。</p>",
+ "<p>Strings will be concatenated using this separator.</p>": "<p>连接字符串时使用的分隔符。</p>",
+ "<p>If True, strings will be stripped before being concatenated.</p>": "<p>为 True 时,先去除各字符串两端的空白,再连接。</p>",
+ "<p>A tuple of all tag names you want to ignore</p>": "<p>包含所有要忽略的标签名的元组。</p>",
+ "<p>If enabled, elements with text-content that is empty or only whitespaces will be ignored</p>": "<p>启用后,忽略文本为空或只包含空白的元素。</p>",
+ "<p>A TextHandler</p>": "<p>一个 TextHandler。</p>",
+ "<p>Join this Selector's url with a relative url to form an absolute full URL.</p>": "<p>将此 Selector 的 URL 与相对 URL 合并,生成完整的绝对 URL。</p>",
+ "<p>Return a prettified version of the element's inner html-code</p>": "<p>返回格式化后更易读的元素内部 HTML 代码。</p>",
+ "<p>Check if the element has a specific class</p>": "<p>检查元素是否包含指定的 class。</p>",
+ "<p>The class name to check for</p>": "<p>要检查的 class 名称。</p>",
+ "<p>True if element has class with that name otherwise False</p>": "<p>元素包含该名称的 class 时返回 True,否则返回 False。</p>",
+ "<p>Return a generator that loops over all ancestors of the element, starting with the element's parent.</p>": "<p>返回一个生成器,从父元素开始遍历当前元素的所有祖先元素。</p>",
+ "<p>Loop over all ancestors of the element till one match the passed function</p>": "<p>遍历元素的所有祖先,直到某个祖先满足传入函数的条件。</p>",
+ "<p>A function that takes each ancestor as an argument and returns True/False</p>": "<p>接收每个祖先元素作为参数,并返回 True 或 False 的函数。</p>",
+ "<p>The first ancestor that match the function or <code>None</code> otherwise.</p>": "<p>第一个满足函数条件的祖先元素,如果没有则返回 <code>None</code>。</p>",
+ "<p>Serialize this element to a string.\nFor text nodes, returns the text value. For HTML elements, returns the outer HTML.</p>": "<p>将此元素序列化为字符串。文本节点返回文本值,HTML 元素返回外层 HTML。</p>",
+ "<p>Return a single-element list containing this element's serialized string.</p>": "<p>返回仅含一个元素的列表,其中是当前元素序列化后的字符串。</p>",
+ "<p>This function will search again for the element in the page tree, used automatically on page structure change</p>": "<p>在页面树中重新查找元素,页面结构变化时会自动使用。</p>",
+ "<p>The element we want to relocate in the tree</p>": "<p>要在树中重新定位的元素。</p>",
+ "<p>The minimum percentage to accept and not going lower than that. Be aware that the percentage\ncalculation depends solely on the page structure, so don't play with this number unless you must know\nwhat you are doing!</p>": "<p>可接受的最低匹配百分比。百分比的计算只依赖页面结构,请仅在了解其影响时修改此值。</p>",
+ "<p>If True, the return result will be converted to <code>Selectors</code> object</p>": "<p>为 True 时,将返回结果转换为 <code>Selectors</code> 对象。</p>",
+ "<p>List of pure HTML elements that got the highest matching score or 'Selectors' object</p>": "<p>匹配分数最高的原始 HTML 元素列表,或 'Selectors' 对象。</p>",
+ "<p>Search the current tree with CSS3 selectors</p>": "<p>使用 CSS3 选择器搜索当前树。</p>",
+ "<p><strong>Important:\nIt's recommended to use the identifier argument if you plan to use a different selector later\nand want to relocate the same element(s)</strong></p>": "<p><strong>重要:如果以后打算使用其他选择器,并希望重新定位相同元素,建议使用 identifier 参数。</strong></p>",
+ "<p>The CSS3 selector to be used.</p>": "<p>要使用的 CSS3 选择器。</p>",
+ "<p>Enabled will make the function try to relocate the element if it was 'saved' before</p>": "<p>启用后,如果元素之前已保存,函数会尝试重新定位它。</p>",
+ "<p>A string that will be used to save/retrieve element's data in adaptive,\notherwise the selector will be used.</p>": "<p>用于保存和读取自适应元素数据的字符串。未指定时使用选择器。</p>",
+ "<p>Automatically save new elements for <code>adaptive</code> later</p>": "<p>自动保存新元素,供之后的 <code>adaptive</code> 功能使用。</p>",
+ "<p>The minimum percentage to accept while <code>adaptive</code> is working and not going lower than that.\nBe aware that the percentage calculation depends solely on the page structure, so don't play with this\nnumber unless you must know what you are doing!</p>": "<p><code>adaptive</code> 工作时可接受的最低匹配百分比。百分比的计算只依赖页面结构,请仅在了解其影响时修改此值。</p>",
+ "<p><code>Selectors</code> class.</p>": "<p><code>Selectors</code> 类。</p>",
+ "<p>Search the current tree with XPath selectors</p>": "<p>使用 XPath 选择器搜索当前树。</p>",
+ "<p>Note: <strong>Additional keyword arguments will be passed as XPath variables in the XPath expression!</strong></p>": "<p>注意:<strong>额外的关键字参数会作为 XPath 变量传入 XPath 表达式!</strong></p>",
+ "<p>The XPath selector to be used.</p>": "<p>要使用的 XPath 选择器。</p>",
+ "<p>Find elements by filters of your creations for ease.</p>": "<p>通过自己定义的过滤条件查找元素。</p>",
+ "<p>Tag name(s), iterable of tag names, regex patterns, function, or a dictionary of elements' attributes. Leave empty for selecting all.</p>": "<p>标签名、多个标签名、标签名的可迭代对象、正则表达式、函数,或元素属性字典。留空表示选择全部。</p>",
+ "<p>The attributes you want to filter elements based on it.</p>": "<p>用于过滤元素的属性。</p>",
+ "<p>The <code>Selectors</code> object of the elements or empty list</p>": "<p>包含元素的 <code>Selectors</code> 对象,或空列表。</p>",
+ "<p>Find elements by filters of your creations for ease, then return the first result. Otherwise return <code>None</code>.</p>": "<p>通过自己定义的过滤条件查找元素,并返回第一个结果。如果没有则返回 <code>None</code>。</p>",
+ "<p>The <code>Selector</code> object of the element or <code>None</code> if the result didn't match</p>": "<p>元素的 <code>Selector</code> 对象;如果没有匹配结果,则返回 <code>None</code>。</p>",
+ "<p>Saves the element's unique properties to the storage for retrieval and relocation later</p>": "<p>将元素的独特属性保存到存储中,供之后读取和重新定位。</p>",
+ "<p>The element itself that we want to save to storage, it can be a <code>Selector</code> or pure <code>HtmlElement</code></p>": "<p>要保存的元素本身,可以是 <code>Selector</code> 或原始 <code>HtmlElement</code>。</p>",
+ "<p>This is the identifier that will be used to retrieve the element later from the storage. See\nthe docs for more info.</p>": "<p>以后从存储中读取元素时使用的标识。更多信息请查看文档。</p>",
+ "<p>Using the identifier, we search the storage and return the unique properties of the element</p>": "<p>根据标识搜索存储,并返回元素的独特属性。</p>",
+ "<p>This is the identifier that will be used to retrieve the element from the storage. See\nthe docs for more info.</p>": "<p>从存储中读取元素时使用的标识。更多信息请查看文档。</p>",
+ "<p>A dictionary of the unique properties</p>": "<p>包含独特属性的字典。</p>",
+ "<p>Return JSON response if the response is jsonable otherwise throws error</p>": "<p>如果响应可以解析为 JSON,则返回解析结果,否则抛出错误。</p>",
+ "<p>Apply the given regex to the current text and return a list of strings with the matches.</p>": "<p>对当前文本应用给定的正则表达式,并返回包含匹配字符串的列表。</p>",
+ "<p>Can be either a compiled regular expression or a string.</p>": "<p>可以是编译后的正则表达式,也可以是字符串。</p>",
+ "<p>If enabled character entity references are replaced by their corresponding character</p>": "<p>启用后,将字符实体引用替换为对应字符。</p>",
+ "<p>if enabled, this will ignore all whitespaces and consecutive spaces while matching</p>": "<p>启用后,匹配时会忽略所有空白及连续空格。</p>",
+ "<p>if disabled, the function will set the regex to ignore the letters case while compiling it</p>": "<p>关闭后,编译正则表达式时会忽略大小写。</p>",
+ "<p>Apply the given regex to text and return the first match if found, otherwise return the default value.</p>": "<p>对文本应用给定的正则表达式,并返回第一个匹配结果。如果没有,则返回默认值。</p>",
+ "<p>The default value to be returned if there is no match</p>": "<p>没有匹配结果时返回的默认值。</p>",
+ "<p>\n <span class=\"doc-param-default\">\n <b>DEFAULT:</b>\n <code>None</code>\n </span>\n </p>": "<p>\n <span class=\"doc-param-default\">\n <b>默认值:</b>\n <code>None</code>\n </span>\n </p>",
+ "<p>if enabled character entity references are replaced by their corresponding character</p>": "<p>启用后,将字符实体引用替换为对应字符。</p>",
+ "<p>Find elements that are in the same tree depth in the page with the same tag name and same parent tag etc...\nthen return the ones that match the current element attributes with a percentage higher than the input threshold.</p>": "<p>查找页面树中深度相同、标签名相同、父元素标签名相同等条件一致的元素,然后返回与当前元素的属性匹配度高于指定阈值的元素。</p>",
+ "<p>This function is inspired by AutoScraper and made for cases where you, for example, found a product div inside\na products-list container and want to find other products using that element as a starting point EXCEPT\nthis function works in any case without depending on the element type.</p>": "<p>此函数受 AutoScraper 启发。例如,在商品列表容器中找到一个商品 div 后,可以以它为起点查找其他商品。不过,此函数不限于这种场景,也不依赖元素类型。</p>",
+ "<p>The percentage to use while comparing element attributes.\nNote: Elements found before attributes matching/comparison will be sharing the same depth, same tag name,\nsame parent tag name, and same grand parent tag name. So they are 99% likely to be correct unless you are\nextremely unlucky, then attributes matching comes into play, so don't play with this number unless\nyou are getting the results you don't want.\nAlso, if the current element doesn't have attributes and the similar element as well, then it's a 100% match.</p>": "<p>比较元素属性时使用的百分比。注意:在比较属性前,找到的元素已经具有相同深度、相同标签名,以及相同的父元素和祖父元素标签名。因此,除非特别不巧,它们有 99% 的可能已经正确。之后才会比较属性,所以只有结果不符合预期时才应调整此值。如果当前元素和相似元素都没有属性,则视为 100% 匹配。</p>",
+ "<p>Attribute names passed will be ignored while matching the attributes in the last step.\nThe default value is to ignore <code>href</code> and <code>src</code> as URLs can change a lot between elements, so it's unreliable</p>": "<p>在最后一步比较属性时,忽略指定的属性名。默认忽略 <code>href</code> 和 <code>src</code>,因为不同元素的 URL 可能相差很大,不适合用于判断。</p>",
+ "<p>If True, element text content will be taken into calculation while matching.\nNot recommended to use in normal cases, but it depends.</p>": "<p>为 True 时,将元素文本内容也纳入匹配计算。通常不建议启用,但可以根据情况选择。</p>",
+ "<p>A <code>Selectors</code> container of <code>Selector</code> objects or empty list</p>": "<p>一个 <code>Selectors</code> 容器,包含 <code>Selector</code> 对象,或为空列表。</p>",
+ "<p>Find elements that its text content fully/partially matches input.</p>": "<p>查找文本内容与输入完全或部分匹配的元素。</p>",
+ "<p>Text query to match</p>": "<p>要匹配的查询文本。</p>",
+ "<p>Returns the first element that matches conditions, enabled by default</p>": "<p>返回第一个符合条件的元素,默认启用。</p>",
+ "<p>If enabled, the function returns elements that contain the input text</p>": "<p>启用后,返回包含输入文本的元素。</p>",
+ "<p>if enabled, the letters case will be taken into consideration</p>": "<p>启用后区分大小写。</p>",
+ "<p>Find elements that its text content matches the input regex pattern.</p>": "<p>查找文本匹配指定正则表达式的元素。</p>",
+ "<p>Regex query/pattern to match</p>": "<p>用于匹配的正则表达式。</p>",
+ "<p>Return the first element that matches conditions; enabled by default.</p>": "<p>只返回第一个满足条件的元素,默认开启。</p>",
+ "<p>If enabled, the letters case will be taken into consideration in the regex.</p>": "<p>启用后,正则表达式区分大小写。</p>",
+ "<p>If enabled, this will ignore all whitespaces and consecutive spaces while matching.</p>": "<p>启用后,匹配时忽略所有空白字符和连续空格。</p>",
+ "<p>A basic <code>Fetcher</code> class type that can only do basic GET, POST, PUT, and DELETE HTTP requests based on <code>curl_cffi</code>.</p>": "<p>基础 <code>Fetcher</code> 类,通过 <code>curl_cffi</code> 发送 GET、POST、PUT 和 DELETE HTTP 请求。</p>",
+ "<p>Set multiple arguments for the parser at once globally</p>": "<p>一次设置多个全局解析参数。</p>",
+ "<p>The keywords can be any arguments of the following: huge_tree, keep_comments, adaptive, storage, storage_args, adaptive_domain</p>": "<p>支持的参数有 huge_tree、keep_comments、adaptive、storage、storage_args 和 adaptive_domain。</p>",
+ "<p>\n <span class=\"doc-param-default\">\n <b>DEFAULT:</b>\n <code>{}</code>\n </span>\n </p>": "<p>\n <span class=\"doc-param-default\">\n <b>默认值:</b>\n <code>{}</code>\n </span>\n </p>",
+ "<p>A <code>Fetcher</code> class type which is a completely stealthy built on top of Chromium.</p>": "<p>基于 Chromium、提供完整隐身功能的 <code>Fetcher</code> 类。</p>",
+ "<p>It works as real browsers passing almost all online tests/protections with many customization options.</p>": "<p>像真实浏览器一样运行,通过几乎所有在线测试和防护,并提供多种自定义选项。</p>",
+ "<p>Opens up a browser and do your request based on your chosen options below.</p>": "<p>打开浏览器,按下面选择的选项发送请求。</p>",
+ "<p>Target url.</p>": "<p>目标 URL。</p>",
+ "<p>Run the browser in headless/hidden (default), or headful/visible mode.</p>": "<p>以无头模式运行,不显示窗口,这是默认设置;也可以显示浏览器窗口。</p>",
+ "<p>Drop requests for unnecessary resources for a speed boost.\nRequests dropped are of type <code>font</code>, <code>image</code>, <code>media</code>, <code>beacon</code>, <code>object</code>, <code>imageset</code>, <code>texttrack</code>, <code>websocket</code>, <code>csp_report</code>, and <code>stylesheet</code>.</p>": "<p>阻止不必要的资源请求以提高速度。类型包括 <code>font</code>、<code>image</code>、<code>media</code>、<code>beacon</code>、<code>object</code>、<code>imageset</code>、<code>texttrack</code>、<code>websocket</code>、<code>csp_report</code> 和 <code>stylesheet</code>。</p>",
+ "<p>A set of domain names to block requests to. Subdomains are also matched (e.g., <code>\"example.com\"</code> blocks <code>\"sub.example.com\"</code> too).</p>": "<p>要阻止请求的域名集合,也会匹配子域名。例如,<code>\"example.com\"</code> 也会阻止 <code>\"sub.example.com\"</code>。</p>",
+ "<p>Block requests to ~3,500 known ad/tracking domains. Can be combined with <code>blocked_domains</code>.</p>": "<p>阻止向约 3,500 个已知广告或跟踪域名发送请求,可与 <code>blocked_domains</code> 结合使用。</p>",
+ "<p>Route DNS queries through Cloudflare's DNS-over-HTTPS to prevent DNS leaks when using proxies.</p>": "<p>通过 Cloudflare 的 DNS-over-HTTPS 发送 DNS 查询,避免使用代理时发生 DNS 泄露。</p>",
+ "<p>Pass a useragent string to be used. Otherwise the fetcher will generate a real Useragent of the same browser and use it.</p>": "<p>指定 User-Agent 字符串。未指定时,Fetcher 会生成并使用相同浏览器的真实 User-Agent。</p>",
+ "<p>Set cookies for the next request.</p>": "<p>为下一次请求设置 Cookie。</p>",
+ "<p>Wait for the page until there are no network connections for at least 500 ms.</p>": "<p>等待页面至少连续 500 ms 没有网络连接。</p>",
+ "<p>The timeout in milliseconds that is used in all operations and waits through the page. The default is 30,000</p>": "<p>页面所有操作和等待的超时时间,单位为毫秒,默认为 30,000。</p>",
+ "<p>The time (milliseconds) the fetcher will wait after everything finishes before closing the page and returning the <code>Response</code> object.</p>": "<p>所有步骤完成后,在关闭页面并返回 <code>Response</code> 对象前额外等待的时间,单位为毫秒。</p>",
+ "<p>Added for automation. A function that takes the <code>page</code> object, runs after navigation, and does the automation you need.</p>": "<p>用于自动化的函数,接收 <code>page</code> 对象,在导航后执行所需操作。</p>",
+ "<p>A function that takes the <code>page</code> object, runs before navigation. Use it to register event listeners or routes that must be set up before the page loads.</p>": "<p>接收 <code>page</code> 对象并在导航前执行的函数。用于注册必须在页面加载前准备好的事件监听器或路由。</p>",
+ "<p>Wait for a specific CSS selector to be in a specific state.</p>": "<p>等待指定 CSS 选择器达到指定状态。</p>",
+ "<p>An absolute path to a JavaScript file to be executed on page creation for all pages in this session.</p>": "<p>JavaScript 文件的绝对路径,在此会话中的每个页面创建时执行。</p>",
+ "<p>Specify user locale, for example, <code>en-GB</code>, <code>de-DE</code>, etc. Locale will affect navigator.language value, Accept-Language request header value as well as number and date formatting\nrules. Defaults to the system default locale.</p>": "<p>区域设置,例如 <code>en-GB</code>、<code>de-DE</code>。影响 navigator.language、请求头 Accept-Language,以及数字和日期格式。默认使用系统区域设置。</p>",
+ "<p>Changes the timezone of the browser. Defaults to the system timezone.</p>": "<p>修改浏览器时区,默认使用系统时区。</p>",
+ "<p>The state to wait for the selector given with <code>wait_selector</code>. The default state is <code>attached</code>.</p>": "<p>等待 <code>wait_selector</code> 指定的元素达到这个状态。默认为 <code>attached</code>。</p>",
+ "<p>Solves all types of the Cloudflare's Turnstile/Interstitial challenges before returning the response to you.</p>": "<p>返回响应前,处理所有类型的 Cloudflare Turnstile 和 Interstitial 挑战。</p>",
+ "<p>If you have a Chrome browser installed on your device, enable this, and the Fetcher will launch an instance of your browser and use it.</p>": "<p>如果设备上已安装 Chrome,启用此选项后,Fetcher 会启动并使用它。</p>",
+ "<p>Add random noise to canvas operations to prevent fingerprinting.</p>": "<p>为 Canvas 操作添加随机噪声,防止指纹识别。</p>",
+ "<p>Forces WebRTC to respect proxy settings to prevent local IP address leak.</p>": "<p>强制 WebRTC 遵守代理设置,避免泄露本地 IP 地址。</p>",
+ "<p>Enabled by default. Disabling it disables WebGL and WebGL 2.0 support entirely. Disabling WebGL is not recommended as many WAFs now check if WebGL is enabled.</p>": "<p>默认开启。关闭后会完全禁用 WebGL 和 WebGL 2.0。不建议关闭,因为很多 WAF 会检查 WebGL 是否启用。</p>",
+ "<p>Enabled by default, wait for all JavaScript on page(s) to fully load and execute.</p>": "<p>等待页面上的所有 JavaScript 加载并执行,默认开启。</p>",
+ "<p>Include open Shadow DOM content in the response HTML. Defaults to False.</p>": "<p>将开放的 Shadow DOM 内容加入响应 HTML,默认为 False。</p>",
+ "<p>Instead of launching a new browser instance, connect to this CDP URL to control real browsers through CDP.</p>": "<p>连接此 CDP URL 来控制已有浏览器,而不是启动新实例。</p>",
+ "<p>Enabled by default, Scrapling will set a Google referer header.</p>": "<p>默认开启,Scrapling 会设置 Google referer 请求头。</p>",
+ "<p>A dictionary of extra headers to add to the request. <em>The referer set by <code>google_search</code> takes priority over the referer set here if used together.</em></p>": "<p>要添加到请求中的额外请求头字典。<em>同时使用时,<code>google_search</code> 设置的 referer 优先于这里的值。</em></p>",
+ "<p>The proxy to be used with requests, it can be a string or a dictionary with the keys 'server', 'username', and 'password' only.</p>": "<p>请求使用的代理,可以是字符串,或仅包含 'server'、'username'、'password' 的字典。</p>",
+ "<p>Path to a User Data Directory, which stores browser session data like cookies and local storage. The default is to create a temporary directory.</p>": "<p>用户数据目录的路径,用于保存 Cookie、本地存储等浏览器会话数据。默认创建临时目录。</p>",
+ "<p>A list of additional browser flags to pass to the browser on launch.</p>": "<p>启动浏览器时传入的额外参数列表。</p>",
+ "<p>The arguments that will be passed in the end while creating the final Selector's class.</p>": "<p>创建最终 Selector 对象时传入的参数。</p>",
+ "<p>Additional arguments to be passed to Playwright's context as additional settings, and it takes higher priority than Scrapling's settings.</p>": "<p>传给 Playwright 上下文的额外设置,优先级高于 Scrapling 设置。</p>",
+ "<p>A <code>Response</code> object.</p>": "<p>一个 <code>Response</code> 对象。</p>",
+ "<p>A factory context manager that provides configured Fetcher sessions.</p>": "<p>创建已配置 Fetcher 会话的上下文管理器。</p>",
+ "<p>When this manager is used in a 'with' or 'async with' block,\nit yields a new session configured with the manager's defaults.\nA single instance of this manager should ideally be used for one active\nsession at a time (or sequentially). Re-entering a context with the\nsame manager instance while a session is already active is disallowed.</p>": "<p>在 'with' 或 'async with' 代码块中使用时,这个管理器会提供一个采用默认配置的新会话。建议每个管理器实例同时只用于一个活动会话,或按顺序创建多个会话。已有会话运行时,不允许用同一个实例再次进入上下文。</p>",
+ "<p>Browser version to impersonate. Can be a single browser string or a list of browser strings for random selection. (Default: latest available Chrome version)</p>": "<p>要模拟的浏览器版本。可以是单个浏览器字符串,或用于随机选择的字符串列表。默认使用最新可用的 Chrome 版本。</p>",
+ "<p>Whether to use HTTP3. Defaults to False. It might be problematic if used it with <code>impersonate</code>.</p>": "<p>是否使用 HTTP3,默认为 False。与 <code>impersonate</code> 同时使用可能出现问题。</p>",
+ "<p>If enabled (default), it creates and adds real browser headers. It also sets a Google referer header.</p>": "<p>生成并添加真实浏览器请求头,包括 Google referer,默认开启。</p>",
+ "<p>Dict of proxies to use. Format: {\"http\": proxy_url, \"https\": proxy_url}.</p>": "<p>要使用的代理字典,格式为 {\"http\": proxy_url, \"https\": proxy_url}。</p>",
+ "<p>Proxy URL to use. Format: \"http://username:password@localhost:8030\".\nCannot be used together with the <code>proxies</code> parameter.</p>": "<p>要使用的代理 URL,格式为 \"http://username:password@localhost:8030\"。不能与 <code>proxies</code> 参数同时使用。</p>",
+ "<p>HTTP basic auth for proxy, tuple of (username, password).</p>": "<p>代理的 HTTP Basic 认证,格式为 (username, password) 元组。</p>",
+ "<p>Number of seconds to wait before timing out.</p>": "<p>超时前等待的秒数。</p>",
+ "<p>Headers to include in the session with every request.</p>": "<p>会话中每次请求都会发送的请求头。</p>",
+ "<p>Number of retry attempts. Defaults to 3.</p>": "<p>重试次数,默认为 3。</p>",
+ "<p>Number of seconds to wait between retry attempts. Defaults to 1 second.</p>": "<p>重试之间的等待秒数,默认为 1 秒。</p>",
+ "<p>Whether to follow redirects. Defaults to \"safe\", which follows redirects but rejects those targeting internal/private IPs (SSRF protection). Pass True to follow all redirects without restriction.</p>": "<p>是否跟随重定向。默认为 \"safe\",跟随重定向但拒绝指向内部或私有 IP 的目标,以防范 SSRF。传入 True 可不受限制地跟随所有重定向。</p>",
+ "<p>Maximum number of redirects. Default 30, use -1 for unlimited.</p>": "<p>最大重定向次数,默认为 30,设为 -1 表示不限制。</p>",
+ "<p>Whether to verify HTTPS certificates. Defaults to True.</p>": "<p>是否验证 HTTPS 证书,默认为 True。</p>",
+ "<p>Tuple of (cert, key) filenames for the client certificate.</p>": "<p>客户端证书和密钥的文件名元组,格式为 (cert, key)。</p>",
+ "<p>Arguments passed when creating the final Selector class.</p>": "<p>创建最终 Selector 对象时传入的参数。</p>",
+ "<p>A ProxyRotator instance for automatic proxy rotation.</p>": "<p>用于自动轮换代理的 ProxyRotator 实例。</p>",
+ "<p>Creates and returns a new synchronous Fetcher Session</p>": "<p>创建并返回新的同步 Fetcher 会话。</p>",
+ "<p>Creates and returns a new asynchronous Session.</p>": "<p>创建并返回新的异步会话。</p>",
+ "<p>A Stealthy Browser session manager with page pooling.</p>": "<p>使用页面池的隐身浏览器会话管理器。</p>",
+ "<p>A Browser session manager with page pooling, it's using a persistent browser Context by default with a temporary user profile directory.</p>": "<p>使用页面池的浏览器会话管理器。默认使用持久浏览器上下文和临时用户配置目录。</p>",
+ "<p>Save completed browser requests and responses. Failed or unfinished requests are omitted. Defaults to False.</p>": "<p>保存已完成的浏览器请求和响应。失败或尚未完成的请求会被省略,默认为 False。</p>",
+ "<p>Maximum retained requests per session. Defaults to 1000; older entries are removed.</p>": "<p>每个会话最多保留的请求数,默认为 1,000,旧条目会被移除。</p>",
+ "<p>Save cookies, local storage and IndexedDB to a Playwright-compatible JSON file.</p>": "<p>将 Cookie、本地存储和 IndexedDB 保存到与 Playwright 兼容的 JSON 文件。</p>",
+ "<p>Requires a started session without proxy rotation. Does not save sessionStorage.</p>": "<p>需要已启动且未启用代理轮换的会话。不保存 sessionStorage。</p>",
+ "<p>Replace cookies, local storage and IndexedDB from a Playwright-compatible JSON file.</p>": "<p>使用与 Playwright 兼容的 JSON 文件替换 Cookie、本地存储和 IndexedDB。</p>",
+ "<p>Requires a started session without proxy rotation. Fetch or reload pages to use the restored login.</p>": "<p>需要已启动且未启用代理轮换的会话。获取或重新加载页面后,才能使用恢复的登录状态。</p>",
+ "<p>Close every open tab in the session's pool. The next request opens a fresh tab.</p>": "<p>关闭会话池中的所有标签页。下一次请求会打开新的标签页。</p>",
+ "<p>Close all resources</p>": "<p>关闭所有资源。</p>",
+ "<p>Get statistics about the current page pool</p>": "<p>获取当前页面池的统计信息。</p>",
+ "<p>Create a browser for this instance and context.</p>": "<p>为此实例及上下文创建浏览器。</p>",
+ "<p>Opens up the browser and do your request based on your chosen options.</p>": "<p>打开浏览器,按所选选项发送请求。</p>",
+ "<p>The Target url.</p>": "<p>目标 URL。</p>",
+ "<p>Static proxy to override rotator and session proxy. A new browser context will be created and used with it.</p>": "<p>覆盖代理轮换器和会话代理的固定代理。会为它创建并使用新的浏览器上下文。</p>",
+ "<p>An async Stealthy Browser session manager with page pooling.</p>": "<p>使用页面池的异步隐身浏览器会话管理器。</p>",
+ "<p>A thread-safe proxy rotator with pluggable rotation strategies.</p>": "<p>线程安全的代理轮换器,支持替换轮换策略。</p>",
+ "<p>Supports:\n- Cyclic rotation (default)\n- Custom rotation strategies via callable\n- Both string URLs and Playwright-style dict proxies</p>": "<p>支持默认的循环轮换、通过可调用对象实现的自定义策略,以及 URL 字符串或 Playwright 格式的代理字典。</p>",
+ "<p>Initialize the proxy rotator.</p>": "<p>初始化代理轮换器。</p>",
+ "<p>List of proxy URLs or Playwright-style proxy dicts.\n- String format: \"http://proxy1:8080\" or \"http://user:pass@proxy:8080\"\n- Dict format: {\"server\": \"http://proxy:8080\", \"username\": \"user\", \"password\": \"pass\"}</p>": "<p>代理 URL 或 Playwright 格式的代理字典列表。字符串格式:\"http://proxy1:8080\" 或 \"http://user:pass@proxy:8080\"。字典格式:{\"server\": \"http://proxy:8080\", \"username\": \"user\", \"password\": \"pass\"}。</p>",
+ "<p>Rotation strategy function. Takes (proxies, current_index) and returns (proxy, next_index). Defaults to cyclic_rotation.</p>": "<p>轮换策略函数,接收 (proxies, current_index),返回 (proxy, next_index),默认为 cyclic_rotation。</p>",
+ "<p>Get a copy of all configured proxies.</p>": "<p>获取所有已配置代理的副本。</p>",
+ "<p>Get the next proxy according to the rotation strategy.</p>": "<p>根据轮换策略获取下一个代理。</p>",
+ "<p>Return the total number of configured proxies.</p>": "<p>返回已配置代理的总数。</p>",
+ "<p>Extends standard Python string by adding more functionality</p>": "<p>扩展标准 Python 字符串,提供更多功能。</p>",
+ "<p>Return a sorted version of the string</p>": "<p>返回排序后的字符串。</p>",
+ "<p>Return a new version of the string after removing all white spaces and consecutive spaces</p>": "<p>移除所有空白字符和连续空格,返回新的字符串。</p>",
+ "<p>Return JSON response if the response is jsonable otherwise throw error</p>": "<p>将响应解析为 JSON,无法解析时抛出错误。</p>",
+ "<p>If enabled, this will ignore all whitespaces and consecutive spaces while matching</p>": "<p>启用后,匹配时忽略所有空白字符和连续空格。</p>",
+ "<p>If disabled, function will set the regex to ignore the letters-case while compiling it</p>": "<p>关闭后,编译正则表达式时忽略大小写。</p>",
+ "<p>Used to quickly check if this regex matches or not without any operations on the results</p>": "<p>快速检查正则表达式是否匹配,不对结果进行其他处理。</p>",
+ "<p>The :class:<code>TextHandlers</code> class is a subclass of the builtin <code>List</code> class, which provides a few additional methods.</p>": "<p>:class:<code>TextHandlers</code> 继承内置的 <code>List</code> 类,并提供一些额外方法。</p>",
+ "<p>Call the <code>.re()</code> method for each element in this list and return\ntheir results flattened as TextHandlers.</p>": "<p>对列表中每个元素调用 <code>.re()</code>,将结果展平后作为 TextHandlers 返回,不包含嵌套列表。</p>",
+ "<p>if disabled, the function will set the regex to ignore the letters-case while compiling it</p>": "<p>关闭后,编译正则表达式时忽略大小写。</p>",
+ "<p>Call the <code>.re_first()</code> method for each element in this list and return\nthe first result or the default value otherwise.</p>": "<p>对列表中每个元素调用 <code>.re_first()</code>,返回第一个匹配结果,没有匹配时返回默认值。</p>",
+ "<p>Returns the first item of the current list</p>": "<p>返回当前列表的第一个元素。</p>",
+ "<p>the default value to return if the current list is empty</p>": "<p>当前列表为空时返回的默认值。</p>",
+ "<p>A read-only mapping to use instead of the standard dictionary for the speed boost, but at the same time I use it to add more functionalities.\nIf the standard dictionary is needed, convert this class to a dictionary with the <code>dict</code> function</p>": "<p>用于替代标准字典的只读映射,速度更快,并提供额外功能。如需普通字典,可以使用 <code>dict</code> 函数转换。</p>",
+ "<p>Convert current attributes to JSON bytes if the attributes are JSON serializable otherwise throws error</p>": "<p>将当前属性转换为 JSON 字节,如果属性无法序列化为 JSON,则抛出错误。</p>",
+ "<p>Acts like the standard dictionary <code>.get()</code> method</p>": "<p>与标准字典的 <code>.get()</code> 方法相同。</p>",
+ "<p>Search current attributes by values and return a dictionary of each matching item</p>": "<p>按值搜索当前属性,并为每个匹配项返回一个字典。</p>",
+ "<p>The keyword to search for in the attribute values</p>": "<p>要在属性值中查找的文本。</p>",
+ "<p>If True, the function will search if keyword in each value instead of perfect match</p>": "<p>为 True 时,检查每个值是否包含指定文本,而不是要求完全匹配。</p>",
+ "<p>Request's response information structure.</p>": "<p>保存请求响应信息的数据结构。</p>",
+ "<p><code>browser_network_requests</code> returns <code>NetworkRequestsModel</code> with <code>requests</code>, <code>next_cursor</code>, <code>has_more</code>, and <code>dropped_count</code>. Each <code>NetworkRequestInfo</code> contains <code>id</code>, <code>url</code>, <code>method</code>, <code>resource_type</code>, and <code>status</code>. Pass <code>next_cursor</code> as <code>after_id</code> to continue; <code>has_more</code> indicates more current matches.</p>": "<p><code>browser_network_requests</code> 返回 <code>NetworkRequestsModel</code>,包含 <code>requests</code>、<code>next_cursor</code>、<code>has_more</code> 和 <code>dropped_count</code>。每个 <code>NetworkRequestInfo</code> 包含 <code>id</code>、<code>url</code>、<code>method</code>、<code>resource_type</code> 和 <code>status</code>。将 <code>next_cursor</code> 作为 <code>after_id</code> 传入即可继续读取。<code>has_more</code> 表示当前还有更多匹配项。</p>",
+ "<p><code>browser_network_request</code> returns <code>NetworkRequestModel</code> with <code>request_id</code>, <code>part</code>, <code>data</code>, and <code>note</code>. Summaries and headers are objects; the full saved body text is returned as a string, including JSON response text. <code>note</code> explains missing body data or partial headers.</p>": "<p><code>browser_network_request</code> 返回 <code>NetworkRequestModel</code>,包含 <code>request_id</code>、<code>part</code>、<code>data</code> 和 <code>note</code>。摘要和头信息以对象返回;保存的完整响应体文本以字符串返回,JSON 响应也一样。<code>note</code> 说明响应体缺失或头信息不完整的情况。</p>",
+ "<p>Summary of a recorded browser request.</p>": "<p>已记录浏览器请求的摘要。</p>",
+ "<p>Recorded request summaries and pagination details.</p>": "<p>已记录请求的摘要及分页信息。</p>",
+ "<p>One complete saved request part, with an optional note.</p>": "<p>已保存请求中某一部分的完整内容,以及可选说明。</p>",
+ "<p>Model classes for session management:</p>": "<p>用于会话管理的模型类:</p>",
+ "<p>Information about an open browser session.</p>": "<p>已打开的浏览器会话信息。</p>",
+ "<p>Response returned when a new session is created.</p>": "<p>创建新会话时返回的响应。</p>",
+ "<p>Response returned when a session is closed.</p>": "<p>关闭会话时返回的响应。</p>",
+ "<p>The main MCP server class that provides all web scraping tools:</p>": "<p>提供所有网页抓取工具的 MCP 服务器主类:</p>",
+ "<p><strong><code>browser_fetch_once</code></strong>: Fetch one URL through a stealthy browser with JavaScript rendering and Cloudflare handling, then close the browser. Use a persistent session for later actions or network history.</p>": "<p><strong><code>browser_fetch_once</code></strong>:通过隐身浏览器获取一个 URL,支持 JavaScript 渲染和 Cloudflare 验证,随后关闭浏览器。如需后续操作或网络历史记录,请使用持久会话。</p>",
+ "<p><strong><code>browser_extract</code></strong>: Read the current page or one element as an AI snapshot, HTML, Markdown, or text without reloading it. Keep results from forms and page actions. Snapshots include element roles, names, references, positions, and sizes; regex search returns matching lines with nearby context and parent nodes.</p>": "<p><strong><code>browser_extract</code></strong>:无需重新加载,即可以 AI 快照、HTML、Markdown 或文本形式读取当前页面或某个元素,并保留表单和页面操作的结果。快照包含元素的角色、名称、引用、位置和大小;正则表达式搜索会返回匹配的行、附近的上下文和父节点。</p>",
+ "<p><strong><code>browser_actions</code></strong>: Chain mouse moves, hovers, clicks, scrolling, field filling, keyboard shortcuts, dialog replies, and waits in one call. Accept or dismiss alerts and confirmations, or enter text in prompts. Fill a search box, submit it, wait for results, and open a result without a separate call for each step.</p>": "<p><strong><code>browser_actions</code></strong>:在一次调用中连续执行鼠标移动、悬停、点击、滚动、字段填写、键盘快捷键、对话框响应和等待。可以接受或关闭提示框与确认框,也可以在输入对话框中填写文本。填写搜索框、提交、等待结果并打开某个结果,无需为每一步单独调用。</p>",
+ "<p>Moves and clicks target selectors, snapshot references, or coordinates; element targets wait and scroll into view. Supports movement in multiple steps, left, right, and middle clicks, double-clicks, and scrolling nested panels.</p>": "<p>移动和点击操作可以通过选择器、快照引用或坐标指定目标;目标为元素时,会等待元素并将其滚动到可见区域。支持分多步移动、左键、右键和中键点击、双击,以及在嵌套面板内滚动。</p>",
+ "<p>Target fields anywhere on the page through selectors or snapshot references. Fill text, check or uncheck boxes, select radio buttons, and choose one or more native dropdown options by label. Replace or clear text, or type at the current caret. Keyboard shortcuts use the current focus. Slow mode adds random pauses between typed characters and all actions.</p>": "<p>通过选择器或快照引用定位页面任意位置的字段。可以填写文本、勾选或取消勾选复选框、选择单选按钮,以及按标签选择一个或多个原生下拉选项。可以替换或清空文本,也可以在当前光标位置输入。键盘快捷键作用于当前焦点。慢速模式会在输入字符之间和各项操作之间加入随机暂停。</p>",
+ "<p>Wait for content or loading overlays through selectors or snapshot references, wait for page load events or settled network activity, or add a fixed pause before continuing.</p>": "<p>通过选择器或快照引用等待内容或加载遮罩,等待页面加载事件或网络活动稳定,也可以在继续前暂停指定时间。</p>",
+ "<p><strong><code>browser_evaluate</code></strong>: Run JavaScript on the current page to extract custom data, calculate results, read application state, or update page content. Supports asynchronous scripts and returns their results as JSON.</p>": "<p><strong><code>browser_evaluate</code></strong>:在当前页面运行 JavaScript,以提取自定义数据、计算结果、读取应用状态或更新页面内容。支持异步脚本,并以 JSON 返回结果。</p>",
+ "<p>Create a Scrapling MCP server.</p>": "<p>创建 Scrapling MCP 服务器。</p>",
+ "<p>Optional global Chromium-compatible browser executable path for browser tools.\nIf omitted, the SCRAPLING_EXECUTABLE_PATH environment variable is used when set.</p>": "<p>为浏览器工具设置兼容 Chromium 的浏览器可执行文件路径,作为全局默认值。此项可选。如未指定,则使用已设置的 SCRAPLING_EXECUTABLE_PATH 环境变量。</p>",
+ "<p>Optional shared token that clients must send as <code>Authorization: Bearer &lt;token&gt;</code>.\nIf omitted, the SCRAPLING_MCP_AUTH_TOKEN environment variable is used when set. It only applies\nto the streamable-http transport.</p>": "<p>可选的共享 token,客户端必须通过 <code>Authorization: Bearer &lt;token&gt;</code> 发送。如未指定,则使用已设置的 SCRAPLING_MCP_AUTH_TOKEN 环境变量。仅适用于 streamable-http 传输方式。</p>",
+ "<p>Open a reusable stealthy browser session. Pass per-request options to <code>browser_fetch</code>.</p>": "<p>打开可复用的隐身浏览器会话。请求级选项请传给 <code>browser_fetch</code>。</p>",
+ "<p>Save browser cookies, local storage and IndexedDB as Playwright-compatible JSON. Excludes sessionStorage.</p>": "<p>将浏览器 Cookie、本地存储 和 IndexedDB 保存为兼容 Playwright 的 JSON。不包含 sessionStorage。</p>",
+ "<p>Replace browser cookies, local storage and IndexedDB from a Playwright-compatible JSON file.</p>": "<p>用兼容 Playwright 的 JSON 文件中的数据替换浏览器 Cookie、本地存储 和 IndexedDB。</p>",
+ "<p>Leaves sessionStorage and open tabs unchanged. Fetch or reload pages to use the restored login.</p>": "<p>不更改 sessionStorage 和已打开的标签页。获取或重新加载页面后,才能使用恢复的登录状态。</p>",
+ "<p>Open a reusable HTTP session for <code>session_make_request</code>, keeping cookies, connections, and request settings.</p>": "<p>打开供 <code>session_make_request</code> 使用的可复用 HTTP 会话,保留 Cookie、连接和请求设置。</p>",
+ "<p>Close a session and free its resources.</p>": "<p>关闭会话并释放其资源。</p>",
+ "<p>List registered sessions, their status, and effective settings.</p>": "<p>列出已注册的会话、它们的状态和实际生效的设置。</p>",
+ "<p>List completed requests across page changes, with IDs and pagination. Recording starts when the browser session opens.</p>": "<p>列出跨页面切换保留的已完成请求,包含 ID 并支持分页。浏览器会话打开后就开始记录。</p>",
+ "<p>Read a complete saved request part without resending it, with structured data and availability notes.</p>": "<p>完整读取已保存请求的某一部分,无需重新发送请求,并返回结构化数据和可用性说明。</p>",
+ "<p>Read the current page or one element as snapshot, HTML, Markdown, or text without navigating.\nReturn plain text; snapshot search keeps refs, ancestor paths and three lines of nearby context.</p>": "<p>无需导航,即可以快照、HTML、Markdown 或文本形式读取当前页面或某个元素。返回纯文本;快照搜索会保留引用、祖先路径和附近三行上下文。</p>",
+ "<p>Run mouse, field, key, dialog, and wait actions in order; return plain text without a snapshot.\nStop on the first error, identifying its action; partial effects remain. No retries.\nElement mouse targets auto-wait and scroll into view; coordinates and wheel do not wait for navigation or scrolling.\nCancelled/timed-out clicks attempt button release. Load waits observe the current document, not future navigation.</p>": "<p>按顺序执行鼠标、字段、按键、对话框和等待操作;返回纯文本,不附带快照。遇到第一个错误时停止,并指出出错的操作;已产生的效果会保留,不会重试。鼠标操作以元素为目标时,会自动等待并将其滚动到可见区域;坐标和滚轮操作不会等待导航或滚动完成。点击被取消或超时时,会尝试释放鼠标按键。加载等待只观察当前文档,不会等待后续导航。</p>",
+ "<p>Run JavaScript on the current page, await promises, and return JSON text without a snapshot.\nReturn JSON-compatible values; null/undefined become null. Script effects are not undone on failure.\nCancellation stops waiting, but may not stop the script.</p>": "<p>在当前页面运行 JavaScript,等待 Promise 完成,并返回 JSON 文本,不附带快照。脚本应返回兼容 JSON 的值;null/undefined 会变为 null。失败时不会撤销脚本已产生的效果。取消操作会停止等待,但可能不会停止脚本。</p>",
+ "<p>Capture the current page or one element without navigating; return the image and current URL.\nElement capture waits and scrolls into view. Use browser_actions for other waits before capture.</p>": "<p>无需导航,即可截取当前页面或某个元素;返回图片和当前 URL。截取元素时,会等待元素并将其滚动到可见区域。截图前如需其他等待,请使用 browser_actions。</p>",
+ "<p>Make an HTTP request without JavaScript. Suitable for low-to-mid protection.</p>": "<p>发送不执行 JavaScript 的 HTTP 请求。适用于防护程度低到中等的网站。</p>",
+ "<p>Fetch a page with a stealth browser and JavaScript rendering.</p>": "<p>通过隐身浏览器获取页面,并执行 JavaScript 渲染。</p>",
+ "<p>Fetch a URL in an open stealthy browser session. Options apply only to this request.</p>": "<p>通过已打开的隐身浏览器会话获取一个 URL。选项仅对本次请求生效。</p>",
+ "<p>Make an HTTP request using the session's cookies, connections, impersonation, and proxy. Options apply to this request.</p>": "<p>使用会话的 Cookie、连接、浏览器模拟和代理发送 HTTP 请求。选项对本次请求生效。</p>",
+ "<p>Serve the MCP server.</p>": "<p>启动 MCP 服务器。</p>",
+ "<p>Serve over the streamable-http transport instead of stdio.</p>": "<p>使用 streamable-http 传输方式提供服务,替代 stdio。</p>",
+ "<p>The host to bind to when <code>http</code> is enabled.</p>": "<p>启用 <code>http</code> 时绑定的主机地址。</p>",
+ "<p>The port to bind to when <code>http</code> is enabled.</p>": "<p>启用 <code>http</code> 时绑定的端口。</p>",
+ "<p>Host names to accept, which turns on DNS-rebinding protection.</p>": "<p>允许的主机名,设置后会启用 DNS 重绑定防护。</p>",
+ "<p>Start the streamable-http transport without a token. The transport\nrequires authentication by default, so this is the explicit opt-out.</p>": "<p>不使用 token 启动 streamable-http。该传输方式默认要求身份验证,此选项用于明确关闭身份验证。</p>",
+ "<p>The <code>Selectors</code> class is a subclass of the builtin <code>List</code> class, which provides a few additional methods.</p>": "<p><code>Selectors</code> 类是内置 <code>List</code> 类的子类,提供了一些额外方法。</p>",
+ "<p>Returns the first Selector item of the current list or <code>None</code> if the list is empty</p>": "<p>返回当前列表中的第一个 Selector 元素;列表为空时返回 <code>None</code>。</p>",
+ "<p>Returns the last Selector item of the current list or <code>None</code> if the list is empty</p>": "<p>返回当前列表中的最后一个 Selector 元素;列表为空时返回 <code>None</code>。</p>",
+ "<p>Returns the length of the current list</p>": "<p>返回当前列表的长度。</p>",
+ "<p>Call the <code>.xpath()</code> method for each element in this list and return\ntheir results as another <code>Selectors</code> class.</p>": "<p>对列表中的每个元素调用 <code>.xpath()</code> 方法,并将结果作为另一个 <code>Selectors</code> 对象返回。</p>",
+ "<p>A string that will be used to retrieve element's data in adaptive,\notherwise the selector will be used.</p>": "<p>用于在自适应模式中检索元素数据的字符串;未指定时使用选择器。</p>",
+ "<p>Call the <code>.css()</code> method for each element in this list and return\ntheir results flattened as another <code>Selectors</code> class.</p>": "<p>对列表中的每个元素调用 <code>.css()</code> 方法,将结果合并为一个 <code>Selectors</code> 对象并返回。</p>",
+ "<p>Call the <code>.re()</code> method for each element in this list and return\ntheir results flattened as List of TextHandler.</p>": "<p>对列表中的每个元素调用 <code>.re()</code> 方法,将结果合并为一个包含 TextHandler 的 List 并返回。</p>",
+ "<p>if disabled, function will set the regex to ignore the letters case while compiling it</p>": "<p>禁用后,函数会在编译正则表达式时设置忽略字母大小写。</p>",
+ "<p>Loop over all current elements and return the first element that matches the passed function</p>": "<p>遍历当前所有元素,并返回第一个符合传入函数条件的元素。</p>",
+ "<p>A function that takes each element as an argument and returns True/False</p>": "<p>接收每个元素作为参数并返回 True/False 的函数。</p>",
+ "<p>The first element that match the function or <code>None</code> otherwise.</p>": "<p>返回第一个符合函数条件的元素;没有匹配时返回 <code>None</code>。</p>",
+ "<p>Filter current elements based on the passed function</p>": "<p>根据传入的函数筛选当前元素。</p>",
+ "<p>The new <code>Selectors</code> object or empty list otherwise.</p>": "<p>返回新的 <code>Selectors</code> 对象;没有匹配时返回空列表。</p>",
+ "<p>Returns the serialized string of the first element, or <code>default</code> if empty.</p>": "<p>返回第一个元素序列化后的字符串;列表为空时返回 <code>default</code>。</p>",
+ "<p>Serialize all elements and return as a TextHandlers list.</p>": "<p>序列化所有元素,并以 TextHandlers 列表返回。</p>",
+ "<p>An abstract base class for creating web spiders.</p>": "<p>用于创建网页 Spider 的抽象基类。</p>",
+ "<p>Check the documentation website for more information.</p>": "<p>更多信息请查看文档网站。</p>",
+ "<p>Initialize the spider.</p>": "<p>初始化 Spider。</p>",
+ "<p>Directory for checkpoint files. If provided, enables pause/resume.</p>": "<p>检查点文件目录。指定后即可暂停和恢复。</p>",
+ "<p>Seconds between periodic checkpoint saves (default 5 minutes).</p>": "<p>定期保存检查点的间隔,单位为秒(默认 5 分钟)。</p>",
+ "<p>Access current crawl stats (works during streaming).</p>": "<p>访问当前抓取的统计数据(流式模式下也可使用)。</p>",
+ "<p>Generate initial requests to start the crawl.</p>": "<p>生成开始抓取所需的初始请求。</p>",
+ "<p>By default, this generates Request objects for each URL in <code>start_urls</code>\nusing the session manager's default session and <code>parse()</code> as callback.</p>": "<p>默认会为 <code>start_urls</code> 中的每个 URL 生成 Request 对象,使用会话管理器的默认会话,并以 <code>parse()</code> 作为回调。</p>",
+ "<p>Override this method for more control over initial requests\n(e.g., to add custom headers, use different callbacks, etc.)</p>": "<p>重写此方法可以更灵活地控制初始请求,例如添加自定义请求头、使用不同的回调等。</p>",
+ "<p>Default callback for processing responses</p>": "<p>处理响应的默认回调。</p>",
+ "<p>Called before crawling starts. Override for setup logic.</p>": "<p>抓取开始前调用。可以重写以执行初始化逻辑。</p>",
+ "<p>It's enabled if the spider is resuming from a checkpoint, left for the user to use.</p>": "<p>Spider 从检查点恢复时,此值为启用状态,可按需使用。</p>",
+ "<p>Called after crawling finishes. Override for cleanup logic.</p>": "<p>抓取结束后调用。可以重写以执行清理逻辑。</p>",
+ "<p>Handle request errors for all spider requests.</p>": "<p>处理 Spider 所有请求中的错误。</p>",
+ "<p>Override for custom error handling.</p>": "<p>重写以自定义错误处理。</p>",
+ "<p>A hook to be overridden by users to do some processing on scraped items, return <code>None</code> to drop the item silently.</p>": "<p>可重写此钩子以处理抓取的数据项;返回 <code>None</code> 会静默丢弃该数据项。</p>",
+ "<p>Check if the response is blocked. Users should override this for custom detection logic.</p>": "<p>检查响应是否被封锁。可以重写以自定义检测逻辑。</p>",
+ "<p>Users should override this to prepare the blocked request before retrying, if needed.</p>": "<p>如需在重试前处理被封锁的请求,可以重写此方法。</p>",
+ "<p>String representation of the spider.</p>": "<p>Spider 的字符串表示。</p>",
+ "<p>Configure sessions for this spider.</p>": "<p>配置此 Spider 的会话。</p>",
+ "<p>Override this method to add custom sessions.\nThe default implementation creates a FetcherSession session.</p>": "<p>重写此方法以添加自定义会话。默认实现会创建一个 FetcherSession 会话。</p>",
+ "<p>The first session added becomes the default for <code>start_requests()</code> unless specified otherwise.</p>": "<p>除非另行指定,添加的第一个会话会成为 <code>start_requests()</code> 的默认会话。</p>",
+ "<p>SessionManager to configure</p>": "<p>要配置的 SessionManager。</p>",
+ "<p>Request graceful shutdown of the crawling process.</p>": "<p>请求有序停止抓取过程。</p>",
+ "<p>Run the spider and return results.</p>": "<p>运行 Spider 并返回结果。</p>",
+ "<p>This is the main entry point for running a spider.\nHandles async execution internally via anyio.</p>": "<p>这是运行 Spider 的主要入口,内部通过 anyio 处理异步执行。</p>",
+ "<p>Pressing Ctrl+C will initiate graceful shutdown (waits for active tasks to complete).\nPressing Ctrl+C a second time will force immediate stop.</p>": "<p>按 Ctrl+C 会开始有序停止,等待正在运行的任务完成。再次按 Ctrl+C 会立即强制停止。</p>",
+ "<p>If crawldir is set, a checkpoint will also be saved on graceful shutdown,\nallowing you to resume the crawl later by running the spider again.</p>": "<p>设置了 crawldir 时,有序停止还会保存检查点。以后再次运行 Spider 即可恢复抓取。</p>",
+ "<p>Whether to use the faster uvloop/winloop event loop implementation, if available.</p>": "<p>是否在可用时使用速度更快的 uvloop/winloop 事件循环实现。</p>",
+ "<p>Asyncio backend options to be used with <code>anyio.run</code></p>": "<p>传给 <code>anyio.run</code> 的 Asyncio 后端选项。</p>",
+ "<p>Stream items as they're scraped. Ideal for long-running spiders or building applications on top of the spiders.</p>": "<p>以流式方式输出抓取到的数据项。适合长时间运行的 Spider,或基于 Spider 构建应用。</p>",
+ "<p>Must be called from an async context. Yields items one by one as they are scraped.\nAccess <code>spider.stats</code> during iteration for real-time statistics.</p>": "<p>必须在异步上下文中调用。数据项抓取完成后会逐个产出。迭代时可以通过 <code>spider.stats</code> 访问实时统计数据。</p>",
+ "<p>Note: SIGINT handling for pause/resume is not available in stream mode.</p>": "<p>注意:流式模式不支持通过 SIGINT 处理暂停和恢复。</p>",
+ "<p>Create a copy of this request.</p>": "<p>创建此请求的副本。</p>",
+ "<p>Generate a unique fingerprint for deduplication.</p>": "<p>生成用于去重的唯一指纹。</p>",
+ "<p>Caches the result in self._fp after first computation.</p>": "<p>首次计算后,将结果缓存到 self._fp。</p>",
+ "<p>Compare requests by priority</p>": "<p>按优先级比较请求。</p>",
+ "<p>Requests are equal if they have the same fingerprint.</p>": "<p>指纹相同的请求视为相等。</p>",
+ "<p>Prepare state for pickling - store callback as name string for pickle compatibility.</p>": "<p>准备 pickle 序列化所需的状态,将回调名称保存为字符串,以兼容 pickle。</p>",
+ "<p>Restore state from pickle - callback restored later via _restore_callback().</p>": "<p>从 pickle 恢复状态,回调稍后通过 _restore_callback() 恢复。</p>",
+ "<p>Complete result from a spider run.</p>": "<p>一次 Spider 运行的完整结果。</p>",
+ "<p>True if the crawl completed normally (not paused).</p>": "<p>抓取正常完成(未暂停)时为 True。</p>",
+ "<p>Statistics for a crawl run.</p>": "<p>一次抓取运行的统计数据。</p>",
+ "<p>A list of scraped items with export capabilities.</p>": "<p>支持导出的抓取数据项列表。</p>",
+ "<p>Export items to a JSON file.</p>": "<p>将数据项导出到 JSON 文件。</p>",
+ "<p>Path to the output file</p>": "<p>输出文件的路径。</p>",
+ "<p>Pretty-print with 2-space indentation (slightly slower)</p>": "<p>使用 2 个空格缩进格式化输出(稍慢)。</p>",
+ "<p>Export items as JSON Lines (one JSON object per line).</p>": "<p>将数据项导出为 JSON Lines,每行一个 JSON 对象。</p>",
+ "<p>Export items to a CSV file.</p>": "<p>将数据项导出到 CSV 文件。</p>",
+ "<p>Items that don't share the same keys are still written, with the missing cells left empty, and any value\nthat isn't a scalar (a nested dictionary or a list) is written as JSON.</p>": "<p>键不完全相同的数据项仍会写入文件,缺失的单元格会留空,非标量值(嵌套字典或列表)会以 JSON 写入。</p>",
+ "<p>The columns to write, defaulting to every key found in the items, in the order they appeared</p>": "<p>要写入的列,默认包括数据项中的所有键,按首次出现的顺序排列。</p>",
+ "<p>The character separating the columns</p>": "<p>列分隔符。</p>",
+ "<p>Export items to an XML file.</p>": "<p>将数据项导出到 XML 文件。</p>",
+ "<p>Each item becomes an element whose children are named after the item's keys. Keys that aren't valid XML\nnames are rewritten and keep the original in a <code>name</code> attribute, and any value that isn't a scalar\n(a nested dictionary or a list) is written as JSON.</p>": "<p>每个数据项会变成一个元素,其子元素以数据项的键命名。不符合 XML 名称规则的键会被改写,原始名称保存在 <code>name</code> 属性中。非标量值(嵌套字典或列表)会以 JSON 写入。</p>",
+ "<p>The name of the element wrapping all the items</p>": "<p>包含所有数据项的元素名称。</p>",
+ "<p>The name of the element wrapping every item</p>": "<p>包含单个数据项的元素名称。</p>",
+ "<p>Pretty-print the file instead of writing it on a single line</p>": "<p>格式化文件,便于阅读,而不是将内容全部写在一行。</p>",
+ "<p>Manages pre-configured session instances.</p>": "<p>管理预先配置好的会话实例。</p>",
+ "<p>Register a session instance.</p>": "<p>注册会话实例。</p>",
+ "<p>Name to reference this session in requests</p>": "<p>在请求中引用此会话的名称。</p>",
+ "<p>Your pre-configured session instance</p>": "<p>预先配置好的会话实例。</p>",
+ "<p>If True, this becomes the default session</p>": "<p>为 True 时,将此会话设为默认会话。</p>",
+ "<p>If True, the session will be started only when a request uses its ID.</p>": "<p>为 True 时,仅在请求使用此会话 ID 时启动会话。</p>",
+ "<p>Removes a session.</p>": "<p>移除会话。</p>",
+ "<p>ID of session to remove</p>": "<p>要移除的会话 ID。</p>",
+ "<p>Remove and returns a session.</p>": "<p>移除并返回会话。</p>",
+ "<p>Start all sessions that aren't already alive.</p>": "<p>启动所有尚未运行的会话。</p>",
+ "<p>Close all registered sessions.</p>": "<p>关闭所有已注册的会话。</p>",
+ "<p>Check if a session ID is registered.</p>": "<p>检查会话 ID 是否已注册。</p>",
+ "<p>Number of registered sessions.</p>": "<p>已注册的会话数量。</p>"
+} %}
+{% macro translate(value) %}
+ {% set result = namespace(html=value | replace("Bases:", "基类:")) %}
+ {% for source, target in translations.items() %}
+ {% set result.html = result.html | replace(source, target | safe) %}
+ {% endfor %}
+ {{ result.html | safe }}
+{% endmacro %}
diff --git a/zensical-base.yml b/zensical-base.yml
index 699bdb0..25e5ea0 100644
--- a/zensical-base.yml
+++ b/zensical-base.yml
@@ -132,6 +132,9 @@ extra:
- name: Deutsch
link: https://scrapling.readthedocs.io/en/latest/de/
lang: de
+ - name: 简体中文
+ link: https://scrapling.readthedocs.io/en/latest/zh/
+ lang: zh
watch:
- zensical-base.yml
- docs/assets
diff --git a/zensical.zh.yml b/zensical.zh.yml
new file mode 100644
index 0000000..7da318a
--- /dev/null
+++ b/zensical.zh.yml
@@ -0,0 +1,99 @@
+INHERIT: zensical-base.yml
+site_description: Scrapling - 轻松抓取现代网站。
+site_url: https://scrapling.readthedocs.io/en/latest/zh/
+docs_dir: docs/locales/zh
+site_dir: site/zh
+edit_uri: edit/main/docs/locales/zh/
+copyright: Copyright &copy; 2025 Karim Shoair - <a href="#__consent">更改 Cookie 设置</a>
+nav:
+- 简介: index.md
+- 入门: overview.md
+- 性能测试: benchmarks.md
+- 使用指南:
+ - 解析页面:
+ - 选择元素: parsing/selection.md
+ - 主要类: parsing/main_classes.md
+ - 自适应抓取: parsing/adaptive.md
+ - 获取页面:
+ - 选择 Fetcher: fetching/choosing.md
+ - HTTP 请求: fetching/static.md
+ - 浏览器抓取: fetching/stealthy.md
+ - 爬虫:
+ - 架构: spiders/architecture.md
+ - 快速开始: spiders/getting-started.md
+ - 请求和响应: spiders/requests-responses.md
+ - 会话: spiders/sessions.md
+ - 代理和拦截: spiders/proxy-blocking.md
+ - 通用模板: spiders/generic-templates.md
+ - 平台模板: spiders/platform-templates.md
+ - 进阶功能: spiders/advanced.md
+ - 命令行:
+ - 概览: cli/overview.md
+ - 交互式 Shell: cli/interactive-shell.md
+ - 提取命令: cli/extract-commands.md
+ - AI 集成:
+ - MCP 服务器: ai/mcp-server.md
+ - Agent Skill: ai/agent-skill.md
+ - 构建 RAG 系统: ai/building-rag-systems.md
+ - 集成和迁移:
+ - 集成 Scrapy: integrations/scrapy.md
+ - 从 BeautifulSoup 迁移: tutorials/migrating_from_beautifulsoup.md
+- 教程:
+ - 免费替代 AI 数据提取服务: tutorials/replacing_ai.md
+- 开发:
+ - API 参考:
+ - Selector: api-reference/selector.md
+ - Fetcher: api-reference/fetchers.md
+ - MCP 服务器: api-reference/mcp-server.md
+ - 自定义类型: api-reference/custom-types.md
+ - Response: api-reference/response.md
+ - Spider: api-reference/spiders.md
+ - 代理轮换: api-reference/proxy-rotation.md
+ - 创建自己的元素定位存储系统: development/adaptive_storage_system.md
+ - 使用 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
+theme:
+ language: zh
+ palette:
+ - media: '(prefers-color-scheme: light)'
+ scheme: default
+ accent: green
+ primary: deep purple
+ toggle:
+ icon: lucide/sun
+ name: 切换到深色模式
+ - media: '(prefers-color-scheme: dark)'
+ scheme: slate
+ accent: light green
+ primary: deep purple
+ toggle:
+ icon: lucide/moon
+ name: 切换到浅色模式
+markdown_extensions:
+ toc:
+ permalink_title: 永久链接
+plugins:
+ mkdocstrings:
+ locale: zh
+extra:
+ analytics:
+ feedback:
+ title: 这页内容有帮助吗?
+ ratings:
+ - icon: material/heart
+ name: 这页内容有帮助
+ data: 1
+ note: 感谢反馈!
+ - icon: material/heart-broken
+ name: 这页内容需要改进
+ data: 0
+ note: '感谢反馈!请<a href="https://github.com/D4Vinci/Scrapling/issues/new?template=04-docs_issue.yml" target="_blank" rel="noopener">报告文档问题</a>,帮助我们改进这一页。'
+ consent:
+ title: Cookie 许可
+ description: 我们使用 Cookie 保存偏好设置,并了解文档是否有帮助。你的许可有助于我们改进文档。
+ actions:
+ - accept
+ - reject
+ - manage