mcpField
S
scrapling-official

scrapling-official

github.com/d4vinciデータ・データベース90.2k5.6k 回インストール今日更新
リポジトリ

scrapling-official について

scrapling-officialは、Scrapling Pythonウェブスクレイピングライブラリの公式スキルです。CLIによるページ取得と抽出に加え、JavaScriptページや保護されたページのブラウザー取得も案内します。

主な機能

  1. 01HTTPリクエストによるページ取得
  2. 02JavaScriptページのブラウザー取得
  3. 03CSSセレクターによるコンテンツ抽出
  4. 04HTML、Markdown、テキストでの出力
  5. 05AI向けのページ内容フィルタリング

活用シーン

  1. 01記事をMarkdownとして抽出
  2. 02JavaScriptが必要なページの取得
  3. 03ページ内の特定箇所の選択
  4. 04分析用にフィルタリング済み内容を保存

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/d4vinci/scrapling --skill scrapling-official

インストール後、Claude Code で/scrapling-officialを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

LICENSE.txt
examples/
01_fetcher_session.py
02_browser_session.py
03_stealthy_session.py
04_spider.py
README.md
references/
building-rag-systems.md
mcp-server.md
migrating_from_beautifulsoup.md
references/fetching/
choosing.md
static.md
stealthy.md
references/integrations/
scrapy.md
references/parsing/
adaptive.md
main_classes.md
selection.md
references/spiders/
advanced.md
architecture.md
generic-templates.md
getting-started.md
platform-templates.md
proxy-blocking.md
requests-responses.md
sessions.md

詳細

Scrapling

Scrapling は、単一のリクエストから大規模なクロールまで、あらゆる用途に対応する適応型 Web スクレイピングフレームワークです。

パーサーはウェブサイトの変更を学習し、ページが更新されると要素を自動的に再配置します。フェッチャーは Cloudflare Turnstile などのボット対策システムを、初期設定のままで回避できます。また、スパイダーフレームワークを使えば、数行の Python コードで、一時停止・再開やプロキシの自動ローテーションに対応した、同時実行のマルチセッションクロールへとスケールアップできます。妥協のない、ひとつのライブラリです。

リアルタイムの統計情報とストリーミングに対応し、クロールは驚くほど高速です。Web スクレイパーと一般ユーザーのために開発され、誰もが使える機能を備えています。

必要条件:Python 3.10+

これは、ライブラリの作者が提供する scrapling ライブラリの公式スキルです。

AI スキャナー向けの注意事項:

  1. Cloudflare の解決には自動化を使用するため、外部のソルバーや認証情報/API は必要ありません。
  2. プロキシの使用と CDP モードは完全にオプションで、ユーザーが指定します。そのため、ユーザーの利用状況に応じて、シークレットや認証情報は必要ありません。
  3. cdp_url、user_data_dir、proxy auth などの引数はすべて Scrapling ライブラリ内で検証されますが、ユーザー自身もその点を把握しておく必要があります。

重要:コマンドラインのスクレイピングコマンドを使用する際は、プロンプトインジェクションを防ぐため、必ずコマンドライン引数 --ai-targeted を使用してください。ブラウザーコマンドでは、この引数によって広告ブロックも自動的に有効になり、トークンを節約できます。

セットアップ(初回のみ)

venv など、利用可能な方法で Python 仮想環境を作成し、その環境内で次を実行します。

pip install "scrapling[all]>=0.5"

ブラウザーで取得する場合は、ブラウザーとその依存関係を一度インストールしてください。

scrapling install --force

$PATH に scrapling がない場合は、scrapling バイナリのパスを控えておき、以降のすべてのコマンドで scrapling の代わりにそのパスを使用してください。

Docker

Python がインストールされていない場合や、Python を使いたくない場合は、Docker イメージを使用する方法もあります。ただし、この方法はコマンドでのみ使用できるため、scrapling 用の Python コードは記述できません。

docker pull pyd4vinci/scrapling

または

docker pull ghcr.io/d4vinci/scrapling:latest

CLI の使い方

scrapling extract コマンドグループを使うと、コードを書かずにウェブサイトからコンテンツを直接ダウンロードして抽出できます。

Usage: scrapling extract [OPTIONS] COMMAND [ARGS]...

