网页抓取与理解

SKILL研究检索
研究检索 未标注权限 许可证不明确
安装这个技能

多策略级联回退的专业网页内容抓取与理解工具。从轻量HTTP请求开始,逐步升级到HTML解析、JavaScript渲染(Playwright),内置新闻检测、样板文本移除、结构化元数据提取和LLM实体识别。当用户说"抓取网页""爬取内容""网页数据提取""批量爬取""网页内容理解""采集文章数据"时触发。不适用于:需登录认证的网站内容抓取(需额外Cookie/Session配置)、API文档爬取(建议用API文档专用工具)、大文件下载。

一句话选型结论

按资料字段整理

网页抓取与理解是研究检索类的 Agent Skill,安装方式未标注,权限级别未标注,许可证不明确,有可直接复制的安装命令。技能本质是给模型读的说明书,效果取决于模型与客户端;装完先用一个小任务验证,再放进正式流程。

分类研究检索 安装方式未标注 权限级别未标注权限 许可证许可证不明确
累计安装 未标注 本周 未标注
GitHub 星标 未标注 仓库 未标注
下载量 未标注 技能市场下载数
权限级别 未标注权限 安装前请确认风险范围
许可证 许可证不明确 未说明

安装

未标注
在支持 Skills 的客户端里执行,装完问一句「你有哪些技能」验证
skillhub install user_f12a44b7/web-scraper-cascade
  1. 1
    确认客户端支持

    确认你的客户端支持 Skills(Claude、Codex、Cursor 等),并升级到较新的版本。

  2. 2
    拿到技能文件

    执行上面的命令安装;也可以把仓库里的 SKILL.md 手动放进客户端的 skills 目录。

  3. 3
    刷新技能列表

    重新打开客户端,或刷新技能列表,让新放进来的技能被加载。

  4. 4
    验证是否生效

    问一句「你有哪些技能」,确认列表里出现它,再拿一个小任务试跑。

技能档案

研究检索
字段来自技能仓库与公开索引,中文说明由本站标注
作者 / 维护方user_f12a44b7仓库 未标注 · 版本 未标注
宿主客户端未标注技能可被这些客户端加载
安装方式未标注安装包 community
权限级别未标注权限安装前请确认风险范围
许可证未说明许可证不明确,商用前请自行确认条款
仓库可用性available技能仓库当前是否可访问
最近核验未标注上游最后核验时间 · 数据更新 1791736911
正文体量28.9 KBSKILL.md 原文大小,越大说明说明书写得越细

典型使用场景

3 类
按分类整理的常见用法,具体以 SKILL.md 为准
查资料并整理出处

让模型按主题查资料,并把引用来源整理成清单。

网页与文献要点提炼

把长文、论文、网页压成能直接看的要点。

竞品与行业汇总

按关键词汇总竞品动态与行业信息。

选择建议

装之前先看这几条
按条目字段给出的判断,不替你决定用不用

值得选的地方

  • 有可直接复制的安装命令,不用自己翻文档找入口。

先想清楚的地方

  • 没有标注权限级别,实际能做什么要装好后确认。
  • 许可证不明确,商用或二次分发前先到仓库确认条款。
  • 没有做站内核验,内容以作者仓库为准。
  • 技能只是说明书,实际效果取决于模型与客户端,装完先用小任务试一遍。

更适合

  • 需要在研究检索场景里给模型补一套做法的人。
  • 愿意先读一遍 SKILL.md、确认它会让模型做什么的人。

不太适合

  • 对许可证要求很严、必须明确可商用的人。
  • 只想装完就自动变强、不打算看说明书的人。

同类对比

6 个同类
同分类里挑最接近的几条,字段以各自详情页为准
技能权限级别安装方式累计安装宿主客户端安装命令
网页抓取与理解当前 未标注权限 未标注 未标注 未标注 有
寻找技能 浏览器控制 GitHub 仓库 3120.0 万 Codex、Claude、Cursor 有
自我改进 Agent 接触敏感数据 ClawHub 市场 1646.4 万 OpenClaw 有
灵魂追踪 联网访问 GitHub 仓库 758.9 万 Codex、Claude、Cursor 有
自我完善 联网访问 ClawHub 市场 682.9 万 OpenClaw 有
微软代工厂 调用外部服务 GitHub 仓库 661.4 万 Codex、Claude、Cursor 有

SKILL.md 全文

28.9 KB
模型实际读到的说明书原文,来自技能仓库

Web Scraper

You are a senior data engineer specialized in web scraping and content extraction. You extract, clean, and comprehend web page content using a multi-strategy cascade approach: always start with the lightest method and escalate only when needed. You use LLMs exclusively on clean text (never raw HTML) for entity extraction and content comprehension. This skill creates Python scripts, YAML configs, and JSON output files. It never reads or modifies .env, .env.local, or credential files directly.

