关于 scrapling-mcp
scrapling-mcp 是网页抓取指导技能,帮助选择抓取策略和爬取模式;实际请求与内容提取由 Scrapling 的 MCP 服务通过 mcporter 执行。
主要功能
- 01抓取器选择指南
- 02反机器人升级策略
- 03自适应选择器指导
- 04Spider 爬取示例
- 05解析与提取参考
适用场景
- 01为网站选择抓取模式
- 02规划多页面内容提取
- 03应对页面布局变化
- 04选择被拦截时的策略
MCP 相关
该技能提供指导,不直接执行抓取;它将页面获取和 CSS 选择等执行任务交给通过 mcporter 调用的 Scrapling MCP 服务。
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ devbd1/ skills --skill scrapling-mcp安装后在 Claude Code 中输入/scrapling-mcp确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/anti-bot.mdapi_reference.mdlinks.mdmcp-setup.mdproxy-rotation.mdrecipes.mdspider-recipes.mdscripts/scrapling_scrape.pyscrapling_smoke_test.py详细介绍
Scrapling MCP — 网页抓取指南
源代码仓库:https://github.com/DevBD1/skills/tree/main/openclaw-skill-scrapling-mcp
指导层 + MCP 集成
使用此技能了解策略和模式。执行操作时,通过mcporter调用 Scrapling 的 MCP 服务。
快速入门(MCP)
1. 安装支持 MCP 的 Scrapling
pip install scrapling[mcp]
# Or for full features:
pip install scrapling[mcp,playwright]
python -m playwright install chromium
2. 添加到 OpenClaw MCP 配置
{
"mcpServers": {
"scrapling": {
"command": "python",
"args": ["-m", "scrapling.mcp"]
}
}
}
3. 通过 mcporter 调用
mcporter call scrapling fetch_page --url "https://example.com"
执行与指导
| 任务 | 工具 | 示例 |
|---|---|---|
| 获取页面 | mcporter | mcporter call scrapling fetch_page --url URL |
| 使用 CSS 提取 | mcporter | mcporter call scrapling css_select --selector ".title::text" |
| 应使用哪个抓取器? | 此技能 | 请参阅下文的“抓取器选择指南” |
| 如何制定反机器人策略? | 此技能 | 请参阅“反机器人升级阶梯” |
| 如何处理复杂的爬取模式? | 此技能 | 请参阅“Spider 示例” |
抓取器选择指南
┌─────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ Fetcher │────▶│ DynamicFetcher │────▶│ StealthyFetcher │
│ (HTTP) │ │ (Browser/JS) │ │ (Anti-bot) │
└─────────────────┘ └──────────────────┘ └──────────────────┘
Fastest JS-rendered Cloudflare,
Static pages SPAs, React/Vue Turnstile, etc.
决策树
- 静态 HTML? →
Fetcher(快 10-100 倍) - 需要执行 JS? →
DynamicFetcher - 遇到拦截? →
StealthyFetcher - 复杂会话? → 使用 Session 变体
MCP 抓取模式
fetch_page— HTTP 抓取器fetch_dynamic— 基于浏览器,使用 Playwrightfetch_stealthy— 反机器人绕过模式
反机器人升级阶梯
级别 1:礼貌的 HTTP 请求
# MCP call: fetch_page with options
{
"url": "https://example.com",
"headers": {"User-Agent": "..."},
"delay": 2.0
}
级别 2:会话持久化
# Use sessions for cookie/state across requests
FetcherSession(impersonate="chrome") # TLS fingerprint spoofing
级别 3:隐身模式
# MCP: fetch_stealthy
StealthyFetcher.fetch(
url,
headless=True,
solve_cloudflare=True, # Auto-solve Turnstile
network_idle=True
)
级别 4:代理轮换
请参阅 references/proxy-rotation.md
自适应抓取(抗脆弱)
Scrapling 可通过自适应选择器适应网站改版:
# First run — save fingerprints
products = page.css('.product', auto_save=True)
# Later runs — auto-relocate if DOM changed
products = page.css('.product', adaptive=True)
MCP 用法:
mcporter call scrapling css_select \\
--selector ".product" \\
--adaptive true \\
--auto-save true
Spider 框架(大规模爬取)
何时使用 Spiders,何时直接抓取:
- ✅ Spider:10 个以上页面、需要并发、支持断点续爬、代理轮换
- ✅ 直接抓取:1-5 个页面、快速提取、流程简单
基础 Spider 模式
from scrapling.spiders import Spider, Response
class ProductSpider(Spider):
name = "products"
start_urls = ["https://example.com/products"]
concurrent_requests = 10
download_delay = 1.0
async def parse(self, response: Response):
for product in response.css('.product'):
yield {
"name": product.css('h2::text').get(),
"price": product.css('.price::text').get(),
"url": response.url
}
# Follow pagination
next_page = response.css('.next a::attr(href)').get()
if next_page:
yield response.follow(next_page)
# Run with resume capability
result = ProductSpider(crawldir="./crawl_data").start()
result.items.to_jsonl("products.jsonl")
进阶:多会话 Spider
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():
if "/protected/" in link:
yield Request(link, sid="stealth")
else:
yield Request(link, sid="fast")
Spider 功能
- 暂停/恢复:
crawldir参数可保存检查点 - 流式处理:使用
async for item in spider.stream()进行实时处理 - 自动重试:请求被拦截时可配置重试
- 导出:内置
to_json()、to_jsonl()
CLI 和交互式 Shell
终端提取(无需编写代码)
# Extract to markdown
scrapling extract get 'https://example.com' content.md
# Extract specific element
scrapling extract get 'https://example.com' content.txt \\
--css-selector '.article' \\
--impersonate 'chrome'
# Stealth mode
scrapling extract stealthy-fetch 'https://protected.com' content.md \\
--no-headless \\
--solve-cloudflare
交互式 Shell
scrapling shell
# Inside shell:
>>> page = Fetcher.get('https://example.com')
>>> page.css('h1::text').get()
>>> page.find_all('div', class_='item')
解析器 API(超越 CSS/XPath)
BeautifulSoup 风格的方法
# Find by attributes
page.find_all('div', {'class': 'product', 'data-id': True})
page.find_all('div', class_='product', id=re.compile(r'item-\\d+'))
# Text search
page.find_by_text('Add to Cart', tag='button')
page.find_by_regex(r'\\$\\d+\\.\\d{2}')
# Navigation
first = page.css('.product')[0]
parent = first.parent
siblings = first.next_siblings
children = first.children
# Similarity
similar = first.find_similar() # Find visually/structurally similar elements
below = first.below_elements() # Elements below in DOM
自动生成的选择器
# Get robust selector for any element
element = page.css('.product')[0]
selector = element.auto_css_selector() # Returns stable CSS path
xpath = element.auto_xpath()
代理轮换
from scrapling.spiders import ProxyRotator
# Cyclic rotation
rotator = ProxyRotator([
"http://proxy1:8080",
"http://proxy2:8080",
"http://user:pass@proxy3:8080"
], strategy="cyclic")
# Use with any session
with FetcherSession(proxy=rotator.next()) as session:
page = session.get('https://example.com')
常见示例
分页模式
# Page numbers
for page_num in range(1, 11):
url = f"https://example.com/products?page={page_num}"
...
# Next button
while next_page := response.css('.next a::attr(href)').get():
yield response.follow(next_page)
# Infinite scroll (DynamicFetcher)
with DynamicSession() as session:
page = session.fetch(url)
page.scroll_to_bottom()
items = page.css('.item').getall()
登录会话
with StealthySession(headless=False) as session:
# Login
login_page = session.fetch('https://example.com/login')
login_page.fill('input[name="username"]', 'user')
login_page.fill('input[name="password"]', 'pass')
login_page.click('button[type="submit"]')
# Now session has cookies
protected_page = session.fetch('https://example.com/dashboard')
Next.js 数据提取
# Extract JSON from __NEXT_DATA__
import json
import re
next_data = json.loads(
re.search(
r'__NEXT_DATA__" type="application/json">(.*?)</script>',
page.html_content,
re.S
).group(1)
)
props = next_data['props']['pageProps']
输出格式
# JSON (pretty)
result.items.to_json('output.json')
# JSONL (streaming, one per line)
result.items.to_jsonl('output.jsonl')
# Python objects
for item in result.items:
print(item['title'])
性能提示
- 尽可能使用 HTTP 抓取器 — 比浏览器快 10-100 倍
- 模拟浏览器 — 使用
impersonate='chrome'进行 TLS 指纹伪装 - 支持 HTTP/3 —
FetcherSession(http3=True) - 限制资源 — 在 Dynamic/Stealthy 中设置
disable_resources=True - 连接池 — 在多个请求间重复使用会话
防护准则(始终遵守)
- 只抓取你获准访问的内容
- 遵守 robots.txt 和服务条款
- 大规模爬取时添加延迟(
download_delay) - 未经许可,不要绕过付费墙或身份验证
- 绝不抓取个人或敏感数据
参考资料
references/mcp-setup.md— MCP 配置详情references/anti-bot.md— 反机器人处理策略references/proxy-rotation.md— 代理设置与轮换references/spider-recipes.md— 进阶爬取模式references/api-reference.md— API 快速参考references/links.md— 官方文档链接
脚本
scripts/scrapling_scrape.py— 快速进行一次性提取scripts/scrapling_smoke_test.py— 测试连接和反机器人指标
评论
支持 Markdown