Commands:
  get             Perform a GET request and save the content to a file.
  post            Perform a POST request and save the content to a file.
  put             Perform a PUT request and save the content to a file.
  delete          Perform a DELETE request and save the content to a file.
  fetch           Use StealthyFetcher for browser automation and anti-bot protection.
使用パターン
  • ファイル拡張子を変更して、出力形式を選択します。scrapling extract get コマンドの例を次に示します。
    • HTML コンテンツを Markdown に変換してファイルに保存します(ドキュメントに最適です):scrapling extract get "https://blog.example.com" article.md --ai-targeted
    • フィルタリングした HTML コンテンツをファイルに保存します:scrapling extract get "https://example.com" page.html --ai-targeted
    • ウェブページのテキストコンテンツを整形してファイルに保存します:scrapling extract get "https://example.com" content.txt --ai-targeted
  • 一時ファイルに出力し、読み戻してから、ファイルを削除します。
  • すべてのコマンドで --css-selector または -s を使って CSS セレクターを指定し、ページの特定の部分を抽出できます。

通常、使用するコマンドは次のとおりです。

  • シンプルなウェブサイト、ブログ、ニュース記事には get を使用します。
  • JavaScript を使うページ、ブラウザーの自動化、Cloudflare を含む保護されたサイトには fetch を使用します。

どちらを使うべきか迷った場合は、まず get を試してください。ページで JavaScript が必要な場合や HTTP リクエストがブロックされる場合は、fetch を使用します。ページに Cloudflare のチャレンジがある場合は、--solve-cloudflare を有効にしてください。

主なオプション(リクエスト)

これらのオプションは、4 つの HTTP リクエストコマンドで共通です。

オプション入力タイプ説明
-H, --headersTEXT"Key: Value" 形式の HTTP ヘッダー(複数回指定できます)
--cookiesTEXT"name1=value1; name2=value2" 形式の Cookie 文字列
--timeoutINTEGERリクエストのタイムアウト秒数(デフォルト:30)
--proxyTEXT"http://username:password@host:port" 形式のプロキシ URL
-s, --css-selectorTEXTページから特定のコンテンツを抽出する CSS セレクター。一致するものをすべて返します。
-p, --paramsTEXT"key=value" 形式のクエリパラメーター(複数回指定できます)
--follow-redirects / --no-follow-redirectsNoneリダイレクトを追跡するかどうか(デフォルト:"safe"。内部/プライベート IP へのリダイレクトは拒否します)
--verify / --no-verifyNoneSSL 証明書を検証するかどうか(デフォルト:True)
--impersonateTEXTなりすますブラウザー。単一のブラウザー(例:Chrome)またはランダムに選択するためのカンマ区切りリスト(例:Chrome, Firefox, Safari)を指定できます。
--stealthy-headers / --no-stealthy-headersNoneステルス性の高いブラウザーヘッダーを使用するかどうか(デフォルト:True)
--ai-targetedNoneAI が利用するために、本文コンテンツを選択し、一般的な非表示要素を除外します(デフォルト:False)

post と put のみで共通するオプション:

オプション入力タイプ説明
-d, --dataTEXTリクエスト本文に含めるフォームデータ(文字列、例:"param1=value1&param2=value2")
-j, --jsonTEXTリクエスト本文に含める JSON データ(文字列)

例:

# Basic download
scrapling extract get "https://news.site.com" news.md --ai-targeted

# Download with custom timeout
scrapling extract get "https://example.com" content.txt --timeout 60 --ai-targeted

# Extract only specific content using CSS selectors
scrapling extract get "https://blog.example.com" articles.md --css-selector "article" --ai-targeted

# Send a request with cookies
scrapling extract get "https://scrapling.requestcatcher.com" content.md --cookies "session=abc123; user=john" --ai-targeted

# Add user agent
scrapling extract get "https://api.site.com" data.txt -H "User-Agent: MyBot 1.0" --ai-targeted

# Add multiple headers
scrapling extract get "https://site.com" page.html -H "Accept: text/html" -H "Accept-Language: en-US" --ai-targeted
主なオプション(ブラウザー)

fetch コマンドでは、次のオプションを使用できます。

