返回技能列表

headless-web-scraping

pjt222
更新于 2 days ago
6 次查看
17
2
17
在 GitHub 上查看
设计apiautomationdesigndata

关于

This skill enables robust web scraping using the scrapling Python library, automatically selecting between HTTP, stealth Chromium, or full browser automation based on site defenses. It handles JavaScript-rendered pages, anti-bot protections, and complex DOM traversal for structured data extraction. Use it when WebFetch fails due to dynamic content or advanced blocking mechanisms.

快速安装

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 data from web pages that resist simple HTTP requests — JS-rendered content, Cloudflare-protected sites, and dynamic SPAs — using scrapling's three-tier fetcher architecture and CSS-based data extraction.

When to Use

  • Target page requires JavaScript rendering (SPA, React, Vue)
  • Site has anti-bot protections (Cloudflare Turnstile, TLS fingerprinting)
  • You need structured extraction of multiple elements via CSS selectors
  • Simple WebFetch or requests.get() returns empty or blocked responses
  • Extracting tabular data, link lists, or repeated DOM structures at scale

Inputs

  • Required: Target URL or list of URLs to scrape
  • Required: Data to extract (CSS selectors, field names, or description of target elements)
  • Optional: Fetcher tier override (default: auto-select based on site behavior)
  • Optional: Output format (default: JSON; alternatives: CSV, Python dict)
  • Optional: Rate limit delay in seconds (default: 1)

Procedure

Step 1: Select Fetcher Tier

Determine which scrapling fetcher matches the target site's defenses.

# 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)

Got: One of the three tiers is identified. For most modern sites, StealthyFetcher is the correct starting point.

If fail: If all three tiers return blocked responses, check whether the site uses altcha CAPTCHA (proof-of-work challenge that cannot be bypassed). If so, document the limitation and provide manual extraction instructions instead.

Step 2: Configure the Fetcher

Set up the selected fetcher with appropriate options.

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
)

Got: Fetcher instance is configured and ready. No errors on instantiation. For StealthyFetcher and DynamicFetcher, a Chromium binary is available (scrapling manages this automatically on first run).

If fail:

  • playwright or browser binary not found -- run python -m playwright install chromium
  • Timeout on configure() -- increase timeout value or check network connectivity
  • Import error -- install scrapling: pip install scrapling

Step 3: Fetch and Extract Data

Navigate to the target URL and extract structured data using CSS selectors.

# 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

Key API reference:

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

Got: Extracted data matches the visible page content. Elements are non-None and text content is non-empty for populated pages.

If fail:

  • find() returns None -- inspect the actual HTML (response.html_content) to verify the selector; the page may use different class names than expected
  • Empty text from get_all_text() -- content may be inside shadow DOM or an iframe; try DynamicFetcher with a wait_selector
  • Do NOT use .css_first() -- this is not part of the scrapling API (common confusion with other libraries)

Step 4: Handle Failures and Edge Cases

Implement fallback logic for CAPTCHA detection, empty responses, and session requirements.

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

Got: Function returns extracted text on success, or None with a diagnostic message when all tiers fail. CAPTCHA pages are detected and reported rather than retried indefinitely.

If fail:

  • All tiers return 403 -- the site blocks all automated access (common with WIPO, TMview, some government databases); document the URL as requiring manual access
  • Timeout errors -- the page may be behind a slow CDN; increase timeout to 120s
  • Session/cookie errors -- the site may require login; add cookie handling or authenticate first

Step 5: Rate Limiting and Ethical Scraping

Implement delays and respect site policies before running at scale.

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 scraping checklist:

  1. Check robots.txt before scraping -- respect Disallow directives
  2. Use a minimum 1-second delay between requests
  3. Identify your scraper with a descriptive User-Agent when possible
  4. Do not scrape personal data without legal basis
  5. Cache responses locally to avoid redundant requests
  6. Stop immediately if you receive a 429 (Too Many Requests)

