> [!NOTE] > 本文档由 WeHub 基于上游 README 翻译整理,属于社区翻译,非官方中文文档。 > [English](./README.en.md) · [原始项目](https://github.com/D4Vinci/Scrapling) · [上游 README](https://github.com/D4Vinci/Scrapling/blob/HEAD/README.md) > 原作者、版权与许可证归属以原始项目及本仓库 LICENSE 文件为准。
العربيه | Español | Português (Brasil) | Français | Deutsch | 简体中文 | 日本語 | Русский | 한국어
选择方法 · Fetchers · Spiders · 代理轮换 · CLI · MCP
Scrapling 是一款自适应 Web Scraping(网页爬取)框架,可处理从单次请求到大规模爬取的一切场景。 其解析器会学习网站变化,并在页面更新时自动重新定位你的元素。其 Fetcher 可开箱即用地绕过 Cloudflare Turnstile 等反机器人系统。其 Spider 框架让你只需几行 Python 代码,即可扩展到并发、多会话爬取,并支持暂停/恢复与自动代理轮换——一个库,零妥协。 极速爬取,实时统计与流式输出。由网页爬取从业者打造,兼顾专业用户与普通用户,人人适用。 ```python from scrapling.fetchers import Fetcher, AsyncFetcher, StealthyFetcher, DynamicFetcher StealthyFetcher.adaptive = True p = StealthyFetcher.fetch('https://example.com', headless=True, network_idle=True) # Fetch website under the radar! products = p.css('.product', auto_save=True) # Scrape data that survives website design changes! products = p.css('.product', adaptive=True) # Later, if the website structure changes, pass `adaptive=True` to find them! ``` 或扩展到完整爬取 ```python from scrapling.spiders import Spider, Response class MySpider(Spider): name = "demo" start_urls = ["https://example.com/"] async def parse(self, response: Response): for item in response.css('.product'): yield {"title": item.css('h2::text').get()} MySpider().start() ``` # Platinum Sponsors
|
Proxidize 提供移动与住宅代理,适用于爬取、浏览器自动化、SEO 监控、AI Agent 与数据采集。使用优惠码 scrapling20 可享 8 折。 |
|
ColdProxy 提供住宅与数据中心代理,用于稳定的网页爬取、公开数据采集,以及覆盖 195+ 个国家的地理定向测试。 |
|
Scrapling 可处理 Cloudflare Turnstile。针对企业级防护, Hyper Solutions 提供 API 端点,可为 Akamai、DataDome、Kasada 和 Incapsula 生成有效的反机器人令牌。简单 API 调用,无需浏览器自动化。 |
|
Evomi :住宅代理低至 $0.49/GB。爬取浏览器配备完整伪装的 Chromium、住宅 IP、自动 CAPTCHA 求解与反机器人绕过。 提供 Scraper API,轻松获取结果。支持 MCP 与 N8N 集成。 |
|
TikHub.io 提供 900+ 稳定 API,覆盖 TikTok、X、YouTube 和 Instagram 等 16+ 平台,拥有 40M+ 数据集。 另提供折扣 AI 模型——Claude、GPT、GEMINI 等,最高可省 71%。 |
|
合上笔记本,爬虫仍在运行。 PetroSky VPS——专为不间断自动化打造的云服务器。提供 Windows 与 Linux 机器,完全可控。起价 €6.99/月。 |
|
阅读 The Web Scraping Club 对 Scrapling 的完整评测(2025 年 11 月),这是专注于 Web Scraping 的头号 Newsletter。 |
|
Swiftproxy 提供可扩展的住宅代理,拥有 80M+ IP,覆盖 195+ 个国家,连接快速可靠,支持自动轮换,具备出色的防封性能。提供免费试用。 |
|
|
NodeMaven——可靠的代理提供商,拥有市场上质量最高的 IP。使用优惠码 SCRAPLING35 可享代理 35% 折扣。 |
您想在此展示广告?点击[此处](https://github.com/sponsors/D4Vinci))选择适合您的赞助等级!
---
## 核心特性
### Spiders——完整的爬虫框架
- 🕷️ **类 Scrapy 的 Spider API**:使用 `start_urls` 定义爬虫,配合异步 `parse` 回调以及 `Request` / `Response` 对象。
- ⚡ **并发抓取**:可配置的并发限制、按域名限速以及下载延迟。
- 🔄 **多会话支持**:在单个爬虫中统一 HTTP 请求与隐身无头浏览器接口——按 ID 将请求路由到不同会话。
- 💾 **暂停与恢复**:基于检查点的爬虫持久化。按 Ctrl+C 优雅关闭;重新启动后从上次中断处继续。
- 📡 **流式模式**:通过 `async for item in spider.stream()` 实时流式传输抓取到的数据项,并提供实时统计信息——非常适合 UI、数据管道以及长时间运行的爬取任务。
- 🛡️ **请求被拦截检测**:自动检测并重试被拦截的请求,支持自定义逻辑。
- 🤖 **Robots.txt 合规**:可选的 `robots_txt_obey` 标志,遵守 `Disallow`、`Crawl-delay` 和 `Request-rate` 指令,并按域名缓存。
- 🧪 **开发模式**:首次运行时将响应缓存到磁盘,后续运行直接回放——在不重复访问目标服务器的情况下迭代你的 `parse()` 逻辑。
- 📦 **内置导出**:通过钩子函数和你自己的数据管道,或内置的 JSON/JSONL(分别对应 `result.items.to_json()` / `result.items.to_jsonl()`)导出结果。
### 高级网站抓取与会话支持
- **HTTP 请求**:使用 `Fetcher` 类实现快速且隐蔽的 HTTP 请求。可模拟浏览器 TLS 指纹、请求头,并使用 HTTP/3。
- **动态加载**:通过 `DynamicFetcher` 类以完整的浏览器自动化抓取动态网站,支持 Playwright 的 Chromium 和 Google 的 Chrome。
- **反爬绕过**:通过 `StealthyFetcher` 和指纹伪造实现高级隐身能力。可通过自动化轻松绕过各类 Cloudflare Turnstile/插页式验证。
- **会话管理**:通过 `FetcherSession`、`StealthySession` 和 `DynamicSession` 类实现持久化会话支持,用于跨请求的 Cookie 和状态管理。
- **代理轮换**:内置 `ProxyRotator`,支持循环或自定义轮换策略,适用于所有会话类型,并支持按请求覆盖代理。
- **域名与广告拦截**:拦截对特定域名(及其子域名)的请求,或在基于浏览器的抓取器中启用内置广告拦截(约 3,500 个已知广告/跟踪域名)。
- **DNS 泄露防护**:可选的 DNS-over-HTTPS 支持,通过 Cloudflare 的 DoH 路由 DNS 查询,防止使用代理时发生 DNS 泄露。
- **异步支持**:所有抓取器均支持完整的异步操作,并提供专用的异步会话类。
### 自适应抓取与 AI 集成
- 🔄 **智能元素追踪**:网站变更后,使用智能相似度算法重新定位元素。
- 🎯 **智能灵活选择**:CSS 选择器、XPath 选择器、基于过滤的搜索、文本搜索、正则表达式搜索等。
- 🔍 **查找相似元素**:自动定位与已找到元素相似的元素。
- 🤖 **用于 AI 的 MCP 服务器**:内置 MCP 服务器,用于 AI 辅助的网页抓取和数据提取。该 MCP 服务器具备强大的自定义能力,利用 Scrapling 在将目标内容传递给 AI(Claude/Cursor 等)之前进行提取,从而加速操作并通过减少 token 用量降低成本。([演示视频](https://www.youtube.com/watch?v=qyFk3ZNwOxE))))
### 高性能与久经考验的架构
- 🚀 **极速**:优化后的性能超越大多数 Python 抓取库。
- 🔋 **内存高效**:优化的数据结构和延迟加载,实现最小的内存占用。
- ⚡ **快速 JSON 序列化**:比标准库快 10 倍。
- 🏗️ **久经考验**:Scrapling 不仅拥有 92% 的测试覆盖率和完整的类型提示覆盖,在过去一年中更被数百位网页抓取工程师日常使用。
### 开发者/网页抓取工程师友好体验
- 🎯 **交互式网页抓取 Shell**:可选的内置 IPython Shell,集成 Scrapling、快捷操作和新工具,加速网页抓取脚本开发,例如将 curl 请求转换为 Scrapling 请求,以及在浏览器中查看请求结果。
- 🚀 **直接在终端中使用**:可选地,你可以使用 Scrapling 抓取 URL,而无需编写一行代码!
- 🛠️ **丰富的导航 API**:高级 DOM 遍历,支持父级、兄弟节点和子节点导航方法。
- 🧬 **增强文本处理**:内置正则表达式、清洗方法和优化的字符串操作。
- 📝 **自动选择器生成**:为任意元素生成鲁棒的 CSS/XPath 选择器。
- 🔌 **熟悉的 API**:与 Scrapy/BeautifulSoup 类似,使用与 Scrapy/Parsel 相同的伪元素。
- 📘 **完整的类型覆盖**:全面的类型提示,提供出色的 IDE 支持和代码补全。每次变更都会通过 **PyRight** 和 **MyPy** 自动扫描整个代码库。
- 🔋 **即用型 Docker 镜像**:每次发布都会自动构建并推送包含所有浏览器的 Docker 镜像。
## 快速入门
让我们快速了解一下 Scrapling 的功能,无需深入细节。
### 基础用法
带会话支持的 HTTP 请求
```python
from scrapling.fetchers import Fetcher, FetcherSession
with FetcherSession(impersonate='chrome') as session: # Use latest version of Chrome's TLS fingerprint
page = session.get('https://quotes.toscrape.com/', stealthy_headers=True)
quotes = page.css('.quote .text::text').getall()
# Or use one-off requests
page = Fetcher.get('https://quotes.toscrape.com/')
quotes = page.css('.quote .text::text').getall()
```
高级隐身模式
```python
from scrapling.fetchers import StealthyFetcher, StealthySession
with StealthySession(headless=True, solve_cloudflare=True) as session: # Keep the browser open until you finish
page = session.fetch('https://nopecha.com/demo/cloudflare', google_search=False)
data = page.css('#padded_content a').getall()
# Or use one-off request style, it opens the browser for this request, then closes it after finishing
page = StealthyFetcher.fetch('https://nopecha.com/demo/cloudflare')
data = page.css('#padded_content a').getall()
```
完整浏览器自动化
```python
from scrapling.fetchers import DynamicFetcher, DynamicSession
with DynamicSession(headless=True, disable_resources=False, network_idle=True) as session: # Keep the browser open until you finish
page = session.fetch('https://quotes.toscrape.com/', load_dom=False)
data = page.xpath('//span[@class="text"]/text()').getall() # XPath selector if you prefer it
# Or use one-off request style, it opens the browser for this request, then closes it after finishing
page = DynamicFetcher.fetch('https://quotes.toscrape.com/')
data = page.css('.quote .text::text').getall()
```
### Spiders(爬虫)
使用并发请求、多种会话类型和暂停/恢复功能构建完整的爬虫:
```python
from scrapling.spiders import Spider, Request, Response
class QuotesSpider(Spider):
name = "quotes"
start_urls = ["https://quotes.toscrape.com/"]
concurrent_requests = 10
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(),
}
next_page = response.css('.next a')
if next_page:
yield response.follow(next_page[0].attrib['href'])
result = QuotesSpider().start()
print(f"Scraped {len(result.items)} quotes")
result.items.to_json("quotes.json")
```
在单个爬虫中使用多种会话类型:
```python
from scrapling.spiders import Spider, Request, Response
from scrapling.fetchers import FetcherSession, AsyncStealthySession
class MultiSessionSpider(Spider):
name = "multi"
start_urls = ["https://example.com/"]
def configure_sessions(self, manager):
manager.add("fast", FetcherSession(impersonate="chrome"))
manager.add("stealth", AsyncStealthySession(headless=True), lazy=True)
async def parse(self, response: Response):
for link in response.css('a::attr(href)').getall():
# Route protected pages through the stealth session
if "protected" in link:
yield Request(link, sid="stealth")
else:
yield Request(link, sid="fast", callback=self.parse) # explicit callback
```
通过检查点暂停和恢复长时间运行的爬取任务,像这样运行爬虫:
```python
QuotesSpider(crawldir="./crawl_data").start()
```
按 Ctrl+C 优雅暂停——进度会自动保存。之后,当你再次启动爬虫时,传入相同的 `crawldir`,它就会从停止的地方恢复。
### 高级解析与导航
```python
from scrapling.fetchers import Fetcher
# Rich element selection and navigation
page = Fetcher.get('https://quotes.toscrape.com/')
# Get quotes with multiple selection methods
quotes = page.css('.quote') # CSS selector
quotes = page.xpath('//div[@class="quote"]') # XPath
quotes = page.find_all('div', {'class': 'quote'}) # BeautifulSoup-style
# Same as
quotes = page.find_all('div', class_='quote')
quotes = page.find_all(['div'], class_='quote')
quotes = page.find_all(class_='quote') # and so on...
# Find element by text content
quotes = page.find_by_text('quote', tag='div')
# Advanced navigation
quote_text = page.css('.quote')[0].css('.text::text').get()
quote_text = page.css('.quote').css('.text::text').getall() # Chained selectors
first_quote = page.css('.quote')[0]
author = first_quote.next_sibling.css('.author::text')
parent_container = first_quote.parent
# Element relationships and similarity
similar_elements = first_quote.find_similar()
below_elements = first_quote.below_elements()
```
如果你不想抓取网站,可以直接使用解析器,如下所示:
```python
from scrapling.parser import Selector
page = Selector("...")
```
效果完全一样!
### 异步会话管理示例
```python
import asyncio
from scrapling.fetchers import FetcherSession, AsyncStealthySession, AsyncDynamicSession
async with FetcherSession(http3=True) as session: # `FetcherSession` is context-aware and can work in both sync/async patterns
page1 = session.get('https://quotes.toscrape.com/')
page2 = session.get('https://quotes.toscrape.com/', impersonate='firefox135')
# Async session usage
async with AsyncStealthySession(max_pages=2) as session:
tasks = []
urls = ['https://example.com/page1', 'https://example.com/page2']
for url in urls:
task = session.fetch(url)
tasks.append(task)
print(session.get_pool_stats()) # Optional - The status of the browser tabs pool (busy/free/error)
results = await asyncio.gather(*tasks)
print(session.get_pool_stats())
```
## CLI 与交互式 Shell
Scrapling 包含一个强大的命令行界面:
[](https://asciinema.org/a/736339)
启动交互式 Web 抓取 Shell
```bash
scrapling shell
```
无需编程即可直接将页面提取到文件(默认提取 `body` 标签内的内容)。如果输出文件以 `.txt` 结尾,则提取目标的文本内容;如果以 `.md` 结尾,则输出 HTML 内容的 Markdown 表示形式;如果以 `.html` 结尾,则直接输出 HTML 内容本身。
```bash
scrapling extract get 'https://example.com' content.md
scrapling extract get 'https://example.com' content.txt --css-selector '#fromSkipToProducts' --impersonate 'chrome' # All elements matching the CSS selector '#fromSkipToProducts'
scrapling extract fetch 'https://example.com' content.md --css-selector '#fromSkipToProducts' --no-headless
scrapling extract stealthy-fetch 'https://nopecha.com/demo/cloudflare' captchas.html --css-selector '#padded_content a' --solve-cloudflare
```
> [!NOTE]
> 还有很多其他功能,但我们希望此页面保持简洁,包括 MCP 服务器和交互式 Web 抓取 Shell。请在此处查看完整文档:[here](https://scrapling.readthedocs.io/en/latest/)
## 性能基准测试
Scrapling 不仅功能强大,而且速度极快。以下基准测试将 Scrapling 的解析器与其他流行库的最新版本进行了对比。
### 文本提取速度测试(5000 个嵌套元素)
| # | 库名称 | 时间 (ms) | 与 Scrapling 对比 |
|---|:----------------:|:---------:|:----------------:|
| 1 | Scrapling | 1.98 | 1.0x |
| 2 | Parsel/Scrapy | 1.99 | 1.005x |
| 3 | Raw Lxml | 2.48 | 1.253x |
| 4 | PyQuery | 23.15 | ~12x |
| 5 | Selectolax | 196.09 | ~99x |
| 6 | MechanicalSoup | 1531.24 | ~773.4x |
| 7 | BS4 with Lxml | 1535.19 | ~775.3x |
| 8 | BS4 with html5lib | 3388.16 | ~1711.2x |
### 元素相似度与文本搜索性能
Scrapling 的自适应元素查找能力显著优于其他替代方案:
| 库 | 时间 (ms) | 与 Scrapling 对比 |
|-------------|:---------:|:----------------:|
| Scrapling | 2.29 | 1.0x |
| AutoScraper | 12.46 | 5.441x |
> 所有基准测试均为 100 次以上运行的平均值。测试方法详见 [benchmarks.py](https://github.com/D4Vinci/Scrapling/blob/main/benchmarks.py)。
## 安装
Scrapling 需要 Python 3.10 或更高版本:
```bash
pip install scrapling
```
> [!IMPORTANT]
> 此安装仅包含解析器引擎及其依赖项,不包含任何抓取器(fetchers)或命令行依赖项。因此,仅凭此安装,从 `scrapling.fetchers` 或 `scrapling.spiders` 导入任何内容(如上述示例所示)都会引发 `ModuleNotFoundError`。如果你要使用任何抓取器或爬虫,请先按照下方说明安装抓取器的依赖项。
### 可选依赖项
1. 如果你要使用以下任何额外功能、抓取器或其类,则需要安装抓取器的依赖项及其浏览器依赖项,具体如下:
```bash
pip install "scrapling[fetchers]"
scrapling install # 正常安装
scrapling install --force # 强制重新安装
```
这将下载所有浏览器及其系统依赖项和指纹操作依赖项。
或者你也可以通过代码安装,而不是运行命令:
```python
from scrapling.cli import install
install([], standalone_mode=False) # 正常安装
install(["--force"], standalone_mode=False) # 强制重新安装
```
2. 额外功能:
- 安装 MCP 服务器功能:
```bash
pip install "scrapling[ai]"
```
- 安装 Shell 功能(Web 抓取 Shell 和 `extract` 命令):
```bash
pip install "scrapling[shell]"
```
- 安装全部功能:
```bash
pip install "scrapling[all]"
```
请注意,在安装上述任意附加功能后,你还需要使用 `scrapling install` 安装浏览器依赖项(如果尚未安装)。
### Docker
你也可以通过 DockerHub 使用以下命令安装包含所有扩展和浏览器的 Docker 镜像:
```bash
docker pull pyd4vinci/scrapling
```
或者从 GitHub 容器镜像仓库下载:
```bash
docker pull ghcr.io/d4vinci/scrapling:latest
```
该镜像通过 GitHub Actions 自动构建并推送,基于仓库的主分支。
## 贡献
欢迎贡献!在开始之前,请阅读我们的[贡献指南](https://github.com/D4Vinci/Scrapling/blob/main/CONTRIBUTING.md)。
## 免责声明
> [!CAUTION]
> 本库仅用于教育和研究目的。使用本库即表示您同意遵守当地及国际的数据抓取与隐私法律。作者和贡献者不对任何滥用此软件的行为负责。请始终遵守网站的服務条款及 robots.txt 文件。
## 🎓 引用
如果您在研究中使用了本库,请按以下参考文献引用我们:
```text
@misc{scrapling,
author = {Karim Shoair},
title = {Scrapling},
year = {2024},
url = {https://github.com/D4Vinci/Scrapling},
note = {An adaptive Web Scraping framework that handles everything from a single request to a full-scale crawl!}
}
```
## 许可证
本项目基于 BSD-3-Clause 许可证授权。
## 致谢
本项目包含来自以下项目的改编代码:
- Parsel(BSD 许可证)——用于[翻译器](https://github.com/D4Vinci/Scrapling/blob/main/scrapling/core/translator.py) 子模块
---