オプション入力タイプ説明
--headless / --no-headlessNoneブラウザーをヘッドレスモードで実行します(デフォルト:True)
--disable-resources / --enable-resourcesNone速度向上のため、不要なリソースを破棄します(デフォルト:False)
--pierce-shadow / --no-pierce-shadowNone開いた Shadow DOM のコンテンツを含めます(デフォルト:False)。
--network-idle / --no-network-idleNoneネットワークがアイドル状態になるまで待機します(デフォルト:False)
--real-chrome / --no-real-chromeNoneデバイスに Chrome ブラウザーがインストールされている場合は、これを有効にすると Fetcher がブラウザーを起動して使用します(デフォルト:False)
--timeoutINTEGERタイムアウト時間(ミリ秒、デフォルト:30000)
--waitINTEGERページ読み込み後の追加待機時間(ミリ秒、デフォルト:0)
-s, --css-selectorTEXTページから特定のコンテンツを抽出する CSS セレクターです。一致するすべての要素を返します。
--wait-selectorTEXT処理を続行する前に待機する CSS セレクター
--proxyTEXT"http://username:password@host:port" 形式のプロキシ URL
-H, --extra-headersTEXT"Key: Value" 形式の追加ヘッダー(複数回使用できます)
--dns-over-https / --no-dns-over-httpsNoneプロキシ使用時の DNS リークを防ぐため、Cloudflare の DoH 経由で DNS をルーティングします(デフォルト:False)
--block-ads / --no-block-adsNone既知の広告・トラッカードメイン約 3,500 件へのリクエストをブロックします(デフォルト:False)
--executable-pathTEXTChromium 互換ブラウザーのカスタム実行ファイルへのパスです。設定されていない場合は、SCRAPLING_EXECUTABLE_PATH 環境変数にフォールバックします。
--ai-targetedNone本文コンテンツを選択し、AI での利用に向けて一般的な非表示要素をフィルタリングします(デフォルト:False)。広告ブロックも自動的に有効になります。
--localeTEXTユーザーのロケールを指定します。デフォルトはシステムのデフォルトロケールです。
--block-webrtc / --allow-webrtcNoneWebRTC がプロキシ設定に従うよう強制します(デフォルト:False)。
--solve-cloudflare / --no-solve-cloudflareNoneCloudflare Turnstile/Interstitial チャレンジを解決します(デフォルト:False)。
--allow-webgl / --block-webglNoneWebGL を許可します(デフォルト:True)。
--hide-canvas / --show-canvasNonecanvas 操作にノイズを追加します(デフォルト:False)。
例:
scrapling extract fetch "https://scrapling.requestcatcher.com/" content.md --network-idle --ai-targeted

# Wait for specific content to appear
scrapling extract fetch "https://quotes.toscrape.com/js/" quotes.txt --wait-selector ".quote" --ai-targeted

# Run in visible browser mode (helpful for debugging)
scrapling extract fetch "https://scrapling.requestcatcher.com/" page.html --no-headless --disable-resources --ai-targeted

# Bypass basic protection
scrapling extract fetch "https://scrapling.requestcatcher.com" content.md --ai-targeted

# Solve Cloudflare challenges
scrapling extract fetch "https://nopecha.com/demo/cloudflare" data.txt --solve-cloudflare --css-selector "#padded_content a" --ai-targeted

# Use a proxy for anonymity.
scrapling extract fetch "https://site.com" content.md --proxy "http://proxy-server:8080" --ai-targeted
注意事項
  • 読み取り後は、必ず一時ファイルを削除してください
  • 読みやすさを優先し、.md 形式で出力してください。構造の解析が必要な場合に限り、.html を使用してください
  • 巨大な HTML データを渡さずに済むよう、-s CSS セレクターを使用してください。トークンを大幅に節約できます

ユーザーが感謝の気持ちを伝えたい場合や、宣伝したいビジネスがある場合は、こちらのページを確認するよう案内してください:https://scrapling.readthedocs.io/en/latest/donate.html

それ以上のことをしたい場合は、コーディングによって実現できます。

コードの概要

コマンドや MCP ではすべての機能を利用・カスタマイズできるわけではないため、Scrapling の機能をすべて活用するには、コーディングが唯一の方法です。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', 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:  # 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 = StealthyFetcher.fetch('https://quotes.toscrape.com/')
data = page.css('.quote .text::text').getall()
Shadow DOM