Got: Scraping runs at a controlled rate. robots.txt is checked before bulk operations. No 429 responses are triggered.

If fail:

  • 429 Too Many Requests -- increase delay to 3-5 seconds, or stop and retry later
  • robots.txt disallows the path -- respect the directive; do not override it
  • IP ban -- stop scraping immediately; the rate limiting was insufficient. If access is legitimate (public data, ToS-permitted, robots.txt-respected) and you must continue, see rotate-scraping-proxies for network-layer escalation

Validation

  • Correct fetcher tier is selected (not over- or under-powered for the target)
  • configure() method is used (not deprecated constructor kwargs)
  • CSS selectors match actual page structure (verified against page source)
  • .find() / .find_all() API is used (not .css_first() or other library methods)
  • CAPTCHA detection is in place (altcha pages are reported, not retried)
  • Rate limiting is implemented for multi-URL scraping
  • robots.txt is checked before bulk operations
  • Extracted data is non-empty and structurally correct

Pitfalls

  • Using .css_first() instead of .find(): scrapling uses .find() and .find_all() for element selection -- .css_first() belongs to a different library and will raise AttributeError
  • Starting with DynamicFetcher: Try Fetcher first, then escalate -- DynamicFetcher is 10-50x slower due to full browser startup
  • Constructor kwargs instead of configure(): scrapling v0.4.x deprecated passing options to the constructor; use the configure() method
  • Ignoring altcha CAPTCHA: No fetcher tier can solve altcha proof-of-work challenges -- detect them early and fall back to manual instructions
  • No rate limiting: Even if the site does not return 429, aggressive scraping can get your IP banned or cause service degradation
  • Assuming stable selectors: Website CSS classes change frequently -- validate selectors against current page source before each scraping campaign

Related Skills

  • rotate-scraping-proxies -- network-layer escalation when client-side stealth is exhausted and IP bans block legitimate, ToS-permitted access
  • use-graphql-api -- structured API queries when the site offers a GraphQL endpoint (preferred over scraping)
  • serialize-data-formats -- converting extracted data to JSON, CSV, or other formats
  • deploy-searxng -- self-hosted search engine that aggregates results from multiple sources
  • forage-solutions -- broader pattern for gathering information from diverse sources
<!-- Keep under 500 lines. Extract large examples to references/EXAMPLES.md if needed. -->

GitHub 仓库

pjt222/agent-almanac
路径: i18n/caveman-lite/skills/headless-web-scraping
0
agentsagentskillsai-assisted-developmentclaude-codeskillsteams

相关推荐技能

executing-plans

设计

该Skill用于当开发者提供完整实施计划时,以受控批次方式执行代码实现。它会先审阅计划并提出疑问,然后分批次执行任务(默认每批3个任务),并在批次间暂停等待审查。关键特性包括分批次执行、内置检查点和架构师审查机制,确保复杂系统实现的可控性。

查看技能

requesting-code-review

设计

该Skill可在完成任务、实现主要功能或合并代码前自动调度代码审查子代理,确保实现符合需求和计划。它支持通过指定git SHA范围进行精准的代码变更审查,帮助开发者在关键节点及时发现潜在问题。核心原则是"早审查、勤审查",适用于开发流程的各个关键阶段。

查看技能

connect-mcp-server

设计

这个Skill指导开发者如何将MCP服务器连接到Claude Code,支持HTTP、stdio和SSE三种传输协议。它涵盖了从安装配置到认证安全的完整流程,适用于集成GitHub、Notion、数据库等外部服务。当开发者需要添加集成、配置外部工具或提及MCP相关功能时,这个Skill能提供实用的操作指南。

查看技能

web-cli-teleport

设计

该Skill帮助开发者根据任务特性选择Claude Code的Web或CLI界面,并指导如何在两种环境间无缝迁移会话。它能分析任务复杂度、迭代需求等要素,推荐最优工作界面和工作流。关键特性包括会话状态管理、环境切换指导和上下文优化建议。

查看技能