AI Pulse

比 BS4 快 785 倍,Scrapling 从抓取到爬取装进一个库

比 BS4 快 785 倍,Scrapling 从抓取到爬取装进一个库

Scrapling 是什么

Scrapling 是一个 Python Web 抓取框架,把快速 HTTP 请求、隐身浏览器、强大的解析和并发爬取整合进一个库。

你可以用它抓取静态页面、渲染 JavaScript、与网站交互,并从网站背后的 API 调用中提取数据。构建爬虫时,它提供可复用会话、代理轮换、自动重试、暂停/恢复和内置数据导出。

你可以从 Python、终端,或通过 MCP 服务器和 Agent Skill 从 AI agent 中使用它。从提取几个字段到把整个网站收集成干净的 Markdown,Scrapling 覆盖完整抓取工作流。

能做什么

先看两个例子

从单个页面开始

from scrapling.fetchers import Fetcher

page = Fetcher.get('https://quotes.toscrape.com/')
quotes = page.css('.quote .text::text').getall()
print(quotes)

用 spider 扩大规模

from scrapling.spiders import Spider, Response

class QuotesSpider(Spider):
    name = "quotes"
    start_urls = ["https://quotes.toscrape.com/"]

    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(),
            }

result = QuotesSpider().start()
print(len(result.items))
result.items.to_json("quotes.json")

这段代码会打印 10,并把引言和作者保存到 quotes.json。

核心功能

Spiders:完整的爬取框架

支持会话的高级网站抓取

解析与数据提取

AI 功能

高性能与经受过实战检验的架构

对开发者和爬虫友好的体验

快速上手

下面快速展示 Scrapling 能做什么,不深入细节。

基础用法:带会话支持的 HTTP 请求

from scrapling.fetchers import Fetcher, FetcherSession

with FetcherSession(impersonate='chrome') as session:  # 使用最新版 Chrome 的 TLS 指纹
    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', solve_cloudflare=True)
data = page.css('#padded_content a').getall()

完整浏览器自动化

from scrapling.fetchers import StealthyFetcher, StealthySession