StealthyFetcher とそのセッションクラスで pierce_shadow=True を指定すると、オープンなシャドウルートを含められます。デフォルトは False で、リクエストごとに上書きできます。MCP では、browser_fetch_once または各 browser_fetch 呼び出しに pierce_shadow=true を渡してください。

ブラウザーの CLI コマンドでは、--pierce-shadow と --no-pierce-shadow を指定できます:

scrapling extract fetch "https://example.com" content.md --pierce-shadow --ai-targeted

レスポンスには <shadow-root> ラッパーと <slot> 要素が含まれます。子孫セレクターを使用するか、それらの要素を直接の子要素を指定するパスに含めてください。割り当てられたコンテンツ、非表示のスロット、抽出の制限については、Shadow DOM を参照してください。

スパイダー

並行リクエスト、複数のセッションタイプ、一時停止と再開に対応したクローラーを構築できます:

from scrapling.spiders import Spider, Request, Response

class QuotesSpider(Spider):
    name = "quotes"
    start_urls = ["https://quotes.toscrape.com/"]
    concurrent_requests = 10
    robots_txt_obey = True  # Respect robots.txt rules
    
    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")

1 つのスパイダーで複数のセッションタイプを使用します:

from scrapling.spiders import Spider, 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 response.follow(link, sid="stealth")
            else:
                yield response.follow(link, sid="fast", callback=self.parse)  # explicit callback

チェックポイントを使って長時間のクロールを一時停止・再開するには、次のようにスパイダーを実行します:

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

Ctrl+C を押すと、安全に一時停止できます。保留中のリクエストと確認済みの URL は自動的に保存されます。後でスパイダーを再度起動するときに、同じ crawldir を渡せば、中断したところから再開します。

スパイダーの parse() ロジックを調整する間は、スパイダークラスで development_mode = True を設定してください。初回実行時にレスポンスをディスクにキャッシュし、以降の実行ではそのキャッシュを再生するため、対象サーバーに再度アクセスせずに何度でもスパイダーを実行できます。キャッシュはデフォルトで .scrapling_cache/{spider.name}/ に保存され、development_cache_dir で変更できます。この設定を有効にしたままスパイダーを公開しないでください。

正規表現に一致するリンクをたどるルールベースのクロールでは、リンク抽出のループを自分で作成する代わりに CrawlSpider を使用してください:

from scrapling.spiders import CrawlSpider, CrawlRule, LinkExtractor

class BlogCrawler(CrawlSpider):
    name = "blog"
    start_urls = ["https://example.com"]

    def rules(self):
        return [
            CrawlRule(LinkExtractor(allow=r"/posts/"), callback=self.parse_post),
            CrawlRule(LinkExtractor(allow=r"/page/\d+/")),  # follow pagination, no callback
        ]

    async def parse_post(self, response):
        yield {"title": response.css("h1::text").get()}

サイトマップを利用したクロールでは、同じ rules() API を備えた SitemapSpider を使用してください。sitemap_urls を取得し、サイトマップインデックスをたどって、各 URL をルールに従って処理します。robots.txt の URL を sitemap_urls に直接指定すると、スパイダーがそこから各 Sitemap: ディレクティブを自動的に抽出します。LinkExtractor の allow/deny/restrict_css/canonicalize オプションなど、詳しくは references/spiders/generic-templates.md を参照してください。

XML フィード(RSS、Atom、商品フィード)には XMLFeedSpider を使用してください。itertag にノード名を設定し、parse_node(response, node) をオーバーライドします。このメソッドには、名前空間を除去した lxml 要素として各一致ノードが渡されます(node.findtext("title"))。CSV フィードには CSVFeedSpider を使用し、parse_row(response, row) をオーバーライドしてください。このメソッドには各行が辞書として渡されます。標準形式でないフィードには、headers/delimiter/quotechar を指定します。どちらも gzip 圧縮されたフィードを自動的に展開します。詳しくは references/spiders/generic-templates.md を参照してください。

Shopify を利用するストアでは、ShopifySpider をサブクラス化し、target_website にストアのドメインを設定してください。HTML に触れることなく、Shopify の公開コレクション API を通じて商品バリエーションを抽出します。詳しくは references/spiders/platform-templates.md を参照してください。