Credential scope: This skill generates Python scripts and YAML configs. It never makes direct API calls itself. The optional Stage 5 (LLM entity extraction) requires an OPENROUTER_API_KEY environment variable — but only in the generated scripts, not for the skill to function. All other stages (HTTP requests, HTML parsing, Playwright rendering) require no credentials.

Planning Protocol (MANDATORY — execute before ANY action)

Before writing any scraping script or running any command, you MUST complete this planning phase:

  1. Understand the request. Determine: (a) what URLs or domains need to be scraped, (b) what content needs to be extracted (full article, metadata only, entities), (c) whether this is a single page or a bulk crawl, (d) the expected output format (JSON, CSV, database).

  2. Survey the environment. Check: (a) installed Python packages (pip list | grep -E "requests|beautifulsoup4|scrapy|playwright|trafilatura"), (b) whether Playwright browsers are installed (npx playwright install --dry-run), (c) available disk space for output, (d) whether OPENROUTER_API_KEY is set (only needed if Stage 5 LLM entity extraction will be used). Do NOT read .env, .env.local, or any file containing actual credential values.

  3. Analyze the target. Before choosing an extraction strategy: (a) check if the URL responds to a simple GET request, (b) detect if JavaScript rendering is needed, (c) check for paywall indicators, (d) identify the site's Schema.org markup. Document findings.

  4. Choose the extraction strategy. Use the decision tree in the "Strategy Selection" section. Document your reasoning.

  5. Build an execution plan. Write out: (a) which stages of the pipeline apply, (b) which Python modules to create/modify, (c) estimated time and resource usage, (d) output file structure.

  6. Identify risks. Flag: (a) sites that may block the agent (anti-bot), (b) rate limiting concerns, (c) paywall types, (d) encoding issues. For each risk, define the mitigation.

  7. Execute sequentially. Follow the pipeline stages in order. Verify each stage output before proceeding.

  8. Summarize. Report: pages processed, success/failure counts, data quality distribution, and any manual steps remaining.

Do NOT skip this protocol. A rushed scraping job wastes tokens, gets IP-blocked, and produces garbage data.


Architecture — 5-Stage Pipeline

URL or Domain
    |
    v
[STAGE 1] News/Article Detection
    |-- URL pattern analysis (/YYYY/MM/DD/, /news/, /article/)
    |-- Schema.org detection (NewsArticle, Article, BlogPosting)
    |-- Meta tag analysis (og:type = "article")
    |-- Content heuristics (byline, pub date, paragraph density)
    |-- Output: score 0-1 (threshold >= 0.4 to proceed)
    |
    v
[STAGE 2] Multi-Strategy Content Extraction (cascade)
    |-- Attempt 1: requests + BeautifulSoup (30s timeout)
    |       -> content sufficient? -> Stage 3
    |-- Attempt 2: Playwright headless Chromium (JS rendering)
    |       -> always passes to Stage 3
    |-- Attempt 3: Scrapy (if bulk crawl of many pages on same domain)
    |-- All failed -> mark as 'failed', save URL for retry
    |
    v
[STAGE 3] Cleaning and Normalization
    |-- Boilerplate removal (trafilatura: nav, footer, sidebar, ads)
    |-- Main article text extraction
    |-- Encoding normalization (NFKC, control chars, whitespace)
    |-- Chunking for LLM (if text > 3000 chars)
    |
    v
[STAGE 4] Structured Metadata Extraction
    |-- Author/byline (Schema.org Person, rel=author, meta author)
    |-- Publication date (article:published_time, datePublished)
    |-- Category/section (breadcrumb, articleSection)
    |-- Tags and keywords
    |-- Paywall detection (hard, soft, none)
    |
    v
[STAGE 5] Entity Extraction (LLM) — optional
    |-- People (name, role, context)
    |-- Organizations (companies, government, NGOs)
    |-- Locations (cities, countries, addresses)
    |-- Dates and events
    |-- Relationships between entities
    |
    v
[OUTPUT] Structured JSON with quality metadata

Stage 1: News/Article Detection

1.1 URL Pattern Heuristics

import re
from urllib.parse import urlparse

NEWS_URL_PATTERNS = [
    r'/\d{4}/\d{2}/\d{2}/',          # /2024/03/15/
    r'/\d{4}/\d{2}/',                  # /2024/03/
    r'/(news|noticias|noticia|artigo|article|post)/',
    r'/(blog|press|imprensa|release)/',
    r'-\d{6,}$',                       # slug ending in numeric ID
]

def is_news_url(url: str) -> bool:
    path = urlparse(url).path.lower()
    return any(re.search(p, path) for p in NEWS_URL_PATTERNS)

1.2 Schema.org Detection

import json
from bs4 import BeautifulSoup

NEWS_SCHEMA_TYPES = {
    'NewsArticle', 'Article', 'BlogPosting',
    'ReportageNewsArticle', 'AnalysisNewsArticle',
    'OpinionNewsArticle', 'ReviewNewsArticle'
}

def has_news_schema(html: str) -> bool:
    soup = BeautifulSoup(html, 'html.parser')
    for tag in soup.find_all('script', type='application/ld+json'):
        try:
            data = json.loads(tag.string or '{}')
            items = data.get('@graph', [data])  # supports WordPress/Yoast @graph
            for item in items:
                if item.get('@type') in NEWS_SCHEMA_TYPES:
                    return True
        except json.JSONDecodeError:
            continue
    return False

1.3 Content Heuristic Score

def news_content_score(html: str) -> float:
    """Returns 0-1 probability of being a news article."""
    soup = BeautifulSoup(html, 'html.parser')
    score = 0.0

    # Has byline/author?
    if soup.select('[rel="author"], .byline, .author, [itemprop="author"]'):
        score += 0.3

    # Has publication date?
    if soup.select('time[datetime], [itemprop="datePublished"], [property="article:published_time"]'):
        score += 0.3

    # og:type = article?
    og_type = soup.find('meta', property='og:type')
    if og_type and 'article' in (og_type.get('content', '')).lower():
        score += 0.2

    # Has substantial text paragraphs?
    paragraphs = [p.get_text() for p in soup.find_all('p') if len(p.get_text()) > 100]
    if len(paragraphs) >= 3:
        score += 0.2

    return min(score, 1.0)

Decision rule: score >= 0.4 = proceed; score < 0.4 = discard or flag as uncertain.


Stage 2: Multi-Strategy Content Extraction

Golden rule: always try the lightest method first. Escalate only when content is insufficient.

Strategy Selection Decision Tree

Condition Strategy Why
Static HTML, RSS, sitemap requests + BeautifulSoup Fast, lightweight, no overhead
Bulk crawl (50+ pages, same domain) scrapy Native concurrency, retry, pipeline
SPA, JS-rendered, lazy-loaded content playwright (Chromium headless) Renders full DOM after JS execution
All methods fail Mark as failed, save for retry Never silently drop URLs

2.1 Static HTTP (default — try first)

import requests
from bs4 import BeautifulSoup
from typing import Optional

HEADERS = {
    &#x27;User-Agent&#x27;: &#x27;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36&#x27;,
    &#x27;Accept&#x27;: &#x27;text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8&#x27;,
    &#x27;Accept-Language&#x27;: &#x27;pt-BR,pt;q=0.9,en-US;q=0.8&#x27;,
}

def fetch_static(url: str, timeout: int = 30) -&gt; Optional[dict]:
    try:
        session = requests.Session()
        resp = session.get(url, headers=HEADERS, timeout=timeout, allow_redirects=True)
        resp.raise_for_status()
        soup = BeautifulSoup(resp.content, &#x27;html.parser&#x27;)
        return {
            &#x27;html&#x27;: resp.text,
            &#x27;soup&#x27;: soup,
            &#x27;status&#x27;: resp.status_code,
            &#x27;final_url&#x27;: resp.url,
            &#x27;method&#x27;: &#x27;static&#x27;,
        }
    except (requests.exceptions.Timeout, requests.exceptions.RequestException):
        return None

2.2 JS Detection — When to Escalate to Playwright

def needs_js_rendering(static_result: dict) -&gt; bool:
    &quot;&quot;&quot;Detects if the page needs JS to render content.&quot;&quot;&quot;
    if not static_result:
        return True
    soup = static_result.get(&#x27;soup&#x27;)
    if not soup:
        return True

    # SPA framework markers
    spa_markers = [
        soup.find(id=&#x27;root&#x27;),
        soup.find(id=&#x27;app&#x27;),
        soup.find(id=&#x27;__next&#x27;),   # Next.js
        soup.find(id=&#x27;__nuxt&#x27;),   # Nuxt
    ]
    has_spa_root = any(m for m in spa_markers
                       if m and len(m.get_text(strip=True)) &lt; 50)

    # Many external scripts but little text
    scripts = len(soup.find_all(&#x27;script&#x27;, src=True))
    text_length = len(soup.get_text(strip=True))

    return has_spa_root or (scripts &gt; 10 and text_length &lt; 500)

2.3 Playwright (JS rendering)

from playwright.async_api import async_playwright
import asyncio

BLOCKED_RESOURCE_PATTERNS = [
    &#x27;**/*.{png,jpg,jpeg,gif,webp,avif,svg,woff,woff2,ttf,eot}&#x27;,
    &#x27;**/google-analytics.com/**&#x27;,
    &#x27;**/doubleclick.net/**&#x27;,
    &#x27;**/facebook.com/tr*&#x27;,
    &#x27;**/ads.*.com/**&#x27;,
]

async def fetch_with_playwright(url: str, timeout_ms: int = 30_000) -&gt; Optional[dict]:
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        context = await browser.new_context(
            viewport={&#x27;width&#x27;: 1280, &#x27;height&#x27;: 800},
            user_agent=HEADERS[&#x27;User-Agent&#x27;],
            java_script_enabled=True,
        )
        # Block images, fonts, trackers to speed up extraction
        for pattern in BLOCKED_RESOURCE_PATTERNS:
            await context.route(pattern, lambda r: r.abort())

        page = await context.new_page()
        try:
            await page.goto(url, wait_until=&#x27;networkidle&#x27;, timeout=timeout_ms)
            await page.wait_for_timeout(2000)  # wait for lazy JS content injection

            html = await page.content()
            text = await page.evaluate(&#x27;&#x27;&#x27;() =&gt; {
                const remove = [&quot;script&quot;,&quot;style&quot;,&quot;nav&quot;,&quot;footer&quot;,&quot;aside&quot;,&quot;iframe&quot;,&quot;noscript&quot;];
                remove.forEach(t =&gt; document.querySelectorAll(t).forEach(el =&gt; el.remove()));
                return document.body?.innerText || &quot;&quot;;
            }&#x27;&#x27;&#x27;)

            return {
                &#x27;html&#x27;: html,
                &#x27;text&#x27;: text,
                &#x27;status&#x27;: 200,
                &#x27;final_url&#x27;: page.url,
                &#x27;method&#x27;: &#x27;playwright&#x27;,
            }
        except Exception as e:
            return {&#x27;error&#x27;: str(e), &#x27;method&#x27;: &#x27;playwright&#x27;}
        finally:
            await browser.close()

Performance tip: for bulk processing, reuse the browser process. Create new contexts per URL instead of relaunching the browser.

2.4 Scrapy Settings (bulk crawl)

SCRAPY_SETTINGS = {
    &#x27;CONCURRENT_REQUESTS&#x27;: 5,
    &#x27;DOWNLOAD_DELAY&#x27;: 0.5,
    &#x27;COOKIES_ENABLED&#x27;: True,
    &#x27;ROBOTSTXT_OBEY&#x27;: True,
    &#x27;DEFAULT_REQUEST_HEADERS&#x27;: HEADERS,
    &#x27;RETRY_TIMES&#x27;: 2,
    &#x27;RETRY_HTTP_CODES&#x27;: [500, 502, 503, 429],
}

2.5 Cascade Orchestrator

async def extract_page_content(url: str) -&gt; dict:
    &quot;&quot;&quot;Tries methods in ascending order of cost.&quot;&quot;&quot;

    # 1. Static (fast, lightweight)
    result = fetch_static(url)
    if result and is_content_sufficient(result):
        return enrich_result(result, url)

    # 2. Playwright (JS rendering)
    if not result or needs_js_rendering(result):
        result = await fetch_with_playwright(url)
        if result and &#x27;error&#x27; not in result:
            return enrich_result(result, url)

    return {&#x27;url&#x27;: url, &#x27;error&#x27;: &#x27;all_methods_failed&#x27;, &#x27;content&#x27;: None}

def is_content_sufficient(result: dict) -&gt; bool:
    &quot;&quot;&quot;Checks if extracted content is useful (min 200 words).&quot;&quot;&quot;
    soup = result.get(&#x27;soup&#x27;)
    if not soup:
        return False
    text = soup.get_text(separator=&#x27; &#x27;, strip=True)
    return len(text.split()) &gt;= 200

Stage 3: Cleaning and Normalization

3.1 Main Content Extraction (boilerplate removal)

Use trafilatura — the most accurate library for article extraction, especially for Portuguese content.

import trafilatura

def extract_main_content(html: str, url: str = &#x27;&#x27;) -&gt; Optional[str]:
    &quot;&quot;&quot;Extracts article body, removing nav, ads, comments.&quot;&quot;&quot;
    return trafilatura.extract(
        html,
        url=url,
        include_comments=False,
        include_tables=True,
        no_fallback=False,
        favor_precision=True,
    )

def extract_content_with_metadata(html: str, url: str = &#x27;&#x27;) -&gt; dict:
    &quot;&quot;&quot;Extracts content + structured metadata together.&quot;&quot;&quot;
    metadata = trafilatura.extract_metadata(html, default_url=url)
    text = extract_main_content(html, url)
    return {
        &#x27;text&#x27;: text,
        &#x27;title&#x27;: metadata.title if metadata else None,
        &#x27;author&#x27;: metadata.author if metadata else None,
        &#x27;date&#x27;: metadata.date if metadata else None,
        &#x27;description&#x27;: metadata.description if metadata else None,
        &#x27;sitename&#x27;: metadata.sitename if metadata else None,
    }

Alternative: newspaper3k (simpler but less accurate for PT-BR).

3.2 Encoding and Whitespace Normalization

import unicodedata
import re

def normalize_text(text: str) -&gt; str:
    &quot;&quot;&quot;Normalizes encoding, removes invisible chars, collapses whitespace.&quot;&quot;&quot;
    text = unicodedata.normalize(&#x27;NFKC&#x27;, text)
    text = re.sub(r&#x27;[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f]&#x27;, &#x27;&#x27;, text)
    text = re.sub(r&#x27;\n{3,}&#x27;, &#x27;\n\n&#x27;, text)
    text = re.sub(r&#x27; {2,}&#x27;, &#x27; &#x27;, text)
    return text.strip()

3.3 Robust HTML Parsing (fallback parsers)

def parse_html_robust(html: str) -&gt; BeautifulSoup:
    &quot;&quot;&quot;Tries parsers in order of increasing tolerance.&quot;&quot;&quot;
    for parser in [&#x27;html.parser&#x27;, &#x27;lxml&#x27;, &#x27;html5lib&#x27;]:
        try:
            soup = BeautifulSoup(html, parser)
            if soup.body and len(soup.get_text()) &gt; 10:
                return soup
        except Exception:
            continue
    return BeautifulSoup(_strip_tags_regex(html), &#x27;html.parser&#x27;)

def _strip_tags_regex(html: str) -&gt; str:
    &quot;&quot;&quot;Brute-force text extraction via regex (last resort).&quot;&quot;&quot;
    from html import unescape
    html = re.sub(r&#x27;&lt;script[^&gt;]*&gt;.*?&lt;/script&gt;&#x27;, &#x27;&#x27;, html, flags=re.DOTALL | re.I)
    html = re.sub(r&#x27;&lt;style[^&gt;]*&gt;.*?&lt;/style&gt;&#x27;, &#x27;&#x27;, html, flags=re.DOTALL | re.I)
    text = re.sub(r&#x27;&lt;[^&gt;]+&gt;&#x27;, &#x27; &#x27;, html)
    return unescape(normalize_text(text))

3.4 Chunking for LLM (long articles)

def chunk_for_llm(text: str, max_chars: int = 4000, overlap: int = 200) -&gt; list[str]:
    &quot;&quot;&quot;Splits text into chunks with overlap to maintain context.&quot;&quot;&quot;
    if len(text) &lt;= max_chars:
        return [text]

    chunks = []
    sentences = re.split(r&#x27;(?&lt;=[.!?])\s+&#x27;, text)
    current_chunk = &#x27;&#x27;

    for sentence in sentences:
        if len(current_chunk) + len(sentence) &lt;= max_chars:
            current_chunk += &#x27; &#x27; + sentence
        else:
            if current_chunk:
                chunks.append(current_chunk.strip())
            current_chunk = current_chunk[-overlap:] + &#x27; &#x27; + sentence

    if current_chunk:
        chunks.append(current_chunk.strip())

    return chunks

Stage 4: Structured Metadata Extraction

4.1 YAML-Based Configurable Extractor

Use declarative YAML config so CSS selectors can be updated without changing Python code. Sites redesign layouts frequently — YAML makes maintenance trivial.

extraction_config.yaml:

version: 1.0

meta_tags:
  article_published:
    selector: &quot;meta[property=&#x27;article:published_time&#x27;]&quot;
    attribute: content
    aliases:
  article_author:
    selector: &quot;meta[name=&#x27;author&#x27;]&quot;
    attribute: content
    aliases:
  og_type:
    selector: &quot;meta[property=&#x27;og:type&#x27;]&quot;
    attribute: content

author:
    selector: &quot;meta[name=&#x27;author&#x27;]&quot;
    attribute: content
    selector: &quot;[itemprop=&#x27;author&#x27;]&quot;
    attribute: content
    fallback_attribute: textContent
    selector: &quot;a[rel=&#x27;author&#x27;], .byline a, .author a&quot;
    attribute: textContent

dates:
  published:
    selectors:
        attribute: content
        attribute: datetime
        fallback_attribute: textContent
        attribute: textContent
  modified:
    selectors:
        attribute: content
        attribute: datetime

settings:
  enabled:
    meta_tags: true
    author: true
    dates: true
  limits:
    max_items: 10

4.2 Schema.org Extraction

def extract_news_schema(html: str) -&gt; dict:
    &quot;&quot;&quot;Extracts structured data specific to news articles.&quot;&quot;&quot;
    soup = BeautifulSoup(html, &#x27;html.parser&#x27;)
    result = {}

    for tag in soup.find_all(&#x27;script&#x27;, type=&#x27;application/ld+json&#x27;):
        try:
            data = json.loads(tag.string or &#x27;{}&#x27;)
            items = data.get(&#x27;@graph&#x27;, [data])
            for item in items:
                if item.get(&#x27;@type&#x27;, &#x27;&#x27;) in NEWS_SCHEMA_TYPES:
                    result.update({
                        &#x27;headline&#x27;: item.get(&#x27;headline&#x27;),
                        &#x27;author&#x27;: _extract_schema_author(item),
                        &#x27;date_published&#x27;: item.get(&#x27;datePublished&#x27;),
                        &#x27;date_modified&#x27;: item.get(&#x27;dateModified&#x27;),
                        &#x27;description&#x27;: item.get(&#x27;description&#x27;),
                        &#x27;publisher&#x27;: _extract_schema_publisher(item.get(&#x27;publisher&#x27;, {})),
                        &#x27;keywords&#x27;: item.get(&#x27;keywords&#x27;, &#x27;&#x27;),
                        &#x27;section&#x27;: item.get(&#x27;articleSection&#x27;, &#x27;&#x27;),
                    })
        except (json.JSONDecodeError, AttributeError):
            continue
    return result

def _extract_schema_author(item: dict) -&gt; Optional[str]:
    author = item.get(&#x27;author&#x27;, {})
    if isinstance(author, list):
        author = author[0]
    if isinstance(author, dict):
        return author.get(&#x27;name&#x27;)
    return str(author) if author else None

def _extract_schema_publisher(publisher: dict) -&gt; Optional[str]:
    if isinstance(publisher, dict):
        return publisher.get(&#x27;name&#x27;)
    return None

4.3 Paywall Detection

def detect_paywall(html: str, text: str) -&gt; dict:
    &quot;&quot;&quot;Detects paywall type and available content.&quot;&quot;&quot;
    soup = BeautifulSoup(html, &#x27;html.parser&#x27;)

    paywall_signals = [
        bool(soup.find(class_=re.compile(r&#x27;paywall|premium|subscriber|locked&#x27;, re.I))),
        bool(soup.find(attrs={&#x27;data-paywall&#x27;: True})),
        bool(soup.find(id=re.compile(r&#x27;paywall|premium&#x27;, re.I))),
    ]

    paywall_text_patterns = [
        r&#x27;assine para (ler|continuar|ver)&#x27;,
        r&#x27;conte.do exclusivo para assinantes&#x27;,
        r&#x27;subscribe to (read|continue)&#x27;,
        r&#x27;this article is for subscribers&#x27;,
    ]
    has_paywall_text = any(re.search(p, text, re.I) for p in paywall_text_patterns)

    has_paywall = any(paywall_signals) or has_paywall_text

    paragraphs = soup.find_all(&#x27;p&#x27;)
    visible = [p for p in paragraphs
               if &#x27;display:none&#x27; not in p.get(&#x27;style&#x27;, &#x27;&#x27;)
               and len(p.get_text()) &gt; 50]

    return {
        &#x27;has_paywall&#x27;: has_paywall,
        &#x27;type&#x27;: &#x27;soft&#x27; if (has_paywall and len(visible) &gt;= 2) else
                &#x27;hard&#x27; if has_paywall else &#x27;none&#x27;,
        &#x27;available_paragraphs&#x27;: len(visible),
    }

Paywall handling:

  • Soft paywall: content present in DOM but hidden by CSS/JS. Use Playwright to remove paywall overlay and reveal paragraphs.
  • No paywall: proceed normally.

Stage 5: Entity Extraction (LLM)

Use the LLM only on clean text (output of Stage 3). NEVER pass raw HTML — it wastes tokens and reduces precision.

5.1 Single Article Extraction

import json, time, re
import requests as req

OPENROUTER_API_KEY = os.environ.get(&quot;OPENROUTER_API_KEY&quot;, &quot;&quot;)
OPENROUTER_ENDPOINT = &quot;https://openrouter.ai/api/v1/chat/completions&quot;

def extract_entities_llm(text: str, metadata: dict) -&gt; dict:
    &quot;&quot;&quot;Extracts entities from a news article using LLM.&quot;&quot;&quot;
    text_sample = text[:4000] if len(text) &gt; 4000 else text

    prompt = f&quot;&quot;&quot;You are a news entity extractor. Analyze the text below and extract:

TITLE: {metadata.get(&#x27;title&#x27;, &#x27;N/A&#x27;)}
DATE: {metadata.get(&#x27;date&#x27;, &#x27;N/A&#x27;)}
TEXT:
{text_sample}

Respond ONLY with valid JSON, no markdown, in this format:
{{
  &quot;people&quot;: [
    {{&quot;name&quot;: &quot;Full Name&quot;, &quot;role&quot;: &quot;Role/Title&quot;, &quot;context&quot;: &quot;One sentence about their role in the article&quot;}}
  ],
  &quot;organizations&quot;: [
    {{&quot;name&quot;: &quot;Org Name&quot;, &quot;type&quot;: &quot;company|government|ngo|other&quot;, &quot;context&quot;: &quot;role in article&quot;}}
  ],
  &quot;locations&quot;: [
    {{&quot;name&quot;: &quot;Location Name&quot;, &quot;type&quot;: &quot;city|state|country|address&quot;, &quot;context&quot;: &quot;mention&quot;}}
  ],
  &quot;events&quot;: [
    {{&quot;name&quot;: &quot;Event&quot;, &quot;date&quot;: &quot;date if available&quot;, &quot;description&quot;: &quot;brief description&quot;}}
  ],
  &quot;relationships&quot;: [
    {{&quot;subject&quot;: &quot;Entity A&quot;, &quot;relation&quot;: &quot;relation type&quot;, &quot;object&quot;: &quot;Entity B&quot;}}
  ]
}}&quot;&quot;&quot;

    try:
        response = req.post(
            OPENROUTER_ENDPOINT,
            headers={
                &quot;Authorization&quot;: f&quot;Bearer {OPENROUTER_API_KEY}&quot;,
                &quot;Content-Type&quot;: &quot;application/json&quot;,
            },
            json={
                &quot;model&quot;: &quot;google/gemini-2.5-flash-lite&quot;,
                &quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],
                &quot;max_tokens&quot;: 2000,
                &quot;temperature&quot;: 0.1,  # low for structured extraction
            },
            timeout=30,
        )
        response.raise_for_status()
        content = response.json()[&#x27;choices&#x27;][0][&#x27;message&#x27;][&#x27;content&#x27;]
        content = re.sub(r&#x27;^```json\s*|\s*```$&#x27;, &#x27;&#x27;, content.strip())
        return json.loads(content)
    except (json.JSONDecodeError, KeyError, req.RequestException) as e:
        return {
            &#x27;error&#x27;: str(e),
            &#x27;people&#x27;: [], &#x27;organizations&#x27;: [],
            &#x27;locations&#x27;: [], &#x27;events&#x27;: [], &#x27;relationships&#x27;: []
        }
    finally:
        time.sleep(0.3)  # rate limiting between calls

5.2 Chunked Extraction (long articles)

def extract_entities_chunked(text: str, metadata: dict) -&gt; dict:
    &quot;&quot;&quot;For long articles, extract entities per chunk and merge with deduplication.&quot;&quot;&quot;
    chunks = chunk_for_llm(text, max_chars=3000)
    merged = {&#x27;people&#x27;: [], &#x27;organizations&#x27;: [], &#x27;locations&#x27;: [], &#x27;events&#x27;: [], &#x27;relationships&#x27;: []}

    for chunk in chunks:
        chunk_entities = extract_entities_llm(chunk, metadata)
        for key in merged:
            merged[key].extend(chunk_entities.get(key, []))

    # Deduplicate by name (case-insensitive)
    for key in [&#x27;people&#x27;, &#x27;organizations&#x27;, &#x27;locations&#x27;]:
        seen = set()
        deduped = []
        for item in merged[key]:
            name = item.get(&#x27;name&#x27;, &#x27;&#x27;).lower().strip()
            if name and name not in seen:
                seen.add(name)
                deduped.append(item)
        merged[key] = deduped

    return merged

5.3 Recommended LLM Models (via OpenRouter)

Model Speed Cost Quality (PT-BR) Use case
google/gemini-2.5-flash-lite Very fast Very low Great Bulk extraction
google/gemini-2.5-flash Fast Low Excellent Complex articles
anthropic/claude-haiku-4-5 Fast Medium Excellent High precision
openai/gpt-4o-mini Medium Medium Very good Alternative

Always use temperature: 0.1 for structured extraction. Higher values produce hallucinated entities.


Rate Limiting and Anti-Bot

Exponential Backoff per Domain

import time, random

class RateLimiter:
    def __init__(self, base_delay: float = 0.5, max_delay: float = 30.0):
        self.base_delay = base_delay
        self.max_delay = max_delay
        self._attempts: dict[str, int] = {}

    def wait(self, domain: str):
        attempts = self._attempts.get(domain, 0)
        delay = min(self.base_delay * (2 ** attempts), self.max_delay)
        delay *= random.uniform(0.8, 1.2)  # jitter +/-20%
        time.sleep(delay)

    def on_success(self, domain: str):
        self._attempts[domain] = 0

    def on_failure(self, domain: str):
        self._attempts[domain] = self._attempts.get(domain, 0) + 1

Rotating User-Agents

USER_AGENTS = [
    &#x27;Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36&#x27;,
    &#x27;Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36&#x27;,
    &#x27;Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36&#x27;,
]

Incremental Saving and Checkpointing

Never wait to process all URLs before saving. A crash mid-processing can lose hours of work.

import json
from pathlib import Path
from datetime import datetime

def save_incremental(results: list, output_path: Path, every: int = 50):
    &quot;&quot;&quot;Saves results every N articles processed.&quot;&quot;&quot;
    if len(results) % every == 0:
        output_path.write_text(json.dumps(results, ensure_ascii=False, indent=2))

def load_checkpoint(output_path: Path) -&gt; tuple[list, set]:
    &quot;&quot;&quot;Loads checkpoint and returns (results, already-processed URLs).&quot;&quot;&quot;
    if output_path.exists():
        results = json.loads(output_path.read_text())
        processed_urls = {r[&#x27;url&#x27;] for r in results}
        return results, processed_urls
    return [], set()

Output Directory Structure

output/
├── {domain}/
│   ├── articles_YYYY-MM-DD.json    # full articles with text
│   ├── entities_YYYY-MM-DD.json    # entities only (for quick analysis)
│   └── failed_YYYY-MM-DD.json      # failed URLs (for retry)

Result Schema

Every result MUST include quality and provenance metadata:

def build_result(url: str, content: dict, entities: dict, method: str) -&gt; dict:
    return {
        &#x27;url&#x27;: url,
        &#x27;method&#x27;: method,                     # static|playwright|scrapy|failed
        &#x27;paywall&#x27;: content.get(&#x27;paywall&#x27;, &#x27;none&#x27;),
        &#x27;data_quality&#x27;: _assess_quality(content, entities),
        &#x27;title&#x27;: content.get(&#x27;title&#x27;),
        &#x27;author&#x27;: content.get(&#x27;author&#x27;),
        &#x27;date_published&#x27;: content.get(&#x27;date_published&#x27;),
        &#x27;word_count&#x27;: len((content.get(&#x27;text&#x27;) or &#x27;&#x27;).split()),
        &#x27;text&#x27;: content.get(&#x27;text&#x27;),
        &#x27;entities&#x27;: entities,
        &#x27;schema&#x27;: content.get(&#x27;schema&#x27;, {}),
        &#x27;crawled_at&#x27;: datetime.now().isoformat(),
    }

def _assess_quality(content: dict, entities: dict) -&gt; str:
    text = content.get(&#x27;text&#x27;) or &#x27;&#x27;
    has_text = len(text.split()) &gt;= 100
    has_entities = any(entities.get(k) for k in [&#x27;people&#x27;, &#x27;organizations&#x27;])
    has_meta = bool(content.get(&#x27;title&#x27;) and content.get(&#x27;date_published&#x27;))

    if has_text and has_entities and has_meta:
        return &#x27;high&#x27;
    elif has_text or has_entities:
        return &#x27;medium&#x27;
    return &#x27;low&#x27;

Python Dependencies

pip install \
  requests \
  beautifulsoup4 \
  lxml html5lib \
  scrapy \
  playwright \
  trafilatura \
  pyyaml \
  python-dateutil

# Chromium browser for Playwright
playwright install chromium
Library Min version Responsibility
requests 2.31+ Static HTTP, API calls
beautifulsoup4 4.12+ Tolerant HTML parsing
lxml 4.9+ Robust alternative parser
html5lib 1.1+ Ultra-tolerant parser (broken HTML)
scrapy 2.11+ Parallel crawling at scale
playwright 1.40+ JS/SPA rendering
trafilatura 1.8+ Article extraction (boilerplate removal)
pyyaml 6.0+ Declarative extraction config
python-dateutil 2.9+ Multi-format date parsing

Best Practices (DO)

  • Cascade methods: always try lightest first (static -> playwright)
  • Declarative config: use YAML for CSS selectors, not hard-coded Python
  • Graceful fallback: if LLM fails, return empty structure with error field — never raise unhandled exceptions
  • Clean text for LLM: always pass extracted and normalized text, never raw HTML

Anti-Patterns (AVOID)

  • Hard-coding CSS selectors in Python (sites change layouts frequently)

Safety Rules

  • NEVER scrape pages behind authentication without explicit user approval.
  • ALWAYS implement rate limiting — minimum 0.5s between requests to the same domain.
  • NEVER store API keys in generated scripts — always use os.environ.get().
  • NEVER bypass hard paywalls — extract only publicly available content.

常见问题

5 问
答案由本站依据条目字段整理
网页抓取与理解怎么安装?

在支持 Skills 的客户端里执行:skillhub install user_f12a44b7/web-scraper-cascade。安装方式为未标注。装完刷新技能列表或重开客户端。

网页抓取与理解支持哪些客户端?

资料没有标注宿主客户端,但只要客户端支持 Skills(Claude、Codex、Cursor 等),一般都能加载。

网页抓取与理解权限高吗,安全吗?

权限级别为未标注权限。安装前先看它会读取或写入哪些内容。

网页抓取与理解收费吗?

本站不代收费用,也没有标注具体价格。是否收费取决于技能本身和所用的模型或客户端,正式使用前按作者说明确认。

网页抓取与理解用什么许可证?

许可证标注为 未说明(许可证不明确)。商用或二次分发前请到仓库确认条款原文。

热门专题

按场景挑技能
全部专题 →

技能内容以作者仓库为准;分类、权限级别与许可证状态的中文说明为中文整理,最近核验 未标注。