with StealthySession(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 = StealthyFetcher.fetch('https://quotes.toscrape.com/')
data = page.css('.quote .text::text').getall()

爬虫:并发、多会话与暂停/恢复

用并发请求、多种会话类型和暂停/恢复构建完整爬虫:

from scrapling.spiders import Spider, 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")

在单个 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", callback=self.parse)  # 显式 callback

用检查点暂停和恢复长时间爬取,可以这样运行 spider:

QuotesSpider(crawldir="./crawl_data").start()

设置 crawldir 后,按 Ctrl+C 保存待处理请求和已见 URL。用同一 crawldir 重启即可恢复。抓取到的 item 要单独保存。

或者干脆不写爬取逻辑,用现成模板,比如拉取整个 Shopify 商店目录:

from scrapling.spiders import ShopifySpider

class MyStore(ShopifySpider):
    target_website = "example.com"

result = MyStore().start()  # 商店中的每个产品,每个变体一条 item

该模板通过公开的 collection 端点读取产品,每个变体一条 item。

高级解析与导航

from scrapling.fetchers import Fetcher

# 富元素选择和导航
page = Fetcher.get('https://quotes.toscrape.com/')

# 用多种选择方法获取引言
quotes = page.css('.quote')  # CSS 选择器
quotes = page.xpath('//div[@class="quote"]')  # 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('Albert Einstein', first_match=False)

# 高级导航
quote_text = page.css('.quote')[0].css('.text::text').get()
quote_texts = page.css('.quote').css('.text::text').getall()  # 链式选择器
first_quote = page.css('.quote')[0]
author = first_quote.css('.author::text').get()
next_quote = first_quote.next
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 asyncio
from scrapling.fetchers import FetcherSession, AsyncStealthySession

async def main():
    async with FetcherSession(http3=True) as http_session:  # `FetcherSession` 是上下文感知的,可用于同步/异步模式
        page1 = await http_session.get('https://quotes.toscrape.com/')
        page2 = await http_session.get('https://quotes.toscrape.com/page/2/', impersonate='chrome')
        print(len(page1.css('.quote')), len(page2.css('.quote')))

    async with AsyncStealthySession(max_pages=2) as browser_session:
        urls = ['https://quotes.toscrape.com/js/', 'https://quotes.toscrape.com/js/page/2/']
        pages = await asyncio.gather(*(browser_session.fetch(url, wait_selector='.quote') for url in urls))
        print([len(page.css('.quote')) for page in pages])

asyncio.run(main())

CLI 与交互式 Shell

Scrapling 包含强大的命令行接口。

启动交互式 Web 抓取 shell:

pip install "scrapling[shell]"
scrapling shell

不用编程就能把页面直接提取到文件。用 --css-selector 选择内容,或用 --ai-targeted 选择并清理正文内容。文件扩展名用 .txt 表示文本,.md 表示 Markdown,.html 表示 HTML。

scrapling extract get 'https://quotes.toscrape.com/' quotes.md
scrapling extract get 'https://quotes.toscrape.com/' quotes.txt --css-selector '.quote' --impersonate 'chrome'
scrapling extract fetch 'https://quotes.toscrape.com/js/' quotes.md --css-selector '.quote' --wait-selector '.quote' --no-headless
scrapling extract fetch 'https://nopecha.com/demo/cloudflare' captchas.html --css-selector '#padded_content a' --solve-cloudflare

注意:还有更多功能,但本页保持简洁,包括 MCP 服务器和交互式 Web 抓取 Shell。完整文档请查看项目文档。

性能基准

Scrapling 不仅强大,也很快。下面的基准测试把 Scrapling 的解析器与其他流行库的最新版本进行比较。

文本提取速度测试(5000 个嵌套元素):

#库时间 (ms)相对 Scrapling
1Scrapling1.991.0x
2Parsel/Scrapy2.061.035
3Raw Lxml2.561.286
4PyQuery23.98~12x
5Selectolax197.02~99x
6MechanicalSoup1545.15~776.5x
7BS4 with Lxml1562.1~785.0x
8BS4 with html5lib3412.73~1714.9x

元素相似性与文本搜索性能:

Scrapling 的自适应元素查找能力显著优于替代方案:

库时间 (ms)相对 Scrapling
Scrapling2.31.0x
AutoScraper12.585.47x

所有基准测试都是 100+ 次运行的平均值。方法说明见 benchmarks.py。

安装

Scrapling 要求 Python 3.10 或更高版本:

pip install scrapling

注意:这个安装只包含解析器引擎及其依赖,不包含任何抓取器或命令行依赖。因此只这样安装后,导入 scrapling.fetchers 或 scrapling.spiders(如上面示例所示)会抛出 ModuleNotFoundError。如果要使用任何抓取器或 spider,先按下面说明安装抓取器依赖。

可选依赖

如果要使用下面的额外功能、抓取器或其类,需要安装抓取器依赖和浏览器依赖:

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]"
pip install "scrapling[rag]"
pip install "scrapling[shell]"
pip install "scrapling[all]"

需要浏览器抓取器时运行 scrapling install。HTTP 请求不需要安装浏览器。

Docker

也可以从 DockerHub 拉取包含所有额外功能和浏览器的 Docker 镜像:

docker pull pyd4vinci/scrapling

或从 GitHub registry 下载:

docker pull ghcr.io/d4vinci/scrapling:latest

该镜像通过 GitHub Actions 使用仓库的主分支自动构建并推送。

贡献

欢迎贡献。开始前请阅读贡献指南。

免责声明

注意:本库仅用于教育和研究目的。使用本库即表示你同意遵守当地和国际的数据抓取及隐私法律。作者和贡献者不对本软件的任何滥用负责。始终尊重网站的服务条款和 robots.txt 文件。

阅读原文
📚 相关主题 开源Python

订阅 AI Pulse

每天 08:00 · 12:30 · 18:30 · 23:50 更新