Note
本文档由 WeHub 基于上游 README 翻译整理,属于社区翻译,非官方中文文档。
English · 原始项目 · 上游 README
原作者、版权与许可证归属以原始项目及本仓库 LICENSE 文件为准。
العربيه | Español | Português (Brasil) | Français | Deutsch | 简体中文 | 日本語 | Русский | 한국어
选择方法 · Fetchers · Spiders · 代理轮换 · CLI · MCP
Scrapling 是一款自适应 Web Scraping(网页爬取)框架,可处理从单次请求到大规模爬取的一切场景。
其解析器会学习网站变化,并在页面更新时自动重新定位你的元素。其 Fetcher 可开箱即用地绕过 Cloudflare Turnstile 等反机器人系统。其 Spider 框架让你只需几行 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!
或扩展到完整爬取
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()
|
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% 折扣。 |
您想在此展示广告?点击此处)
您想在此展示广告?点击此处)选择适合您的赞助等级!
start_urls 定义爬虫,配合异步 parse 回调以及 Request / Response 对象。async for item in spider.stream() 实时流式传输抓取到的数据项,并提供实时统计信息——非常适合 UI、数据管道以及长时间运行的爬取任务。robots_txt_obey 标志,遵守 Disallow、Crawl-delay 和 Request-rate 指令,并按域名缓存。parse() 逻辑。result.items.to_json() / result.items.to_jsonl())导出结果。Fetcher 类实现快速且隐蔽的 HTTP 请求。可模拟浏览器 TLS 指纹、请求头,并使用 HTTP/3。DynamicFetcher 类以完整的浏览器自动化抓取动态网站,支持 Playwright 的 Chromium 和 Google 的 Chrome。StealthyFetcher 和指纹伪造实现高级隐身能力。可通过自动化轻松绕过各类 Cloudflare Turnstile/插页式验证。FetcherSession、StealthySession 和 DynamicSession 类实现持久化会话支持,用于跨请求的 Cookie 和状态管理。ProxyRotator,支持循环或自定义轮换策略,适用于所有会话类型,并支持按请求覆盖代理。让我们快速了解一下 Scrapling 的功能,无需深入细节。
带会话支持的 HTTP 请求
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()
高级隐身模式
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()
完整浏览器自动化
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()
使用并发请求、多种会话类型和暂停/恢复功能构建完整的爬虫:
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")
在单个爬虫中使用多种会话类型:
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
通过检查点暂停和恢复长时间运行的爬取任务,像这样运行爬虫:
QuotesSpider(crawldir="./crawl_data").start()
按 Ctrl+C 优雅暂停——进度会自动保存。之后,当你再次启动爬虫时,传入相同的 crawldir,它就会从停止的地方恢复。
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()
如果你不想抓取网站,可以直接使用解析器,如下所示:
from scrapling.parser import Selector
page = Selector("<html>...</html>")
效果完全一样!
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())
Scrapling 包含一个强大的命令行界面:
启动交互式 Web 抓取 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' # 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
Scrapling 不仅功能强大,而且速度极快。以下基准测试将 Scrapling 的解析器与其他流行库的最新版本进行了对比。
| # | 库名称 | 时间 (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。
Scrapling 需要 Python 3.10 或更高版本:
pip install scrapling
Important
此安装仅包含解析器引擎及其依赖项,不包含任何抓取器(fetchers)或命令行依赖项。因此,仅凭此安装,从
scrapling.fetchers或scrapling.spiders导入任何内容(如上述示例所示)都会引发ModuleNotFoundError。如果你要使用任何抓取器或爬虫,请先按照下方说明安装抓取器的依赖项。
如果你要使用以下任何额外功能、抓取器或其类,则需要安装抓取器的依赖项及其浏览器依赖项,具体如下:
pip install "scrapling[fetchers]"
scrapling install # 正常安装
scrapling install --force # 强制重新安装
这将下载所有浏览器及其系统依赖项和指纹操作依赖项。
或者你也可以通过代码安装,而不是运行命令:
from scrapling.cli import install
install([], standalone_mode=False) # 正常安装
install(["--force"], standalone_mode=False) # 强制重新安装
额外功能:
pip install "scrapling[ai]"
extract 命令):
pip install "scrapling[shell]"
pip install "scrapling[all]"
请注意,在安装上述任意附加功能后,你还需要使用 scrapling install 安装浏览器依赖项(如果尚未安装)。
你也可以通过 DockerHub 使用以下命令安装包含所有扩展和浏览器的 Docker 镜像:
docker pull pyd4vinci/scrapling
或者从 GitHub 容器镜像仓库下载:
docker pull ghcr.io/d4vinci/scrapling:latest
该镜像通过 GitHub Actions 自动构建并推送,基于仓库的主分支。
欢迎贡献!在开始之前,请阅读我们的贡献指南。
Caution
本库仅用于教育和研究目的。使用本库即表示您同意遵守当地及国际的数据抓取与隐私法律。作者和贡献者不对任何滥用此软件的行为负责。请始终遵守网站的服務条款及 robots.txt 文件。
如果您在研究中使用了本库,请按以下参考文献引用我们:
@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 许可证授权。
本项目包含来自以下项目的改编代码: