资讯动态

Scrapling 自适应 Web 爬虫框架:从单请求到大规模爬取的完整技术指南

发布时间:2026/9/5 23:17:00 来源:尧图企业网站定制
Scrapling 自适应 Web 爬虫框架从单请求到大规模爬取的完整技术指南【免费下载链接】Scrapling️ An adaptive Web Scraping framework that handles everything from a single request to a full-scale crawl!项目地址: https://gitcode.com/GitHub_Trending/sc/Scrapling本文基于 Scrapling 仓库中的官方 README西班牙语版 docs/README_ES.md撰写系统讲解这套“自适应 Web 抓取框架”的三大核心——自适应解析器Parser、多引擎抓取器Fetchers与并发爬虫框架Spiders并结合仓库源码逐一印证其特性、安装方式、命令行工具与性能基准。读完后你将能够独立完成安装配置、选择合适 Fetcher 发起请求、编写支持断点续爬的 Spider以及使用 CLI 零代码提取页面内容。Scrapling 官方定位是“一个自适应的 Web 抓取框架能够处理从单个请求到大规模爬取的一切An adaptive Web Scraping framework that handles everything from a single request to a full-scale crawl”。其两大核心卖点在 README 开篇即有明确表述解析器会“学习”网站变化当页面结构更新后能够自动重新定位relocate你之前保存的元素Fetcher 原生具备反爬规避能力可以直接处理 Cloudflare Turnstile/Interstitial 等反机器人系统Spider 框架支持并发、多会话、Pause Resume 与自动 Proxy 轮换全部只用少量 Python 代码完成。仓库中一段最精炼的入门代码即展示了“抓取 自适应解析”的主线用法继承自 READMEfrom scrapling.fetchers import Fetcher, AsyncFetcher, StealthyFetcher, DynamicFetcher StealthyFetcher.adaptive True p StealthyFetcher.fetch(https://example.com, headlessTrue, network_idleTrue) # 低姿态抓取网页 products p.css(.product, auto_saveTrue) # 提取能“存活”于站点改版的数据 products p.css(.product, adaptiveTrue) # 站点结构变化后传 adaptiveTrue 即可重新找到元素核心特性总览READMEdocs/README_ES.md将特性划分为五大板块Spiders 爬虫框架、高级 Fetch 能力含 Session、自适应抓取与 AI 集成、高性能架构、以及开发者体验。下面逐一展开并给出仓库中的实现位置作为佐证。Spiders完整的 Scrapy 风格爬取框架官方特性列表包括以下条目均出自 README路径已转换为仓库相对路径以便查证Scrapy 风格 API用start_urls、异步parse回调、Request/Response对象定义 Spider实现位于 scrapling/spiders/spider.py并发爬取可配置并发上限、按域限速与下载延迟对应 scrapling/spiders/throttle.py多会话Multi-Session在同一个 Spider 中统一使用 HTTP 请求与隐身浏览器会话按会话 ID 路由请求到不同 SessionPause Resume基于 Checkpoint 的爬取持久化按CtrlC可优雅停机再次启动时从上次进度继续。源码中Spider.__init__接受crawldir参数注释明确写着 “Directory for checkpoint files. If provided, enables pause/resume”见 scrapling/spiders/spider.py#L106-L138流式模式Streaming通过async for item in spider.stream()在元素产生时即时消费并附带实时统计适合 UI、管道与长时爬取被拦截请求检测自动检测被拦截的请求并重试重试逻辑可自定义AutoThrottleSpider 根据站点响应速度自动调整每个域的延迟被限流/拦截时自动加倍延迟或遵循Retry-After响应头恢复后再加速robots.txt 合规可选robots_txt_obey标志尊重Disallow、Crawl-delay、Request-rate指令并按域缓存实现见 scrapling/spiders/robotstxt.py开发模式首次运行时把响应落盘后续运行直接回放让你反复调试parse()逻辑而不必反复访问目标服务器即用型 Spider 模板CrawlSpider按规则追链、SitemapSpidersitemap/robots 引导式爬取、XMLFeedSpider/CSVFeedSpider迭代 XML/RSS 与 CSV 源、ShopifySpider通过 Shopify JSON API 按变体粒度导出全部商品。这些模板分别实现在 scrapling/spiders/templates/crawler.py、scrapling/spiders/templates/sitemap.py、scrapling/spiders/templates/feed.py 与 scrapling/spiders/templates/shopify.py并从 scrapling/spiders/init.py 统一导出链接提取原语独立的LinkExtractor支持 allow/deny 模式、域名过滤、CSS/XPath 边界、扩展名过滤与规范化实现见 scrapling/spiders/links.py结果导出除自带 hook/管道外还提供内置导出方法。源码 scrapling/spiders/result.py 中可以看到ItemsResult的四个导出方法签名to_json(path, *, indentFalse)、to_jsonl(path)、to_csv(path, *, fieldsNone, delimiter,)、to_xml(path, *, root_tagitems, item_tagitem, indentTrue)。高级 Fetch 能力与 Session 体系README 列出的高级抓取能力包括HTTP 请求Fetcher提供快速的 HTTP 请求可模仿浏览器 TLS 指纹、自定义请求头并支持 HTTP/3动态加载DynamicFetcher基于 Playwright 的 Chromium/Chrome 提供完整浏览器自动化反爬规避StealthyFetcher具备更深入的隐身能力与指纹伪造可自动处理各类 Cloudflare Turnstile/Interstitial 质询。在 scrapling/fetchers/stealth_chrome.py 的参数文档中可以看到network_idle表示“等待页面直到至少 500 ms 没有网络活动”solve_cloudflare表示“在返回响应前解决所有类型的 Cloudflare Turnstile/Interstitial 质询”google_search默认启用会设置 Google 来源 Referer会话管理FetcherSession、StealthySession、DynamicSession三类持久会话类用于跨请求维持 Cookie 与状态Proxy 轮换内置ProxyRotator支持顺序cyclic或自定义轮换策略可用于所有会话类型并支持按请求覆盖 Proxy实现见 scrapling/engines/toolbelt/proxy_rotation.py域名/广告拦截可拦截特定域名含子域的请求或启用内置广告拦截约 3500 个已知广告/追踪域名见 scrapling/engines/toolbelt/ad_domains.pyDNS 泄漏防护可选 DNS-over-HTTPS将 DNS 查询经 Cloudflare DoH 路由避免使用代理时发生 DNS 泄漏远程浏览器通过cdp_url用 CDP 连接已在运行的浏览器本机、远程主机或托管浏览器服务也可用executable_path让任意浏览器 Fetcher 指向你自己的 Chromium 构建后台 API 捕获给capture_xhr传入 URL 模式页面加载期间所有匹配的 XHR/fetch 响应会被收集为Response对象存入response.captured_xhr——无需逆向工程即可拿到站点 API 数据完整 Async 支持所有 fetcher 均有对应的 async 类与会话类。从源码结构看scrapling/fetchers/init.py 采用了惰性导入_LAZY_IMPORTS映射 模块级__getattr__Fetcher/AsyncFetcher/FetcherSession来自scrapling.fetchers.requestsDynamicFetcher/DynamicSession/AsyncDynamicSession来自scrapling.fetchers.chromeStealthyFetcher/StealthySession/AsyncStealthySession来自scrapling.fetchers.stealth_chrome。这也解释了为什么只装基础包时导入scrapling.fetchers里的任何类会抛出ModuleNotFoundError——底层依赖如curl_cffi、Playwright属于可选依赖组。自适应抓取与 AI 集成智能元素追踪基于相似度算法在网站改版后重新定位元素。解析器入口 scrapling/parser.py 中Selector的构造参数包含adaptive: Optional[bool] False文档注释说明该参数是“全局关闭自适应功能”的总开关且优先级高于所有 adaptive 相关方法/参数——即adaptive 能力默认关闭需要显式开启灵活的选择方式CSS 选择器、XPath、基于过滤器的查找、文本查找、正则查找等详见 docs/parsing/selection.md相似元素查找自动定位与已找到元素相似的其他元素find_similar()MCP 服务器内置 Model Context Protocol 服务器用于 AI 辅助的 Web 抓取与数据提取它先利用 Scrapling 提取目标内容再交给 AIClaude/Cursor 等以减少 token 消耗还支持跨调用保持浏览器会话、页面截图与 CDP 远程浏览器控制说明文档见 docs/ai/mcp-server.mdAgent Skill仓库内提供开箱即用的 agent-skill 目录含SKILL.md与完整的参考文档教编程 Agent 使用与当前 API 一致的 Scrapling 写法避免“靠猜”生成代码。高性能架构与开发体验README 的性能主张均以仓库官方表述为准解析速度超过大多数 Python Web 抓取库、内存占用优化惰性加载、JSON 序列化比标准库快约 10 倍、测试覆盖率 92% 且具备完整类型提示每次变更用 PyRight 与 MyPy 扫描全量源码。开发者体验方面的特性包括可选的 IPython 交互 Shell含 curl 转 Scrapling 请求、在浏览器中查看请求结果等快捷工具、直接通过终端命令抓取 URL 而无需写代码、丰富的 DOM 导航 API父/兄弟/子元素、内置 regex 与字符串清洗方法、CSS/XPath 选择器自动生成、与 Scrapy/BeautifulSoup 相似且兼容 Scrapy/Parsel 伪元素::text、::attr()等的 API以及与 Scrapy 的直接集成——用scrapling_response装饰器即可把 Scrapy 回调里已有的响应交给 Scrapling 解析器集成代码见 scrapling/integrations/scrapy.py。快速上手基础用法三种 Fetcher 对应会话以下示例完整继承自 READMEdocs/README_ES.md 的“Primeros Pasos”一节。HTTP 请求带会话支持——Fetcher可模仿 Chrome 最新 TLS 指纹from scrapling.fetchers import Fetcher, FetcherSession with FetcherSession(impersonatechrome) as session: # 使用最新版 Chrome TLS 指纹 page session.get(https://quotes.toscrape.com/, stealthy_headersTrue) quotes page.css(.quote .text::text).getall() # 或者使用一次性请求 page Fetcher.get(https://quotes.toscrape.com/) quotes page.css(.quote .text::text).getall()高级隐身模式——solve_cloudflareTrue会在返回前自动通过 Cloudflare 质询StealthySession会保持浏览器打开直到你结束所有请求from scrapling.fetchers import StealthyFetcher, StealthySession with StealthySession(headlessTrue, solve_cloudflareTrue) as session: page session.fetch(https://nopecha.com/demo/cloudflare, google_searchFalse) data page.css(#padded_content a).getall() # 或者用一次性请求风格为此请求打开浏览器完成后自动关闭 page StealthyFetcher.fetch(https://nopecha.com/demo/cloudflare) data page.css(#padded_content a).getall()完整浏览器自动化——DynamicFetcher走标准 Playwright 路线也支持 XPathfrom scrapling.fetchers import DynamicFetcher, DynamicSession with DynamicSession(headlessTrue, disable_resourcesFalse, network_idleTrue) as session: page session.fetch(https://quotes.toscrape.com/, load_domFalse) data page.xpath(//span[classtext]/text()).getall() # 如果你喜欢 XPath # 或者一次性请求风格 page DynamicFetcher.fetch(https://quotes.toscrape.com/) data page.css(.quote .text::text).getall()三者如何取舍仓库有专门文档给出速度、隐身性、反爬选项、JS 加载能力、内存占用等维度的对比表见 docs/fetching/choosing.md。简言之纯 HTTP 就能搞定的场景用Fetcher动态加载、小自动化与中小防护用DynamicFetcher更复杂的防护与 Cloudflare 质询用StealthyFetcher。按请求或全局配置解析器所有 Fetcher 共享同一套解析器配置接口来自 docs/fetching/choosing.md。先于请求调用configure或直接设置类属性from scrapling.fetchers import Fetcher Fetcher.configure(adaptiveTrue, keep_commentsFalse, keep_cdataFalse) # 其余参数同 # 或者 Fetcher.adaptive True Fetcher.keep_comments False Fetcher.keep_cdata False可用配置参数为adaptive、adaptive_domain、huge_tree、keep_comments、keep_cdata、storage、storage_args——与 Selector 类 的构造参数一致。任意时刻可用fetcher_class.display_config()打印当前配置。如前所述adaptive参数在 scrapling/parser.py#L89 中默认为False必须显式开启。Spiders并发爬取、多会话与断点续爬基础并发爬虫完整继承自 READMEfrom 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(fSe extrajeron {len(result.items)} citas) # 打印提取条数 result.items.to_json(quotes.json)单个 Spider 内混用多种会话类型——受保护页面走隐身会话其余走快速 HTTP 会话sid即会话路由 IDfrom 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(impersonatechrome)) manager.add(stealth, AsyncStealthySession(headlessTrue), lazyTrue) async def parse(self, response: Response): for link in response.css(a::attr(href)).getall(): # 受保护页面路由到隐身会话 if protected in link: yield Request(link, sidstealth) else: yield Request(link, sidfast, callbackself.parse) # 显式 callbackPause Resume给 Spider 传入crawldir即启用 Checkpoint 持久化QuotesSpider(crawldir./crawl_data).start()按CtrlC会优雅暂停并自动保存进度再次启动同一crawldir时从断点继续。这与源码中crawldir“If provided, enables pause/resume” 的注释scrapling/spiders/spider.py#L106一致。直接用模板——例如抓取任意 Shopify 商店全部商品每变体一条from scrapling.spiders import ShopifySpider class MyStore(ShopifySpider): target_website example.com result MyStore().start() # 商店全部商品一个变体一个条目高级解析与 DOM 导航不抓取网页时也可直接使用解析器from scrapling.parser import Selector; page Selector(html.../html)用法与 Fetcher 返回的页面完全一致。README 给出的完整解析示例from scrapling.fetchers import Fetcher page Fetcher.get(https://quotes.toscrape.com/) # 多种选择方式 quotes page.css(.quote) # CSS 选择器 quotes page.xpath(//div[classquote]) # XPath quotes 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, tagdiv) # 高级导航 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()Async 会话管理示例FetcherSession同时兼容 sync/async 上下文AsyncStealthySession支持多标签页池并发可用get_pool_stats()查看标签页池状态占用/空闲/错误import asyncio from scrapling.fetchers import FetcherSession, AsyncStealthySession, AsyncDynamicSession async with FetcherSession(http3True) as session: # 上下文感知sync/async 模式均可用 page1 session.get(https://quotes.toscrape.com/) page2 session.get(https://quotes.toscrape.com/, impersonatefirefox135) # 使用 async 会话 async with AsyncStealthySession(max_pages2) 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())CLI 与交互式 ShellScrapling 自带命令行界面命令注册见 scrapling/cli.pyinstall、shell、extract、mcp四个子命令文档见 docs/cli/overview.md。启动 Web 抓取交互式 Shellscrapling shell不写任何代码直接提取页面到文件默认提取body内容输出格式由扩展名决定——.txt输出纯文本.md输出 Markdown 表示.html输出 HTML 本体scrapling extract get https://example.com content.md scrapling extract get https://example.com content.txt --css-selector #fromSkipToProducts --impersonate chrome 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性能基准README 引用了仓库官方基准数据见 docs/benchmarks.md方法学脚本为 benchmarks.py均为 100 次以上运行的平均值。文本提取速度5000 个嵌套元素#库耗时 (ms)相对 Scrapling1Scrapling1.991.0x2Parsel/Scrapy2.061.0353Raw Lxml2.561.2864PyQuery23.98~12x5Selectolax197.02~99x6MechanicalSoup1545.15~776.5x7BS4 Lxml1562.1~785.0x8BS4 html5lib3412.73~1714.9x自适应元素查找 / 文本搜索库耗时 (ms)相对 ScraplingScrapling2.31.0xAutoScraper12.585.47x注意以上为仓库官方文档公布的对比数据复现时以 benchmarks.py 中的方法学为准实际表现会随运行环境、库版本变化。安装与部署Scrapling 要求Python 3.10 或更高版本pyproject.toml 中requires-python 3.10。1. 基础安装仅解析引擎pip install scrapling重要基础安装只包含解析引擎及其依赖不含任何 Fetcher 与命令行依赖。此时从scrapling.fetchers或scrapling.spiders导入任何内容都会抛出ModuleNotFoundError。如需使用 Fetcher 或 Spider必须先安装 fetchers 依赖组。2. 安装 Fetchers 与浏览器依赖pip install scrapling[fetchers] scrapling install # 常规安装 scrapling install --force # 强制重装这会在本地下载所有浏览器及其系统依赖与指纹处理依赖。也可以从代码中安装from scrapling.cli import install install([], standalone_modeFalse) # 常规安装 install([--force], standalone_modeFalse) # 强制重装从 scrapling/cli.py#L120-L142 的install实现可以看到它实际执行了三件事python -m playwright install chromium、python -m playwright install-deps chromium以及更新 tld 域名数据完成后写入.scrapling_dependencies_installed标记文件——标记已存在且未加--force时直接提示 “The dependencies are already installed”。3. 可选依赖组对应 pyproject.toml#L72-L96 中的optional-dependencies定义pip install scrapling[ai] # MCP 服务器功能 pip install scrapling[shell] # Web 抓取 Shell 与 extract 命令 pip install scrapling[all] # 全部功能其中[fetchers]依赖组包含click、curl_cffi、playwright、patchright、browserforge、apify-fingerprint-datapoints、msgspec、anyio、protego[ai]额外需要mcp与markdownify并自动带入[fetchers][shell]依赖IPython8.37最后一个支持 Python 3.10 的版本线、markdownify与[fetchers]。无论装哪个 extra只要用到浏览器 Fetcher都别忘了再执行一次scrapling install。4. Docker 方式每个 release 会自动构建并推送包含全部 extras 与浏览器的镜像docker pull pyd4vinci/scrapling # 或从 GitHub 容器注册表 docker pull ghcr.io/d4vinci/scrapling:latest使用须知与延伸阅读合规声明继承自 README 的免责声明本库仅供教育与研究用途使用者需遵守当地及国际上的数据抓取与隐私法律并始终尊重目标网站的服务条款与 robots.txt 文件贡献提交代码前请先阅读 CONTRIBUTING.md许可BSD-3-Clause见 LICENSE致谢项目包含改编自 ParselBSD 许可的代码用于 scrapling/core/translator.py 子模块完整的主题文档在仓库内均有对应页面选择方法、如何选择 Fetcher、Spider 架构、代理轮换与封锁、CLI 总览、MCP 服务器、自适应存储系统。总结来说Scrapling 的架构思路是“一个库、三种抽象”Selector负责会“自愈”的解析Fetcher/DynamicFetcher/StealthyFetcher及其 Session 变体负责从纯 HTTP 到反爬规避的抓取Spider框架负责把前两者放大为可断点续爬、可流式消费、可多会话路由的并发爬取任务。理解这三层及它们之间Response对象的衔接就掌握了使用整套框架的关键。【免费下载链接】Scrapling️ An adaptive Web Scraping framework that handles everything from a single request to a full-scale crawl!项目地址: https://gitcode.com/GitHub_Trending/sc/Scrapling创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价