MCP HubMCP Hub
스킬 목록으로 돌아가기

headless-web-scraping

pjt222
업데이트됨 2 days ago
6 조회
17
2
17
GitHub에서 보기
디자인apiautomationdesigndata

정보

이 스킬은 scrapling 라이브러리의 3단계 페처 시스템을 활용하여 JavaScript 렌더링 및 봇 방어 사이트에 대한 강력한 웹 스크래핑을 제공합니다. 사이트 방어 수준에 따라 기본 HTTP부터 스텔스 크로뮴 또는 전체 브라우저 자동화에 이르기까지 적절한 방법을 자동 선택하며 헤드리스 브라우징을 구성합니다. 개발자는 WebFetch가 실패하고 복잡한 페이지에서 CSS 선택자와 DOM 탐색을 통한 구조화된 데이터 추출이 필요할 때 이 스킬을 사용해야 합니다.

빠른 설치

Claude Code

추천
기본
npx skills add pjt222/agent-almanac -a claude-code
플러그인 명령대체
/plugin add https://github.com/pjt222/agent-almanac
Git 클론대체
git clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/headless-web-scraping

Claude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요

문서

Headless Web Scraping

Extract from resistant pages (JS-rendered, Cloudflare, dynamic SPAs) via scrapling 3-tier fetcher + CSS extraction.

Use When

  • JS rendering (SPA, React, Vue)
  • Anti-bot (Cloudflare Turnstile, TLS fingerprint)
  • Structured multi-element via CSS
  • WebFetch / requests.get() empty or blocked
  • Tabular/list/repeated DOM at scale

In

  • Required: URL(s)
  • Required: data to extract (CSS selectors, field names, target desc)
  • Optional: fetcher tier override (default: auto)
  • Optional: out format (default JSON; CSV, dict)
  • Optional: rate limit sec (default 1)

Do

Step 1: Select tier

# Decision matrix:
# 1. Fetcher        — static HTML, no JS, no anti-bot (fastest)
# 2. StealthyFetcher — Cloudflare/Turnstile, TLS fingerprint checks
# 3. DynamicFetcher  — JS-rendered SPAs, click/scroll interactions

# Quick probe: try Fetcher first, escalate on failure
from scrapling import Fetcher

fetcher = Fetcher()
response = fetcher.get("https://example.com/target-page")

if response.status == 200 and response.get_all_text():
    print("Fetcher tier sufficient")
else:
    print("Escalate to StealthyFetcher or DynamicFetcher")
SignalRecommended Tier
Static HTML, no protectionFetcher
403/503, Cloudflare challenge pageStealthyFetcher
Page loads but content area is emptyDynamicFetcher
Need to click buttons or scrollDynamicFetcher
altcha CAPTCHA presentNone (cannot be automated)

→ 1 of 3 tiers. Modern sites → StealthyFetcher usual start.

If err: all 3 blocked → check altcha CAPTCHA (PoW, cannot bypass). Document limitation + manual extraction.

Step 2: Configure

from scrapling import Fetcher, StealthyFetcher, DynamicFetcher

# Tier 1: Fast HTTP with TLS fingerprint impersonation
fetcher = Fetcher()
fetcher.configure(
    timeout=30,
    retries=3,
    follow_redirects=True
)

# Tier 2: Headless Chromium with anti-detection
fetcher = StealthyFetcher()
fetcher.configure(
    headless=True,
    timeout=60,
    network_idle=True  # wait for all network requests to settle
)

# Tier 3: Full browser automation
fetcher = DynamicFetcher()
fetcher.configure(
    headless=True,
    timeout=90,
    network_idle=True,
    wait_selector="div.results"  # wait for specific element before extracting
)

→ Fetcher configured + ready. No err on init. Stealth/Dynamic → Chromium auto-managed first run.

If err:

  • playwright / browser binary missing → python -m playwright install chromium
  • configure() timeout → increase timeout or check network
  • Import err → pip install scrapling

Step 3: Fetch + extract

# Fetch the page
response = fetcher.get("https://example.com/target-page")

# Single element extraction
title = response.find("h1.page-title")
if title:
    print(title.get_all_text())

# Multiple elements
items = response.find_all("div.result-item")
for item in items:
    name = item.find("span.name")
    price = item.find("span.price")
    print(f"{name.get_all_text()}: {price.get_all_text()}")

# Get attribute values
links = response.find_all("a.product-link")
urls = [link.get("href") for link in links]

# Get raw HTML content of an element
detail_html = response.find("div.description").html_content

API ref:

MethodPurpose
response.find("selector")First matching element
response.find_all("selector")All matching elements
element.get("attr")Attribute value (href, src, data-*)
element.get_all_text()All text content, recursively
element.html_contentRaw inner HTML

→ Extracted data matches visible content. Non-None elements, non-empty text on populated pages.

If err:

  • find()None → inspect response.html_content for actual HTML; selectors may differ
  • Empty get_all_text() → shadow DOM / iframe → DynamicFetcher w/ wait_selector
  • NO .css_first() → not scrapling API (other lib confusion)

Step 4: Handle failures + edge cases

import time

def scrape_with_fallback(url, selector):
    """Try each fetcher tier in order, with CAPTCHA detection."""
    tiers = [
        ("Fetcher", Fetcher),
        ("StealthyFetcher", StealthyFetcher),
        ("DynamicFetcher", DynamicFetcher),
    ]

    for tier_name, tier_class in tiers:
        fetcher = tier_class()
        fetcher.configure(headless=True, timeout=60)

        try:
            response = fetcher.get(url)
        except Exception as error:
            print(f"{tier_name} failed: {error}")
            continue

        # Detect CAPTCHA / challenge pages
        page_text = response.get_all_text().lower()
        if "altcha" in page_text or "proof of work" in page_text:
            print(f"altcha CAPTCHA detected -- cannot automate")
            return None

        if response.status == 403 or response.status == 503:
            print(f"{tier_name} blocked (HTTP {response.status}), escalating")
            continue

        result = response.find(selector)
        if result and result.get_all_text().strip():
            return result.get_all_text()

        print(f"{tier_name} returned empty content, escalating")

    print("All tiers exhausted. Manual extraction required.")
    return None

