- 🕷️ 类 Scrapy 的 Spider API:使用
start_urls、asyncparsecallback 和Request/Response对象定义 Spider。 - ⚡ 并发爬取:可配置的并发限制、按域名节流和下载延迟。
- 🔄 多 Session 支持:统一接口,支持 HTTP 请求和隐秘无头浏览器在同一个 Spider 中使用–通过 ID 将请求路由到不同的 Session。
- 💾 暂停与恢复:基于 Checkpoint 的爬取持久化。按 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通过 JSON API 抓取任意 Shopify 商店的全部商品,每个变体一条数据。 - 🔗 链接提取:独立的
LinkExtractor组件,支持 allow/deny 模式、域名过滤、CSS/XPath 范围限定、扩展名过滤和链接规范化–可在模板中使用,也可单独使用。 - 📦 内置导出:通过钩子和您自己的管道导出结果,或使用内置的 JSON/JSONL/CSV/XML 导出器:
result.items.to_json()、to_jsonl()、to_csv()和to_xml()。
- HTTP 请求:使用
Fetcher类进行快速和隐秘的 HTTP 请求。可以模拟浏览器的 TLS fingerprint、标头并使用 HTTP/3。 - 动态加载:通过
DynamicFetcher类使用完整的浏览器自动化获取动态网站,支持 Playwright 的 Chromium 和 Google Chrome。 - 反机器人绕过:使用
StealthyFetcher的高级隐秘功能和 fingerprint 伪装。可以轻松自动绕过所有类型的 Cloudflare Turnstile/Interstitial。 - Session 管理:使用
FetcherSession、StealthySession和DynamicSession类实现持久化 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 捕获:向
capture_xhr传入 URL 模式,页面加载过程中所有匹配的 XHR/fetch 响应都会作为Response对象收集到response.captured_xhr中–无需自己逆向分析请求即可获取网站的 API 数据。 - Async 支持:所有 Fetcher 和专用 async Session 类的完整 async 支持。
- 🔄 智能元素跟踪:使用智能相似性算法在网站更改后重新定位元素。
- 🎯 智能灵活选择:CSS 选择器、XPath 选择器、基于过滤器的搜索、文本搜索、正则表达式搜索等。
- 🔍 查找相似元素:自动定位与已找到元素相似的元素。
- 🤖 MCP 服务器:让 AI 聊天机器人和智能体(Claude/Cursor 等)通过 Scrapling 抓取网页,提供一次性工具和基于会话的工具,覆盖普通 HTTP 请求(任意方法)、浏览器抓取以及可绕过 Cloudflare 的隐身抓取。页面在交给 AI 之前会先用 CSS 选择器缩小范围并清除提示注入内容,因此智能体读得更少、花得更少,也不会被隐藏文本劫持。还包含页面截图、通过 CDP 控制远程浏览器,以及默认安全的 HTTP 传输。(演示视频)
- 🧠 Agent Skill:开箱即用的 Agent Skill,让编码智能体全面掌握本库,使它们用 Scrapling 写出的代码符合当前 API,而不是靠猜测。
- 📚 RAG 就绪的 Markdown:用一行代码(
page.markdown())把任意页面转换为干净、经过净化、可直接供 LLM 使用的 Markdown,或使用SiteToMarkdownSpider模板把整个网站抓取为 Markdown 语料库,整个过程无需调用 LLM。(文档)
- 🚀 闪电般快速:优化性能超越大多数 Python 抓取库。
- 🔋 内存高效:优化的数据结构和延迟加载,最小内存占用。
- ⚡ 快速 JSON 序列化:比标准库快 10 倍。
- 🏗️ 经过实战测试:Scrapling 不仅拥有 92% 的测试覆盖率和完整的类型提示覆盖率,而且在过去一年中每天被数百名 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 镜像会自动构建和推送。
让我们快速展示 Scrapling 的功能,无需深入了解。
支持 Session 的 HTTP 请求
from scrapling.fetchers import Fetcher, FetcherSession
with FetcherSession(impersonate='chrome') as session: # 使用 Chrome 的最新版本 TLS fingerprint
page = session.get('https://quotes.toscrape.com/', stealthy_headers=True)
quotes = page.css('.quote .text::text').getall()
# 或使用一次性请求
page = Fetcher.get('https://quotes.toscrape.com/')
quotes = page.css('.quote .text::text').getall()
高级隐秘模式
from scrapling.fetchers import StealthyFetcher, StealthySession
with StealthySession(headless=True, solve_cloudflare=True) as session: # 保持浏览器打开直到完成
page = session.fetch('https://nopecha.com/demo/cloudflare', google_search=False)
data = page.css('#padded_content a').getall()
# 或使用一次性请求样式,为此请求打开浏览器,完成后关闭
page = StealthyFetcher.fetch('https://nopecha.com/demo/cloudflare')
data = page.css('#padded_content a').getall()
完整的浏览器自动化
from scrapling.fetchers import DynamicFetcher, DynamicSession
with DynamicSession(headless=True, disable_resources=False, network_idle=True) as session: # 保持浏览器打开直到完成
page = session.fetch('https://quotes.toscrape.com/', load_dom=False)
data = page.xpath('//span[@class="text"]/text()').getall() # 如果您偏好 XPath 选择器
# 或使用一次性请求样式,为此请求打开浏览器,完成后关闭
page = DynamicFetcher.fetch('https://quotes.toscrape.com/')
data = page.css('.quote .text::text').getall()
构建具有并发请求、多种 Session 类型和暂停/恢复功能的完整爬虫:
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"抓取了 {len(result.items)} 条引用")
result.items.to_json("quotes.json")
在单个 Spider 中使用多种 Session 类型:
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():
# 将受保护的页面路由到隐秘 Session
if "protected" in link:
yield Request(link, sid="stealth")
else:
yield Request(link, sid="fast", callback=self.parse) # 显式 callback
通过如下方式运行 Spider 来暂停和恢复长时间爬取,使用 Checkpoint:
QuotesSpider(crawldir="./crawl_data").start()
按 Ctrl+C 优雅暂停–进度会自动保存。之后,当您再次启动 Spider 时,传递相同的 crawldir,它将从上次停止的地方继续。
或者使用现成的模板,完全跳过爬取逻辑的编写,例如抓取整个 Shopify 商店的商品目录:
from scrapling.spiders import ShopifySpider
class MyStore(ShopifySpider):
target_website = "example.com"
result = MyStore().start() # 商店中的每件商品,每个变体一条数据
from scrapling.fetchers import Fetcher# 丰富的元素选择和导航page = Fetcher.get('https://quotes.toscrape.com/')# 使用多种选择方法获取引用quotes = page.css('.quote') # CSS 选择器quotes = page.xpath('//div[@class="quote"]') # XPathquotes = page.find_all('div', {'class': 'quote'}) # BeautifulSoup 风格# 等同于quotes = page.find_all('div', class_='quote')quotes = page.find_all(['div'], class_='quote')quotes = page.find_all(class_='quote') # 等等...# 按文本内容查找元素quotes = page.find_by_text('quote', tag='div')# 高级导航quote_text = page.css('.quote')[0].css('.text::text').get()quote_text = page.css('.quote').css('.text::text').getall() # 链式选择器first_quote = page.css('.quote')[0]author = first_quote.next_sibling.css('.author::text')parent_container = first_quote.parent# 元素关系和相似性similar_elements = first_quote.find_similar()below_elements = first_quote.below_elements()如果您不想获取网站,可以直接使用解析器,如下所示:
from scrapling.parser import Selector
page = Selector("<html>...</html>")
用法完全相同!
import asynciofrom scrapling.fetchers import FetcherSession, AsyncStealthySession, AsyncDynamicSessionasync with FetcherSession(http3=True) as session: # `FetcherSession`是上下文感知的,可以在 sync/async 模式下工作 page1 = session.get('https://quotes.toscrape.com/') page2 = session.get('https://quotes.toscrape.com/', impersonate='firefox135')# Async Session 用法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()) # 可选 - 浏览器标签池的状态(忙/空闲/错误) results = await asyncio.gather(*tasks) print(session.get_pool_stats())Scrapling 包含强大的命令行界面:
启动交互式 Web Scraping Shell
scrapling shell
直接将页面提取到文件而无需编程(默认提取 body 标签内的内容)。如果输出文件以.txt 结尾,则将提取目标的文本内容。如果以.md 结尾,它将是 HTML 内容的 Markdown 表示;如果以.html 结尾,它将是 HTML 内容本身。
scrapling extract get 'https://example.com' content.md
scrapling extract get 'https://example.com' content.txt --css-selector '#fromSkipToProducts' --impersonate 'chrome' # 所有匹配 CSS 选择器'#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 Scraping Shell。查看完整文档 这里
Scrapling 不仅功能强大–它还速度极快。以下基准测试将 Scrapling 的解析器与其他流行库的最新版本进行了比较。
| # | 库 | 时间 (ms) | vs Scrapling |
|---|---|---|---|
| 1 | Scrapling | 1.99 | 1.0x |
| 2 | Parsel/Scrapy | 2.06 | 1.035 |
| 3 | Raw 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 |
Scrapling 的自适应元素查找功能明显优于替代方案:
| 库 | 时间 (ms) | vs Scrapling |
|---|---|---|
| Scrapling | 2.3 | 1.0x |
| AutoScraper | 12.58 | 5.47x |
所有基准测试代表 100+ 次运行的平均值。请参阅 benchmarks.py 了解方法。
Scrapling 需要 Python 3.10 或更高版本:
pip install scrapling
Important
此安装仅包括解析器引擎及其依赖项,没有任何 Fetcher 或命令行依赖项。 因此,仅使用此安装时,像上面的示例那样从 scrapling.fetchers 或 scrapling.spiders 导入任何内容都会引发 ModuleNotFoundError。如果要使用任何 Fetcher 或 Spider,请先按照下面的说明安装 Fetcher 的依赖项。
如果您要使用以下任何额外功能、Fetcher 或它们的类,您将需要安装 Fetcher 的依赖项和它们的浏览器依赖项,如下所示:
pip install "scrapling[fetchers]" scrapling install # normal install scrapling install --force # force reinstall
这会下载所有浏览器,以及它们的系统依赖项和 fingerprint 操作依赖项。
或者你可以从代码中安装,而不是运行命令:
from scrapling.cli import install install([], standalone_mode=False) # normal install install(["--force"], standalone_mode=False) # force reinstall
-
额外功能:
- 安装 MCP 服务器功能:
pip install "scrapling[ai]" - 安装(构建 RAG 系统)所需的依赖:
pip install "scrapling[rag]" - 安装 Shell 功能(Web Scraping Shell 和
extract命令):pip install "scrapling[shell]" - 安装所有内容:
pip install "scrapling[all]"
请记住,在安装任何这些额外功能后(如果您还没有安装),您需要使用
scrapling install安装浏览器依赖项 - 安装 MCP 服务器功能:
您还可以使用以下命令从 DockerHub 安装包含所有额外功能和浏览器的 Docker 镜像:
docker pull pyd4vinci/scrapling
或从 GitHub 注册表下载:
docker pull ghcr.io/d4vinci/scrapling:latest
此镜像使用 GitHub Actions 和仓库主分支自动构建和推送。
原创文章,作者:云东方,如若转载,请注明出处:https://www.yundongfang.com/Yun1203.html