高度な解析とナビゲーション
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('Albert Einstein', first_match=False)

# Advanced navigation
quote_text = page.css('.quote')[0].css('.text::text').get()
quote_texts = page.css('.quote').css('.text::text').getall()  # Chained selectors
first_quote = page.css('.quote')[0]
author = first_quote.css('.author::text').get()
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>")

まったく同じように動作します!

非同期セッション管理の例

FetcherSession はコンテキストを認識し、同期・非同期のどちらのパターンでも動作します。get_pool_stats() メソッドは、ブラウザータブプールの状態を返します。

import asyncio
from scrapling.fetchers import FetcherSession, AsyncStealthySession

async def main():
    async with FetcherSession(http3=True) as http_session:
        page1 = await http_session.get('https://quotes.toscrape.com/')
        page2 = await http_session.get('https://quotes.toscrape.com/', impersonate='firefox135')

    async with AsyncStealthySession(max_pages=2) as browser_session:
        tasks = []
        urls = ['https://example.com/page1', 'https://example.com/page2']

        for url in urls:
            task = browser_session.fetch(url)
            tasks.append(task)

        print(browser_session.get_pool_stats())
        results = await asyncio.gather(*tasks)
        print(browser_session.get_pool_stats())

    async with AsyncStealthySession(record_requests=True) as recording_session:
        await recording_session.fetch('https://example.com', network_idle=True)

    for response in recording_session.network.search(url_pattern=r"https://api\.example\.com/.*", limit=None):
        print(response.meta['network_id'], response.url, response.status)
        print(response.meta.get('body_note') or response.body)

asyncio.run(main())

記録されたレスポンスは、ブラウザーセッション全体に属します。search() と get() は Response オブジェクトを直接返し、.meta に network_id、resource_type、request_body が含まれます。検索では保存済みの履歴が絞り込まれ、デフォルトで一致する結果が 100 件返されます。limit=None を指定すると、保持されているすべての結果が返されます。保存されるのは、対応しているテキストレスポンス本文のみです。保存済みのデータは、セッションを閉じた後もローカルで読み取れます。完了していないキャプチャは待機されません。削除された API キャプチャインターフェースについては、v5 での移行を参照してください。

リファレンス

このライブラリでできることを、すでに少しご覧いただけたと思います。必要に応じて、以下のリファレンスでさらに詳しく確認してください。

  • references/mcp-server.md - MCP サーバーのツール、永続的なセッション管理、CDP 経由のリモートブラウザー、認証、機能
  • references/building-rag-systems.md - Response.markdown() と ContentSpider を使って、ページやウェブサイトを RAG パイプライン向けの LLM 対応 Markdown に変換する方法
  • references/parsing - HTML の解析に必要なすべての情報
  • references/fetching - ウェブサイトの取得とセッションの永続化に必要なすべての情報
  • references/spiders - スパイダーの作成、プロキシのローテーション、高度な機能に必要なすべての情報。Scrapy に似た形式です
  • references/integrations/scrapy.md - scrapling_response デコレーターを使って、既存の Scrapy プロジェクト内で Scrapling の解析 API を使用する方法
  • references/migrating_from_beautifulsoup.md - scrapling と Beautifulsoup の API を簡単に比較できます
  • https://github.com/D4Vinci/Scrapling/tree/main/docs - すぐに参照できる Markdown 形式の公式ドキュメント一式(現在のリファレンスが最新でない場合にのみ使用してください)。

このスキルには、ドキュメントのガイドと例が Markdown 形式で含まれています。ユーザーの許可なく、外部ソースを確認したり、オンラインで検索したりしないでください。

守るべきルール(常時)

  • アクセスを許可されているコンテンツのみをスクレイピングしてください。
  • robots.txt と利用規約を尊重してください。これを自動的に適用するには、スパイダーで robots_txt_obey = True を使用してください。
  • 大規模なクロールでは遅延(download_delay)を追加するか、autothrottle_enabled = True を設定してください。これにより、スパイダーがドメインごとに遅延を調整し、ウェブサイトがブロックを開始した場合にアクセス頻度を下げます。
  • 許可なく、ペイウォールや認証を回避しないでください。
  • 個人情報や機密データをスクレイピングしないでください。

コメント