→ Returns text on success, None + diagnostic on fail. CAPTCHA detected + reported not retried.

If err:

  • All 403 → site blocks all automation (WIPO, TMview, gov DBs). Document as manual access.
  • Timeout → slow CDN → increase to 120s.
  • Session/cookie errs → login required → add cookie handling / auth.

Step 5: Rate limit + ethical

import time
import urllib.robotparser

def check_robots_txt(base_url, target_path):
    """Check if scraping is allowed by robots.txt."""
    rp = urllib.robotparser.RobotFileParser()
    rp.set_url(f"{base_url}/robots.txt")
    rp.read()
    return rp.can_fetch("*", f"{base_url}{target_path}")

def scrape_urls(urls, selector, delay=1.0):
    """Scrape multiple URLs with rate limiting."""
    results = []
    fetcher = StealthyFetcher()
    fetcher.configure(headless=True, timeout=60)

    for url in urls:
        response = fetcher.get(url)
        data = response.find(selector)
        if data:
            results.append(data.get_all_text())

        time.sleep(delay)  # respect the server

    return results

Ethical checklist:

  1. robots.txt first → respect Disallow
  2. Min 1-sec delay
  3. Descriptive User-Agent
  4. No personal data w/o legal basis
  5. Cache locally → avoid redundant reqs
  6. 429 → stop immediately

→ Controlled rate. robots.txt checked pre-bulk. No 429.

If err:

  • 429 → increase delay 3-5 sec, or stop + retry later
  • robots.txt disallow → respect, do not override
  • IP ban → stop immediately. If legit access (public, ToS-permit, robots-respect) must continue → see rotate-scraping-proxies for network-layer escalation

Check

  • Correct tier (not over/under)
  • configure() used (not deprecated constructor kwargs)
  • Selectors match actual structure (verified vs source)
  • .find() / .find_all() used (not .css_first())
  • CAPTCHA detection (altcha reported, not retried)
  • Rate limit for multi-URL
  • robots.txt checked pre-bulk
  • Extracted data non-empty + correct

Traps

  • .css_first() instead .find(): scrapling uses .find()/.find_all(). .css_first() = diff lib → AttributeError.
  • Start w/ DynamicFetcher: try Fetcher first. Dynamic 10-50× slower (full browser startup).
  • Constructor kwargs: scrapling v0.4.x deprecated → always configure().
  • Ignore altcha: no tier solves altcha PoW → detect early + fallback manual.
  • No rate limit: even w/o 429 → IP ban / service degradation.
  • Stable selectors: CSS changes frequently → validate before each campaign.

  • rotate-scraping-proxies — network-layer escalation when client-side stealth exhausted
  • use-graphql-api — GraphQL endpoint > scraping
  • serialize-data-formats — JSON/CSV conversion
  • deploy-searxng — self-hosted aggregator
  • forage-solutions — broader info gathering
<!-- Keep under 500 lines. Extract large examples to references/EXAMPLES.md if needed. -->

GitHub 저장소

pjt222/agent-almanac
경로: i18n/caveman-ultra/skills/headless-web-scraping
0
agentsagentskillsai-assisted-developmentclaude-codeskillsteams

연관 스킬

executing-plans

디자인

executing-plans 스킬은 검토 체크포인트가 포함된 통제된 배치로 실행할 완전한 구현 계획이 있을 때 사용합니다. 이 스킬은 계획을 불러와 비판적으로 검토한 후, 소규모 배치(기본값 3개 작업)로 작업을 실행하면서 각 배치 사이에 진행 상황을 아키텍트 검토를 위해 보고합니다. 이를 통해 내재된 품질 관리 체크포인트를 갖춘 체계적인 구현이 보장됩니다.

스킬 보기

requesting-code-review

디자인

이 스킬은 코드 변경 사항을 요구 사항에 따라 분석하기 위해 코드 리뷰어 하위 에이전트를 호출합니다. 작업 완료 후, 주요 기능 구현 후, 또는 메인 브랜치에 병합하기 전에 사용해야 합니다. 이 리뷰는 현재 구현체와 원래 계획을 비교하여 문제를 조기에 발견하는 데 도움이 됩니다.

스킬 보기

connect-mcp-server

디자인

이 스킬은 개발자들이 HTTP, stdio 또는 SSE 전송 방식을 통해 MCP 서버를 Claude Code에 연결하는 포괄적인 가이드를 제공합니다. GitHub, Notion 및 사용자 정의 API와 같은 외부 서비스를 통합하기 위한 설치, 구성, 인증 및 보안을 다룹니다. MCP 통합 설정, 외부 도구 구성 또는 Claude의 모델 컨텍스트 프로토콜 작업 시 활용하세요.

스킬 보기

web-cli-teleport

디자인

이 스킬은 작업 분석을 기반으로 개발자가 Claude Code 웹 인터페이스와 CLI 인터페이스 중 선택할 수 있도록 돕고, 두 환경 간 원활한 세션 텔레포트를 가능하게 합니다. 웹, CLI 또는 모바일 환경 전환 시 세션 상태와 컨텍스트를 관리하여 워크플로를 최적화합니다. 다양한 단계에서 서로 다른 도구가 필요한 복잡한 프로젝트에 사용하세요.

스킬 보기