[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M75H33JNP6D6HEGQ9PAR2ARS":3,"skill-same:01M75H33JNP6D6HEGQ9PAR2ARS":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":6,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":46},"01M75H33JNP6D6HEGQ9PAR2ARS","web-scraper",null,"Web scraping and content comprehension agent — multi-strategy extraction with cascade fallback, news detection, boilerplate removal, structured metadata, and LLM entity extraction","javimosch\u002Fopen-claw-skills","javimosch","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F12900508?v=4","01M6D3F2AS6PV75ET9PZ1QGP8J","Javier Leandro Arancibia","01M75B8NCTAJG9WH5YNZH7C3D8",0,"MIT","https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fguifav\u002Fweb-scraper\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: web-scraper\ndescription: Web scraping and content comprehension agent — multi-strategy extraction with cascade fallback, news detection, boilerplate removal, structured metadata, and LLM entity extraction\nuser-invocable: true\n---\n\n# Web Scraper\n\nYou 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.\n\n**Credential scope:** `OPENROUTER_API_KEY` is used in generated Python scripts to call the OpenRouter API for LLM-based entity extraction (Stage 5). The skill references this variable in template code only — it never makes direct API calls itself. All other operations (HTTP requests, HTML parsing, Playwright rendering) require no credentials.\n\n## Planning Protocol (MANDATORY — execute before ANY action)\n\nBefore writing any scraping script or running any command, you MUST complete this planning phase:\n\n1. **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).\n\n2. **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) `.env.example` for expected API keys. Do NOT read `.env`, `.env.local`, or any file containing actual credential values.\n\n3. **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.\n\n4. **Choose the extraction strategy.** Use the decision tree in the \"Strategy Selection\" section. Document your reasoning.\n\n5. **Build an execution plan.** Write out: (a) which stages of the pipeline apply, (b) which Python modules to create\u002Fmodify, (c) estimated time and resource usage, (d) output file structure.\n\n6. **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.\n\n7. **Execute sequentially.** Follow the pipeline stages in order. Verify each stage output before proceeding.\n\n8. **Summarize.** Report: pages processed, success\u002Ffailure counts, data quality distribution, and any manual steps remaining.\n\nDo NOT skip this protocol. A rushed scraping job wastes tokens, gets IP-blocked, and produces garbage data.\n\n---\n\n## Architecture — 5-Stage Pipeline\n\n```\nURL or Domain\n    |\n    v\n[STAGE 1] News\u002FArticle Detection\n    |-- URL pattern analysis (\u002FYYYY\u002FMM\u002FDD\u002F, \u002Fnews\u002F, \u002Farticle\u002F)\n    |-- Schema.org detection (NewsArticle, Article, BlogPosting)\n    |-- Meta tag analysis (og:type = \"article\")\n    |-- Content heuristics (byline, pub date, paragraph density)\n    |-- Output: score 0-1 (threshold >= 0.4 to proceed)\n    |\n    v\n[STAGE 2] Multi-Strategy Content Extraction (cascade)\n    |-- Attempt 1: requests + BeautifulSoup (30s timeout)\n    |       -> content sufficient? -> Stage 3\n    |-- Attempt 2: Playwright headless Chromium (JS rendering)\n    |       -> always passes to Stage 3\n    |-- Attempt 3: Scrapy (if bulk crawl of many pages on same domain)\n    |-- All failed -> mark as 'failed', save URL for retry\n    |\n    v\n[STAGE 3] Cleaning and Normalization\n    |-- Boilerplate removal (trafilatura: nav, footer, sidebar, ads)\n    |-- Main article text extraction\n    |-- Encoding normalization (NFKC, control chars, whitespace)\n    |-- Chunking for LLM (if text > 3000 chars)\n    |\n    v\n[STAGE 4] Structured Metadata Extraction\n    |-- Author\u002Fbyline (Schema.org Person, rel=author, meta author)\n    |-- Publication date (article:published_time, datePublished)\n    |-- Category\u002Fsection (breadcrumb, articleSection)\n    |-- Tags and keywords\n    |-- Paywall detection (hard, soft, none)\n    |\n    v\n[STAGE 5] Entity Extraction (LLM) — optional\n    |-- People (name, role, context)\n    |-- Organizations (companies, government, NGOs)\n    |-- Locations (cities, countries, addresses)\n    |-- Dates and events\n    |-- Relationships between entities\n    |\n    v\n[OUTPUT] Structured JSON with quality metadata\n```\n\n---\n\n## Stage 1: News\u002FArticle Detection\n\n### 1.1 URL Pattern Heuristics\n\n```python\nimport re\nfrom urllib.parse import urlparse\n\nNEWS_URL_PATTERNS = [\n    r'\u002F\\d{4}\u002F\\d{2}\u002F\\d{2}\u002F',          # \u002F2024\u002F03\u002F15\u002F\n    r'\u002F\\d{4}\u002F\\d{2}\u002F',                  # \u002F2024\u002F03\u002F\n    r'\u002F(news|noticias|noticia|artigo|article|post)\u002F',\n    r'\u002F(blog|press|imprensa|release)\u002F',\n    r'-\\d{6,}$',                       # slug ending in numeric ID\n]\n\ndef is_news_url(url: str) -> bool:\n    path = urlparse(url).path.lower()\n    return any(re.search(p, path) for p in NEWS_URL_PATTERNS)\n```\n\n### 1.2 Schema.org Detection\n\n```python\nimport json\nfrom bs4 import BeautifulSoup\n\nNEWS_SCHEMA_TYPES = {\n    'NewsArticle', 'Article', 'BlogPosting',\n    'ReportageNewsArticle', 'AnalysisNewsArticle',\n    'OpinionNewsArticle', 'ReviewNewsArticle'\n}\n\ndef has_news_schema(html: str) -> bool:\n    soup = BeautifulSoup(html, 'html.parser')\n    for tag in soup.find_all('script', type='application\u002Fld+json'):\n        try:\n            data = json.loads(tag.string or '{}')\n            items = data.get('@graph', [data])  # supports WordPress\u002FYoast @graph\n            for item in items:\n                if item.get('@type') in NEWS_SCHEMA_TYPES:\n                    return True\n        except json.JSONDecodeError:\n            continue\n    return False\n```\n\n### 1.3 Content Heuristic Score\n\n```python\ndef news_content_score(html: str) -> float:\n    \"\"\"Returns 0-1 probability of being a news article.\"\"\"\n    soup = BeautifulSoup(html, 'html.parser')\n    score = 0.0\n\n    # Has byline\u002Fauthor?\n    if soup.select('[rel=\"author\"], .byline, .author, [itemprop=\"author\"]'):\n        score += 0.3\n\n    # Has publication date?\n    if soup.select('time[datetime], [itemprop=\"datePublished\"], [property=\"article:published_time\"]'):\n        score += 0.3\n\n    # og:type = article?\n    og_type = soup.find('meta', property='og:type')\n    if og_type and 'article' in (og_type.get('content', '')).lower():\n        score += 0.2\n\n    # Has substantial text paragraphs?\n    paragraphs = [p.get_text() for p in soup.find_all('p') if len(p.get_text()) > 100]\n    if len(paragraphs) >= 3:\n        score += 0.2\n\n    return min(score, 1.0)\n```\n\n**Decision rule:** score >= 0.4 = proceed; score \u003C 0.4 = discard or flag as uncertain.\n\n---\n\n## Stage 2: Multi-Strategy Content Extraction\n\n**Golden rule:** always try the lightest method first. Escalate only when content is insufficient.\n\n### Strategy Selection Decision Tree\n\n| Condition | Strategy | Why |\n|---|---|---|\n| Static HTML, RSS, sitemap | `requests` + `BeautifulSoup` | Fast, lightweight, no overhead |\n| Bulk crawl (50+ pages, same domain) | `scrapy` | Native concurrency, retry, pipeline |\n| SPA, JS-rendered, lazy-loaded content | `playwright` (Chromium headless) | Renders full DOM after JS execution |\n| All methods fail | Mark as `failed`, save for retry | Never silently drop URLs |\n\n### 2.1 Static HTTP (default — try first)\n\n```python\nimport requests\nfrom bs4 import BeautifulSoup\nfrom typing import Optional\n\nHEADERS = {\n    'User-Agent': 'Mozilla\u002F5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit\u002F537.36',\n    'Accept': 'text\u002Fhtml,application\u002Fxhtml+xml,application\u002Fxml;q=0.9,*\u002F*;q=0.8',\n    'Accept-Language': 'pt-BR,pt;q=0.9,en-US;q=0.8',\n}\n\ndef fetch_static(url: str, timeout: int = 30) -> Optional[dict]:\n    try:\n        session = requests.Session()\n        resp = session.get(url, headers=HEADERS, timeout=timeout, allow_redirects=True)\n        resp.raise_for_status()\n        soup = BeautifulSoup(resp.content, 'html.parser')\n        return {\n            'html': resp.text,\n            'soup': soup,\n            'status': resp.status_code,\n            'final_url': resp.url,\n            'method': 'static',\n        }\n    except (requests.exceptions.Timeout, requests.exceptions.RequestException):\n        return None\n```\n\n### 2.2 JS Detection — When to Escalate to Playwright\n\n```python\ndef needs_js_rendering(static_result: dict) -> bool:\n    \"\"\"Detects if the page needs JS to render content.\"\"\"\n    if not static_result:\n        return True\n    soup = static_result.get('soup')\n    if not soup:\n        return True\n\n    # SPA framework markers\n    spa_markers = [\n        soup.find(id='root'),\n        soup.find(id='app'),\n        soup.find(id='__next'),   # Next.js\n        soup.find(id='__nuxt'),   # Nuxt\n    ]\n    has_spa_root = any(m for m in spa_markers\n                       if m and len(m.get_text(strip=True)) \u003C 50)\n\n    # Many external scripts but little text\n    scripts = len(soup.find_all('script', src=True))\n    text_length = len(soup.get_text(strip=True))\n\n    return has_spa_root or (scripts > 10 and text_length \u003C 500)\n```\n\n### 2.3 Playwright (JS rendering)\n\n```python\nfrom playwright.async_api import async_playwright\nimport asyncio\n\nBLOCKED_RESOURCE_PATTERNS = [\n    '**\u002F*.{png,jpg,jpeg,gif,webp,avif,svg,woff,woff2,ttf,eot}',\n    '**\u002Fgoogle-analytics.com\u002F**',\n    '**\u002Fdoubleclick.net\u002F**',\n    '**\u002Ffacebook.com\u002Ftr*',\n    '**\u002Fads.*.com\u002F**',\n]\n\nasync def fetch_with_playwright(url: str, timeout_ms: int = 30_000) -> Optional[dict]:\n    async with async_playwright() as p:\n        browser = await p.chromium.launch(headless=True)\n        context = await browser.new_context(\n            viewport={'width': 1280, 'height': 800},\n            user_agent=HEADERS['User-Agent'],\n            java_script_enabled=True,\n        )\n        # Block images, fonts, trackers to speed up extraction\n        for pattern in BLOCKED_RESOURCE_PATTERNS:\n            await context.route(pattern, lambda r: r.abort())\n\n        page = await context.new_page()\n        try:\n            await page.goto(url, wait_until='networkidle', timeout=timeout_ms)\n            await page.wait_for_timeout(2000)  # wait for lazy JS content injection\n\n            html = await page.content()\n            text = await page.evaluate('''() => {\n                const remove = [\"script\",\"style\",\"nav\",\"footer\",\"aside\",\"iframe\",\"noscript\"];\n                remove.forEach(t => document.querySelectorAll(t).forEach(el => el.remove()));\n                return document.body?.innerText || \"\";\n            }''')\n\n            return {\n                'html': html,\n                'text': text,\n                'status': 200,\n                'final_url': page.url,\n                'method': 'playwright',\n            }\n        except Exception as e:\n            return {'error': str(e), 'method': 'playwright'}\n        finally:\n            await browser.close()\n```\n\n**Performance tip:** for bulk processing, reuse the browser process. Create new contexts per URL instead of relaunching the browser.\n\n### 2.4 Scrapy Settings (bulk crawl)\n\n```python\nSCRAPY_SETTINGS = {\n    'CONCURRENT_REQUESTS': 5,\n    'DOWNLOAD_DELAY': 0.5,\n    'COOKIES_ENABLED': True,\n    'ROBOTSTXT_OBEY': True,\n    'DEFAULT_REQUEST_HEADERS': HEADERS,\n    'RETRY_TIMES': 2,\n    'RETRY_HTTP_CODES': [500, 502, 503, 429],\n}\n```\n\n### 2.5 Cascade Orchestrator\n\n```python\nasync def extract_page_content(url: str) -> dict:\n    \"\"\"Tries methods in ascending order of cost.\"\"\"\n\n    # 1. Static (fast, lightweight)\n    result = fetch_static(url)\n    if result and is_content_sufficient(result):\n        return enrich_result(result, url)\n\n    # 2. Playwright (JS rendering)\n    if not result or needs_js_rendering(result):\n        result = await fetch_with_playwright(url)\n        if result and 'error' not in result:\n            return enrich_result(result, url)\n\n    return {'url': url, 'error': 'all_methods_failed', 'content': None}\n\ndef is_content_sufficient(result: dict) -> bool:\n    \"\"\"Checks if extracted content is useful (min 200 words).\"\"\"\n    soup = result.get('soup')\n    if not soup:\n        return False\n    text = soup.get_text(separator=' ', strip=True)\n    return len(text.split()) >= 200\n```\n\n---\n\n## Stage 3: Cleaning and Normalization\n\n### 3.1 Main Content Extraction (boilerplate removal)\n\nUse `trafilatura` — the most accurate library for article extraction, especially for Portuguese content.\n\n```python\nimport trafilatura\n\ndef extract_main_content(html: str, url: str = '') -> Optional[str]:\n    \"\"\"Extracts article body, removing nav, ads, comments.\"\"\"\n    return trafilatura.extract(\n        html,\n        url=url,\n        include_comments=False,\n        include_tables=True,\n        no_fallback=False,\n        favor_precision=True,\n    )\n\ndef extract_content_with_metadata(html: str, url: str = '') -> dict:\n    \"\"\"Extracts content + structured metadata together.\"\"\"\n    metadata = trafilatura.extract_metadata(html, default_url=url)\n    text = extract_main_content(html, url)\n    return {\n        'text': text,\n        'title': metadata.title if metadata else None,\n        'author': metadata.author if metadata else None,\n        'date': metadata.date if metadata else None,\n        'description': metadata.description if metadata else None,\n        'sitename': metadata.sitename if metadata else None,\n    }\n```\n\n**Alternative:** `newspaper3k` (simpler but less accurate for PT-BR).\n\n### 3.2 Encoding and Whitespace Normalization\n\n```python\nimport unicodedata\nimport re\n\ndef normalize_text(text: str) -> str:\n    \"\"\"Normalizes encoding, removes invisible chars, collapses whitespace.\"\"\"\n    text = unicodedata.normalize('NFKC', text)\n    text = re.sub(r'[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f\\x7f]', '', text)\n    text = re.sub(r'\\n{3,}', '\\n\\n', text)\n    text = re.sub(r' {2,}', ' ', text)\n    return text.strip()\n```\n\n### 3.3 Robust HTML Parsing (fallback parsers)\n\n```python\ndef parse_html_robust(html: str) -> BeautifulSoup:\n    \"\"\"Tries parsers in order of increasing tolerance.\"\"\"\n    for parser in ['html.parser', 'lxml', 'html5lib']:\n        try:\n            soup = BeautifulSoup(html, parser)\n            if soup.body and len(soup.get_text()) > 10:\n                return soup\n        except Exception:\n            continue\n    return BeautifulSoup(_strip_tags_regex(html), 'html.parser')\n\ndef _strip_tags_regex(html: str) -> str:\n    \"\"\"Brute-force text extraction via regex (last resort).\"\"\"\n    from html import unescape\n    html = re.sub(r'\u003Cscript[^>]*>.*?\u003C\u002Fscript>', '', html, flags=re.DOTALL | re.I)\n    html = re.sub(r'\u003Cstyle[^>]*>.*?\u003C\u002Fstyle>', '', html, flags=re.DOTALL | re.I)\n    text = re.sub(r'\u003C[^>]+>', ' ', html)\n    return unescape(normalize_text(text))\n```\n\n### 3.4 Chunking for LLM (long articles)\n\n```python\ndef chunk_for_llm(text: str, max_chars: int = 4000, overlap: int = 200) -> list[str]:\n    \"\"\"Splits text into chunks with overlap to maintain context.\"\"\"\n    if len(text) \u003C= max_chars:\n        return [text]\n\n    chunks = []\n    sentences = re.split(r'(?\u003C=[.!?])\\s+', text)\n    current_chunk = ''\n\n    for sentence in sentences:\n        if len(current_chunk) + len(sentence) \u003C= max_chars:\n            current_chunk += ' ' + sentence\n        else:\n            if current_chunk:\n                chunks.append(current_chunk.strip())\n            current_chunk = current_chunk[-overlap:] + ' ' + sentence\n\n    if current_chunk:\n        chunks.append(current_chunk.strip())\n\n    return chunks\n```\n\n---\n\n## Stage 4: Structured Metadata Extraction\n\n### 4.1 YAML-Based Configurable Extractor\n\nUse declarative YAML config so CSS selectors can be updated without changing Python code. Sites redesign layouts frequently — YAML makes maintenance trivial.\n\n**`extraction_config.yaml`:**\n\n```yaml\nversion: 1.0\n\nmeta_tags:\n  article_published:\n    selector: \"meta[property='article:published_time']\"\n    attribute: content\n    aliases:\n      - \"meta[name='publication_date']\"\n      - \"meta[name='date']\"\n  article_author:\n    selector: \"meta[name='author']\"\n    attribute: content\n    aliases:\n      - \"meta[property='article:author']\"\n  og_type:\n    selector: \"meta[property='og:type']\"\n    attribute: content\n\nauthor:\n  - name: meta_author\n    selector: \"meta[name='author']\"\n    attribute: content\n  - name: schema_author\n    selector: \"[itemprop='author']\"\n    attribute: content\n    fallback_attribute: textContent\n  - name: byline_link\n    selector: \"a[rel='author'], .byline a, .author a\"\n    attribute: textContent\n\ndates:\n  published:\n    selectors:\n      - selector: \"meta[property='article:published_time']\"\n        attribute: content\n      - selector: \"time[itemprop='datePublished']\"\n        attribute: datetime\n        fallback_attribute: textContent\n      - selector: \"[class*='date'][class*='publish']\"\n        attribute: textContent\n  modified:\n    selectors:\n      - selector: \"meta[property='article:modified_time']\"\n        attribute: content\n      - selector: \"time[itemprop='dateModified']\"\n        attribute: datetime\n\nsettings:\n  enabled:\n    meta_tags: true\n    author: true\n    dates: true\n  limits:\n    max_items: 10\n```\n\n### 4.2 Schema.org Extraction\n\n```python\ndef extract_news_schema(html: str) -> dict:\n    \"\"\"Extracts structured data specific to news articles.\"\"\"\n    soup = BeautifulSoup(html, 'html.parser')\n    result = {}\n\n    for tag in soup.find_all('script', type='application\u002Fld+json'):\n        try:\n            data = json.loads(tag.string or '{}')\n            items = data.get('@graph', [data])\n            for item in items:\n                if item.get('@type', '') in NEWS_SCHEMA_TYPES:\n                    result.update({\n                        'headline': item.get('headline'),\n                        'author': _extract_schema_author(item),\n                        'date_published': item.get('datePublished'),\n                        'date_modified': item.get('dateModified'),\n                        'description': item.get('description'),\n                        'publisher': _extract_schema_publisher(item.get('publisher', {})),\n                        'keywords': item.get('keywords', ''),\n                        'section': item.get('articleSection', ''),\n                    })\n        except (json.JSONDecodeError, AttributeError):\n            continue\n    return result\n\ndef _extract_schema_author(item: dict) -> Optional[str]:\n    author = item.get('author', {})\n    if isinstance(author, list):\n        author = author[0]\n    if isinstance(author, dict):\n        return author.get('name')\n    return str(author) if author else None\n\ndef _extract_schema_publisher(publisher: dict) -> Optional[str]:\n    if isinstance(publisher, dict):\n        return publisher.get('name')\n    return None\n```\n\n### 4.3 Paywall Detection\n\n```python\ndef detect_paywall(html: str, text: str) -> dict:\n    \"\"\"Detects paywall type and available content.\"\"\"\n    soup = BeautifulSoup(html, 'html.parser')\n\n    paywall_signals = [\n        bool(soup.find(class_=re.compile(r'paywall|premium|subscriber|locked', re.I))),\n        bool(soup.find(attrs={'data-paywall': True})),\n        bool(soup.find(id=re.compile(r'paywall|premium', re.I))),\n    ]\n\n    paywall_text_patterns = [\n        r'assine para (ler|continuar|ver)',\n        r'conte.do exclusivo para assinantes',\n        r'subscribe to (read|continue)',\n        r'this article is for subscribers',\n    ]\n    has_paywall_text = any(re.search(p, text, re.I) for p in paywall_text_patterns)\n\n    has_paywall = any(paywall_signals) or has_paywall_text\n\n    paragraphs = soup.find_all('p')\n    visible = [p for p in paragraphs\n               if 'display:none' not in p.get('style', '')\n               and len(p.get_text()) > 50]\n\n    return {\n        'has_paywall': has_paywall,\n        'type': 'soft' if (has_paywall and len(visible) >= 2) else\n                'hard' if has_paywall else 'none',\n        'available_paragraphs': len(visible),\n    }\n```\n\n**Paywall handling:**\n\n- **Hard paywall:** content never sent to client. Extract preview (title, lead, metadata). Mark `paywall: \"hard\"` in output.\n- **Soft paywall:** content present in DOM but hidden by CSS\u002FJS. Use Playwright to remove paywall overlay and reveal paragraphs.\n- **No paywall:** proceed normally.\n\n---\n\n## Stage 5: Entity Extraction (LLM)\n\nUse the LLM **only on clean text** (output of Stage 3). NEVER pass raw HTML — it wastes tokens and reduces precision.\n\n### 5.1 Single Article Extraction\n\n```python\nimport json, time, re\nimport requests as req\n\nOPENROUTER_API_KEY = os.environ.get(\"OPENROUTER_API_KEY\", \"\")\nOPENROUTER_ENDPOINT = \"https:\u002F\u002Fopenrouter.ai\u002Fapi\u002Fv1\u002Fchat\u002Fcompletions\"\n\ndef extract_entities_llm(text: str, metadata: dict) -> dict:\n    \"\"\"Extracts entities from a news article using LLM.\"\"\"\n    text_sample = text[:4000] if len(text) > 4000 else text\n\n    prompt = f\"\"\"You are a news entity extractor. Analyze the text below and extract:\n\nTITLE: {metadata.get('title', 'N\u002FA')}\nDATE: {metadata.get('date', 'N\u002FA')}\nTEXT:\n{text_sample}\n\nRespond ONLY with valid JSON, no markdown, in this format:\n{{\n  \"people\": [\n    {{\"name\": \"Full Name\", \"role\": \"Role\u002FTitle\", \"context\": \"One sentence about their role in the article\"}}\n  ],\n  \"organizations\": [\n    {{\"name\": \"Org Name\", \"type\": \"company|government|ngo|other\", \"context\": \"role in article\"}}\n  ],\n  \"locations\": [\n    {{\"name\": \"Location Name\", \"type\": \"city|state|country|address\", \"context\": \"mention\"}}\n  ],\n  \"events\": [\n    {{\"name\": \"Event\", \"date\": \"date if available\", \"description\": \"brief description\"}}\n  ],\n  \"relationships\": [\n    {{\"subject\": \"Entity A\", \"relation\": \"relation type\", \"object\": \"Entity B\"}}\n  ]\n}}\"\"\"\n\n    try:\n        response = req.post(\n            OPENROUTER_ENDPOINT,\n            headers={\n                \"Authorization\": f\"Bearer {OPENROUTER_API_KEY}\",\n                \"Content-Type\": \"application\u002Fjson\",\n            },\n            json={\n                \"model\": \"google\u002Fgemini-2.5-flash-lite\",\n                \"messages\": [{\"role\": \"user\", \"content\": prompt}],\n                \"max_tokens\": 2000,\n                \"temperature\": 0.1,  # low for structured extraction\n            },\n            timeout=30,\n        )\n        response.raise_for_status()\n        content = response.json()['choices'][0]['message']['content']\n        content = re.sub(r'^```json\\s*|\\s*```$', '', content.strip())\n        return json.loads(content)\n    except (json.JSONDecodeError, KeyError, req.RequestException) as e:\n        return {\n            'error': str(e),\n            'people': [], 'organizations': [],\n            'locations': [], 'events': [], 'relationships': []\n        }\n    finally:\n        time.sleep(0.3)  # rate limiting between calls\n```\n\n### 5.2 Chunked Extraction (long articles)\n\n```python\ndef extract_entities_chunked(text: str, metadata: dict) -> dict:\n    \"\"\"For long articles, extract entities per chunk and merge with deduplication.\"\"\"\n    chunks = chunk_for_llm(text, max_chars=3000)\n    merged = {'people': [], 'organizations': [], 'locations': [], 'events': [], 'relationships': []}\n\n    for chunk in chunks:\n        chunk_entities = extract_entities_llm(chunk, metadata)\n        for key in merged:\n            merged[key].extend(chunk_entities.get(key, []))\n\n    # Deduplicate by name (case-insensitive)\n    for key in ['people', 'organizations', 'locations']:\n        seen = set()\n        deduped = []\n        for item in merged[key]:\n            name = item.get('name', '').lower().strip()\n            if name and name not in seen:\n                seen.add(name)\n                deduped.append(item)\n        merged[key] = deduped\n\n    return merged\n```\n\n### 5.3 Recommended LLM Models (via OpenRouter)\n\n| Model | Speed | Cost | Quality (PT-BR) | Use case |\n|---|---|---|---|---|\n| `google\u002Fgemini-2.5-flash-lite` | Very fast | Very low | Great | Bulk extraction |\n| `google\u002Fgemini-2.5-flash` | Fast | Low | Excellent | Complex articles |\n| `anthropic\u002Fclaude-haiku-4-5` | Fast | Medium | Excellent | High precision |\n| `openai\u002Fgpt-4o-mini` | Medium | Medium | Very good | Alternative |\n\n**Always use `temperature: 0.1` for structured extraction.** Higher values produce hallucinated entities.\n\n---\n\n## Rate Limiting and Anti-Bot\n\n### Exponential Backoff per Domain\n\n```python\nimport time, random\n\nclass RateLimiter:\n    def __init__(self, base_delay: float = 0.5, max_delay: float = 30.0):\n        self.base_delay = base_delay\n        self.max_delay = max_delay\n        self._attempts: dict[str, int] = {}\n\n    def wait(self, domain: str):\n        attempts = self._attempts.get(domain, 0)\n        delay = min(self.base_delay * (2 ** attempts), self.max_delay)\n        delay *= random.uniform(0.8, 1.2)  # jitter +\u002F-20%\n        time.sleep(delay)\n\n    def on_success(self, domain: str):\n        self._attempts[domain] = 0\n\n    def on_failure(self, domain: str):\n        self._attempts[domain] = self._attempts.get(domain, 0) + 1\n```\n\n### Rotating User-Agents\n\n```python\nUSER_AGENTS = [\n    'Mozilla\u002F5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit\u002F537.36 (KHTML, like Gecko) Chrome\u002F120.0.0.0 Safari\u002F537.36',\n    'Mozilla\u002F5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\u002F537.36 (KHTML, like Gecko) Chrome\u002F120.0.0.0 Safari\u002F537.36',\n    'Mozilla\u002F5.0 (X11; Linux x86_64) AppleWebKit\u002F537.36 (KHTML, like Gecko) Chrome\u002F120.0.0.0 Safari\u002F537.36',\n]\n```\n\n---\n\n## Incremental Saving and Checkpointing\n\nNever wait to process all URLs before saving. A crash mid-processing can lose hours of work.\n\n```python\nimport json\nfrom pathlib import Path\nfrom datetime import datetime\n\ndef save_incremental(results: list, output_path: Path, every: int = 50):\n    \"\"\"Saves results every N articles processed.\"\"\"\n    if len(results) % every == 0:\n        output_path.write_text(json.dumps(results, ensure_ascii=False, indent=2))\n\ndef load_checkpoint(output_path: Path) -> tuple[list, set]:\n    \"\"\"Loads checkpoint and returns (results, already-processed URLs).\"\"\"\n    if output_path.exists():\n        results = json.loads(output_path.read_text())\n        processed_urls = {r['url'] for r in results}\n        return results, processed_urls\n    return [], set()\n```\n\n### Output Directory Structure\n\n```\noutput\u002F\n├── {domain}\u002F\n│   ├── articles_YYYY-MM-DD.json    # full articles with text\n│   ├── entities_YYYY-MM-DD.json    # entities only (for quick analysis)\n│   └── failed_YYYY-MM-DD.json      # failed URLs (for retry)\n```\n\n---\n\n## Result Schema\n\nEvery result MUST include quality and provenance metadata:\n\n```python\ndef build_result(url: str, content: dict, entities: dict, method: str) -> dict:\n    return {\n        'url': url,\n        'method': method,                     # static|playwright|scrapy|failed\n        'paywall': content.get('paywall', 'none'),\n        'data_quality': _assess_quality(content, entities),\n        'title': content.get('title'),\n        'author': content.get('author'),\n        'date_published': content.get('date_published'),\n        'word_count': len((content.get('text') or '').split()),\n        'text': content.get('text'),\n        'entities': entities,\n        'schema': content.get('schema', {}),\n        'crawled_at': datetime.now().isoformat(),\n    }\n\ndef _assess_quality(content: dict, entities: dict) -> str:\n    text = content.get('text') or ''\n    has_text = len(text.split()) >= 100\n    has_entities = any(entities.get(k) for k in ['people', 'organizations'])\n    has_meta = bool(content.get('title') and content.get('date_published'))\n\n    if has_text and has_entities and has_meta:\n        return 'high'\n    elif has_text or has_entities:\n        return 'medium'\n    return 'low'\n```\n\n---\n\n## Python Dependencies\n\n```bash\npip install \\\n  requests \\\n  beautifulsoup4 \\\n  lxml html5lib \\\n  scrapy \\\n  playwright \\\n  trafilatura \\\n  pyyaml \\\n  python-dateutil\n\n# Chromium browser for Playwright\nplaywright install chromium\n```\n\n| Library | Min version | Responsibility |\n|---|---|---|\n| `requests` | 2.31+ | Static HTTP, API calls |\n| `beautifulsoup4` | 4.12+ | Tolerant HTML parsing |\n| `lxml` | 4.9+ | Robust alternative parser |\n| `html5lib` | 1.1+ | Ultra-tolerant parser (broken HTML) |\n| `scrapy` | 2.11+ | Parallel crawling at scale |\n| `playwright` | 1.40+ | JS\u002FSPA rendering |\n| `trafilatura` | 1.8+ | Article extraction (boilerplate removal) |\n| `pyyaml` | 6.0+ | Declarative extraction config |\n| `python-dateutil` | 2.9+ | Multi-format date parsing |\n\n---\n\n## Best Practices (DO)\n\n- **Cascade methods:** always try lightest first (static -> playwright)\n- **Incremental save:** save every 50 articles to avoid losing progress on crash\n- **Resume mode:** check already-processed URLs before starting (`load_checkpoint`)\n- **Rate limiting:** minimum 0.5s between requests on same domain; exponential backoff on failures\n- **Document quality:** include `data_quality` and `method` in every result\n- **Separation of concerns:** crawling -> cleaning -> entities (never all at once)\n- **Declarative config:** use YAML for CSS selectors, not hard-coded Python\n- **Graceful fallback:** if LLM fails, return empty structure with `error` field — never raise unhandled exceptions\n- **Clean text for LLM:** always pass extracted and normalized text, never raw HTML\n\n## Anti-Patterns (AVOID)\n\n- Passing raw HTML to the LLM (wastes tokens, lower entity precision)\n- Using only regex for entity extraction (fragile for natural text variations)\n- Hard-coding CSS selectors in Python (sites change layouts frequently)\n- Ignoring encoding (UTF-8 vs Latin-1 causes silent data corruption)\n- Infinite retries (use exponential backoff with max attempt limit)\n- Processing all pages before saving (risk of losing everything on crash)\n- Mixing score scales without explicit normalization (e.g., 0-1 vs 0-100)\n- Using `wait_until='load'` in Playwright for lazy content (use `'networkidle'`)\n\n---\n\n## Safety Rules\n\n- NEVER scrape pages behind authentication without explicit user approval.\n- ALWAYS respect `robots.txt` (Scrapy does this by default; for requests\u002FPlaywright, check manually).\n- ALWAYS implement rate limiting — minimum 0.5s between requests to the same domain.\n- NEVER store API keys in generated scripts — always use `os.environ.get()`.\n- NEVER bypass hard paywalls — extract only publicly available content.\n- For soft paywalls, only reveal content that was already sent to the client (DOM manipulation only, no server-side bypass).\n","# Web Scraper\n\nYou 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.\n\n**Credential scope:** `OPENROUTER_API_KEY` is used in generated Python scripts to call the OpenRouter API for LLM-based entity extraction (Stage 5). The skill references this variable in template code only — it never makes direct API calls itself. All other operations (HTTP requests, HTML parsing, Playwright rendering) require no credentials.\n\n## Planning Protocol (MANDATORY — execute before ANY action)\n\nBefore writing any scraping script or running any command, you MUST complete this planning phase:\n\n1. **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).\n\n2. **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) `.env.example` for expected API keys. Do NOT read `.env`, `.env.local`, or any file containing actual credential values.\n\n3. **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.\n\n4. **Choose the extraction strategy.** Use the decision tree in the \"Strategy Selection\" section. Document your reasoning.\n\n5. **Build an execution plan.** Write out: (a) which stages of the pipeline apply, (b) which Python modules to create\u002Fmodify, (c) estimated time and resource usage, (d) output file structure.\n\n6. **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.\n\n7. **Execute sequentially.** Follow the pipeline stages in order. Verify each stage output before proceeding.\n\n8. **Summarize.** Report: pages processed, success\u002Ffailure counts, data quality distribution, and any manual steps remaining.\n\nDo NOT skip this protocol. A rushed scraping job wastes tokens, gets IP-blocked, and produces garbage data.\n\n---\n\n## Architecture — 5-Stage Pipeline\n\n```\nURL or Domain\n    |\n    v\n[STAGE 1] News\u002FArticle Detection\n    |-- URL pattern analysis (\u002FYYYY\u002FMM\u002FDD\u002F, \u002Fnews\u002F, \u002Farticle\u002F)\n    |-- Schema.org detection (NewsArticle, Article, BlogPosting)\n    |-- Meta tag analysis (og:type = \"article\")\n    |-- Content heuristics (byline, pub date, paragraph density)\n    |-- Output: score 0-1 (threshold >= 0.4 to proceed)\n    |\n    v\n[STAGE 2] Multi-Strategy Content Extraction (cascade)\n    |-- Attempt 1: requests + BeautifulSoup (30s timeout)\n    |       -> content sufficient? -> Stage 3\n    |-- Attempt 2: Playwright headless Chromium (JS rendering)\n    |       -> always passes to Stage 3\n    |-- Attempt 3: Scrapy (if bulk crawl of many pages on same domain)\n    |-- All failed -> mark as 'failed', save URL for retry\n    |\n    v\n[STAGE 3] Cleaning and Normalization\n    |-- Boilerplate removal (trafilatura: nav, footer, sidebar, ads)\n    |-- Main article text extraction\n    |-- Encoding normalization (NFKC, control chars, whitespace)\n    |-- Chunking for LLM (if text > 3000 chars)\n    |\n    v\n[STAGE 4] Structured Metadata Extraction\n    |-- Author\u002Fbyline (Schema.org Person, rel=author, meta author)\n    |-- Publication date (article:published_time, datePublished)\n    |-- Category\u002Fsection (breadcrumb, articleSection)\n    |-- Tags and keywords\n    |-- Paywall detection (hard, soft, none)\n    |\n    v\n[STAGE 5] Entity Extraction (LLM) — optional\n    |-- People (name, role, context)\n    |-- Organizations (companies, government, NGOs)\n    |-- Locations (cities, countries, addresses)\n    |-- Dates and events\n    |-- Relationships between entities\n    |\n    v\n[OUTPUT] Structured JSON with quality metadata\n```\n\n---\n\n## Stage 1: News\u002FArticle Detection\n\n### 1.1 URL Pattern Heuristics\n\n```python\nimport re\nfrom urllib.parse import urlparse\n\nNEWS_URL_PATTERNS = [\n    r'\u002F\\d{4}\u002F\\d{2}\u002F\\d{2}\u002F',          # \u002F2024\u002F03\u002F15\u002F\n    r'\u002F\\d{4}\u002F\\d{2}\u002F',                  # \u002F2024\u002F03\u002F\n    r'\u002F(news|noticias|noticia|artigo|article|post)\u002F',\n    r'\u002F(blog|press|imprensa|release)\u002F',\n    r'-\\d{6,}$',                       # slug ending in numeric ID\n]\n\ndef is_news_url(url: str) -> bool:\n    path = urlparse(url).path.lower()\n    return any(re.search(p, path) for p in NEWS_URL_PATTERNS)\n```\n\n### 1.2 Schema.org Detection\n\n```python\nimport json\nfrom bs4 import BeautifulSoup\n\nNEWS_SCHEMA_TYPES = {\n    'NewsArticle', 'Article', 'BlogPosting',\n    'ReportageNewsArticle', 'AnalysisNewsArticle',\n    'OpinionNewsArticle', 'ReviewNewsArticle'\n}\n\ndef has_news_schema(html: str) -> bool:\n    soup = BeautifulSoup(html, 'html.parser')\n    for tag in soup.find_all('script', type='application\u002Fld+json'):\n        try:\n            data = json.loads(tag.string or '{}')\n            items = data.get('@graph', [data])  # supports WordPress\u002FYoast @graph\n            for item in items:\n                if item.get('@type') in NEWS_SCHEMA_TYPES:\n                    return True\n        except json.JSONDecodeError:\n            continue\n    return False\n```\n\n### 1.3 Content Heuristic Score\n\n```python\ndef news_content_score(html: str) -> float:\n    \"\"\"Returns 0-1 probability of being a news article.\"\"\"\n    soup = BeautifulSoup(html, 'html.parser')\n    score = 0.0\n\n    # Has byline\u002Fauthor?\n    if soup.select('[rel=\"author\"], .byline, .author, [itemprop=\"author\"]'):\n        score += 0.3\n\n    # Has publication date?\n    if soup.select('time[datetime], [itemprop=\"datePublished\"], [property=\"article:published_time\"]'):\n        score += 0.3\n\n    # og:type = article?\n    og_type = soup.find('meta', property='og:type')\n    if og_type and 'article' in (og_type.get('content', '')).lower():\n        score += 0.2\n\n    # Has substantial text paragraphs?\n    paragraphs = [p.get_text() for p in soup.find_all('p') if len(p.get_text()) > 100]\n    if len(paragraphs) >= 3:\n        score += 0.2\n\n    return min(score, 1.0)\n```\n\n**Decision rule:** score >= 0.4 = proceed; score \u003C 0.4 = discard or flag as uncertain.\n\n---\n\n## Stage 2: Multi-Strategy Content Extraction\n\n**Golden rule:** always try the lightest method first. Escalate only when content is insufficient.\n\n### Strategy Selection Decision Tree\n\n| Condition | Strategy | Why |\n|---|---|---|\n| Static HTML, RSS, sitemap | `requests` + `BeautifulSoup` | Fast, lightweight, no overhead |\n| Bulk crawl (50+ pages, same domain) | `scrapy` | Native concurrency, retry, pipeline |\n| SPA, JS-rendered, lazy-loaded content | `playwright` (Chromium headless) | Renders full DOM after JS execution |\n| All methods fail | Mark as `failed`, save for retry | Never silently drop URLs |\n\n### 2.1 Static HTTP (default — try first)\n\n```python\nimport requests\nfrom bs4 import BeautifulSoup\nfrom typing import Optional\n\nHEADERS = {\n    'User-Agent': 'Mozilla\u002F5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit\u002F537.36',\n    'Accept': 'text\u002Fhtml,application\u002Fxhtml+xml,application\u002Fxml;q=0.9,*\u002F*;q=0.8',\n    'Accept-Language': 'pt-BR,pt;q=0.9,en-US;q=0.8',\n}\n\ndef fetch_static(url: str, timeout: int = 30) -> Optional[dict]:\n    try:\n        session = requests.Session()\n        resp = session.get(url, headers=HEADERS, timeout=timeout, allow_redirects=True)\n        resp.raise_for_status()\n        soup = BeautifulSoup(resp.content, 'html.parser')\n        return {\n            'html': resp.text,\n            'soup': soup,\n            'status': resp.status_code,\n            'final_url': resp.url,\n            'method': 'static',\n        }\n    except (requests.exceptions.Timeout, requests.exceptions.RequestException):\n        return None\n```\n\n### 2.2 JS Detection — When to Escalate to Playwright\n\n```python\ndef needs_js_rendering(static_result: dict) -> bool:\n    \"\"\"Detects if the page needs JS to render content.\"\"\"\n    if not static_result:\n        return True\n    soup = static_result.get('soup')\n    if not soup:\n        return True\n\n    # SPA framework markers\n    spa_markers = [\n        soup.find(id='root'),\n        soup.find(id='app'),\n        soup.find(id='__next'),   # Next.js\n        soup.find(id='__nuxt'),   # Nuxt\n    ]\n    has_spa_root = any(m for m in spa_markers\n                       if m and len(m.get_text(strip=True)) \u003C 50)\n\n    # Many external scripts but little text\n    scripts = len(soup.find_all('script', src=True))\n    text_length = len(soup.get_text(strip=True))\n\n    return has_spa_root or (scripts > 10 and text_length \u003C 500)\n```\n\n### 2.3 Playwright (JS rendering)\n\n```python\nfrom playwright.async_api import async_playwright\nimport asyncio\n\nBLOCKED_RESOURCE_PATTERNS = [\n    '**\u002F*.{png,jpg,jpeg,gif,webp,avif,svg,woff,woff2,ttf,eot}',\n    '**\u002Fgoogle-analytics.com\u002F**',\n    '**\u002Fdoubleclick.net\u002F**',\n    '**\u002Ffacebook.com\u002Ftr*',\n    '**\u002Fads.*.com\u002F**',\n]\n\nasync def fetch_with_playwright(url: str, timeout_ms: int = 30_000) -> Optional[dict]:\n    async with async_playwright() as p:\n        browser = await p.chromium.launch(headless=True)\n        context = await browser.new_context(\n            viewport={'width': 1280, 'height': 800},\n            user_agent=HEADERS['User-Agent'],\n            java_script_enabled=True,\n        )\n        # Block images, fonts, trackers to speed up extraction\n        for pattern in BLOCKED_RESOURCE_PATTERNS:\n            await context.route(pattern, lambda r: r.abort())\n\n        page = await context.new_page()\n        try:\n            await page.goto(url, wait_until='networkidle', timeout=timeout_ms)\n            await page.wait_for_timeout(2000)  # wait for lazy JS content injection\n\n            html = await page.content()\n            text = await page.evaluate('''() => {\n                const remove = [\"script\",\"style\",\"nav\",\"footer\",\"aside\",\"iframe\",\"noscript\"];\n                remove.forEach(t => document.querySelectorAll(t).forEach(el => el.remove()));\n                return document.body?.innerText || \"\";\n            }''')\n\n            return {\n                'html': html,\n                'text': text,\n                'status': 200,\n                'final_url': page.url,\n                'method': 'playwright',\n            }\n        except Exception as e:\n            return {'error': str(e), 'method': 'playwright'}\n        finally:\n            await browser.close()\n```\n\n**Performance tip:** for bulk processing, reuse the browser process. Create new contexts per URL instead of relaunching the browser.\n\n### 2.4 Scrapy Settings (bulk crawl)\n\n```python\nSCRAPY_SETTINGS = {\n    'CONCURRENT_REQUESTS': 5,\n    'DOWNLOAD_DELAY': 0.5,\n    'COOKIES_ENABLED': True,\n    'ROBOTSTXT_OBEY': True,\n    'DEFAULT_REQUEST_HEADERS': HEADERS,\n    'RETRY_TIMES': 2,\n    'RETRY_HTTP_CODES': [500, 502, 503, 429],\n}\n```\n\n### 2.5 Cascade Orchestrator\n\n```python\nasync def extract_page_content(url: str) -> dict:\n    \"\"\"Tries methods in ascending order of cost.\"\"\"\n\n    # 1. Static (fast, lightweight)\n    result = fetch_static(url)\n    if result and is_content_sufficient(result):\n        return enrich_result(result, url)\n\n    # 2. Playwright (JS rendering)\n    if not result or needs_js_rendering(result):\n        result = await fetch_with_playwright(url)\n        if result and 'error' not in result:\n            return enrich_result(result, url)\n\n    return {'url': url, 'error': 'all_methods_failed', 'content': None}\n\ndef is_content_sufficient(result: dict) -> bool:\n    \"\"\"Checks if extracted content is useful (min 200 words).\"\"\"\n    soup = result.get('soup')\n    if not soup:\n        return False\n    text = soup.get_text(separator=' ', strip=True)\n    return len(text.split()) >= 200\n```\n\n---\n\n## Stage 3: Cleaning and Normalization\n\n### 3.1 Main Content Extraction (boilerplate removal)\n\nUse `trafilatura` — the most accurate library for article extraction, especially for Portuguese content.\n\n```python\nimport trafilatura\n\ndef extract_main_content(html: str, url: str = '') -> Optional[str]:\n    \"\"\"Extracts article body, removing nav, ads, comments.\"\"\"\n    return trafilatura.extract(\n        html,\n        url=url,\n        include_comments=False,\n        include_tables=True,\n        no_fallback=False,\n        favor_precision=True,\n    )\n\ndef extract_content_with_metadata(html: str, url: str = '') -> dict:\n    \"\"\"Extracts content + structured metadata together.\"\"\"\n    metadata = trafilatura.extract_metadata(html, default_url=url)\n    text = extract_main_content(html, url)\n    return {\n        'text': text,\n        'title': metadata.title if metadata else None,\n        'author': metadata.author if metadata else None,\n        'date': metadata.date if metadata else None,\n        'description': metadata.description if metadata else None,\n        'sitename': metadata.sitename if metadata else None,\n    }\n```\n\n**Alternative:** `newspaper3k` (simpler but less accurate for PT-BR).\n\n### 3.2 Encoding and Whitespace Normalization\n\n```python\nimport unicodedata\nimport re\n\ndef normalize_text(text: str) -> str:\n    \"\"\"Normalizes encoding, removes invisible chars, collapses whitespace.\"\"\"\n    text = unicodedata.normalize('NFKC', text)\n    text = re.sub(r'[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f\\x7f]', '', text)\n    text = re.sub(r'\\n{3,}', '\\n\\n', text)\n    text = re.sub(r' {2,}', ' ', text)\n    return text.strip()\n```\n\n### 3.3 Robust HTML Parsing (fallback parsers)\n\n```python\ndef parse_html_robust(html: str) -> BeautifulSoup:\n    \"\"\"Tries parsers in order of increasing tolerance.\"\"\"\n    for parser in ['html.parser', 'lxml', 'html5lib']:\n        try:\n            soup = BeautifulSoup(html, parser)\n            if soup.body and len(soup.get_text()) > 10:\n                return soup\n        except Exception:\n            continue\n    return BeautifulSoup(_strip_tags_regex(html), 'html.parser')\n\ndef _strip_tags_regex(html: str) -> str:\n    \"\"\"Brute-force text extraction via regex (last resort).\"\"\"\n    from html import unescape\n    html = re.sub(r'\u003Cscript[^>]*>.*?\u003C\u002Fscript>', '', html, flags=re.DOTALL | re.I)\n    html = re.sub(r'\u003Cstyle[^>]*>.*?\u003C\u002Fstyle>', '', html, flags=re.DOTALL | re.I)\n    text = re.sub(r'\u003C[^>]+>', ' ', html)\n    return unescape(normalize_text(text))\n```\n\n### 3.4 Chunking for LLM (long articles)\n\n```python\ndef chunk_for_llm(text: str, max_chars: int = 4000, overlap: int = 200) -> list[str]:\n    \"\"\"Splits text into chunks with overlap to maintain context.\"\"\"\n    if len(text) \u003C= max_chars:\n        return [text]\n\n    chunks = []\n    sentences = re.split(r'(?\u003C=[.!?])\\s+', text)\n    current_chunk = ''\n\n    for sentence in sentences:\n        if len(current_chunk) + len(sentence) \u003C= max_chars:\n            current_chunk += ' ' + sentence\n        else:\n            if current_chunk:\n                chunks.append(current_chunk.strip())\n            current_chunk = current_chunk[-overlap:] + ' ' + sentence\n\n    if current_chunk:\n        chunks.append(current_chunk.strip())\n\n    return chunks\n```\n\n---\n\n## Stage 4: Structured Metadata Extraction\n\n### 4.1 YAML-Based Configurable Extractor\n\nUse declarative YAML config so CSS selectors can be updated without changing Python code. Sites redesign layouts frequently — YAML makes maintenance trivial.\n\n**`extraction_config.yaml`:**\n\n```yaml\nversion: 1.0\n\nmeta_tags:\n  article_published:\n    selector: \"meta[property='article:published_time']\"\n    attribute: content\n    aliases:\n      - \"meta[name='publication_date']\"\n      - \"meta[name='date']\"\n  article_author:\n    selector: \"meta[name='author']\"\n    attribute: content\n    aliases:\n      - \"meta[property='article:author']\"\n  og_type:\n    selector: \"meta[property='og:type']\"\n    attribute: content\n\nauthor:\n  - name: meta_author\n    selector: \"meta[name='author']\"\n    attribute: content\n  - name: schema_author\n    selector: \"[itemprop='author']\"\n    attribute: content\n    fallback_attribute: textContent\n  - name: byline_link\n    selector: \"a[rel='author'], .byline a, .author a\"\n    attribute: textContent\n\ndates:\n  published:\n    selectors:\n      - selector: \"meta[property='article:published_time']\"\n        attribute: content\n      - selector: \"time[itemprop='datePublished']\"\n        attribute: datetime\n        fallback_attribute: textContent\n      - selector: \"[class*='date'][class*='publish']\"\n        attribute: textContent\n  modified:\n    selectors:\n      - selector: \"meta[property='article:modified_time']\"\n        attribute: content\n      - selector: \"time[itemprop='dateModified']\"\n        attribute: datetime\n\nsettings:\n  enabled:\n    meta_tags: true\n    author: true\n    dates: true\n  limits:\n    max_items: 10\n```\n\n### 4.2 Schema.org Extraction\n\n```python\ndef extract_news_schema(html: str) -> dict:\n    \"\"\"Extracts structured data specific to news articles.\"\"\"\n    soup = BeautifulSoup(html, 'html.parser')\n    result = {}\n\n    for tag in soup.find_all('script', type='application\u002Fld+json'):\n        try:\n            data = json.loads(tag.string or '{}')\n            items = data.get('@graph', [data])\n            for item in items:\n                if item.get('@type', '') in NEWS_SCHEMA_TYPES:\n                    result.update({\n                        'headline': item.get('headline'),\n                        'author': _extract_schema_author(item),\n                        'date_published': item.get('datePublished'),\n                        'date_modified': item.get('dateModified'),\n                        'description': item.get('description'),\n                        'publisher': _extract_schema_publisher(item.get('publisher', {})),\n                        'keywords': item.get('keywords', ''),\n                        'section': item.get('articleSection', ''),\n                    })\n        except (json.JSONDecodeError, AttributeError):\n            continue\n    return result\n\ndef _extract_schema_author(item: dict) -> Optional[str]:\n    author = item.get('author', {})\n    if isinstance(author, list):\n        author = author[0]\n    if isinstance(author, dict):\n        return author.get('name')\n    return str(author) if author else None\n\ndef _extract_schema_publisher(publisher: dict) -> Optional[str]:\n    if isinstance(publisher, dict):\n        return publisher.get('name')\n    return None\n```\n\n### 4.3 Paywall Detection\n\n```python\ndef detect_paywall(html: str, text: str) -> dict:\n    \"\"\"Detects paywall type and available content.\"\"\"\n    soup = BeautifulSoup(html, 'html.parser')\n\n    paywall_signals = [\n        bool(soup.find(class_=re.compile(r'paywall|premium|subscriber|locked', re.I))),\n        bool(soup.find(attrs={'data-paywall': True})),\n        bool(soup.find(id=re.compile(r'paywall|premium', re.I))),\n    ]\n\n    paywall_text_patterns = [\n        r'assine para (ler|continuar|ver)',\n        r'conte.do exclusivo para assinantes',\n        r'subscribe to (read|continue)',\n        r'this article is for subscribers',\n    ]\n    has_paywall_text = any(re.search(p, text, re.I) for p in paywall_text_patterns)\n\n    has_paywall = any(paywall_signals) or has_paywall_text\n\n    paragraphs = soup.find_all('p')\n    visible = [p for p in paragraphs\n               if 'display:none' not in p.get('style', '')\n               and len(p.get_text()) > 50]\n\n    return {\n        'has_paywall': has_paywall,\n        'type': 'soft' if (has_paywall and len(visible) >= 2) else\n                'hard' if has_paywall else 'none',\n        'available_paragraphs': len(visible),\n    }\n```\n\n**Paywall handling:**\n\n- **Hard paywall:** content never sent to client. Extract preview (title, lead, metadata). Mark `paywall: \"hard\"` in output.\n- **Soft paywall:** content present in DOM but hidden by CSS\u002FJS. Use Playwright to remove paywall overlay and reveal paragraphs.\n- **No paywall:** proceed normally.\n\n---\n\n## Stage 5: Entity Extraction (LLM)\n\nUse the LLM **only on clean text** (output of Stage 3). NEVER pass raw HTML — it wastes tokens and reduces precision.\n\n### 5.1 Single Article Extraction\n\n```python\nimport json, time, re\nimport requests as req\n\nOPENROUTER_API_KEY = os.environ.get(\"OPENROUTER_API_KEY\", \"\")\nOPENROUTER_ENDPOINT = \"https:\u002F\u002Fopenrouter.ai\u002Fapi\u002Fv1\u002Fchat\u002Fcompletions\"\n\ndef extract_entities_llm(text: str, metadata: dict) -> dict:\n    \"\"\"Extracts entities from a news article using LLM.\"\"\"\n    text_sample = text[:4000] if len(text) > 4000 else text\n\n    prompt = f\"\"\"You are a news entity extractor. Analyze the text below and extract:\n\nTITLE: {metadata.get('title', 'N\u002FA')}\nDATE: {metadata.get('date', 'N\u002FA')}\nTEXT:\n{text_sample}\n\nRespond ONLY with valid JSON, no markdown, in this format:\n{{\n  \"people\": [\n    {{\"name\": \"Full Name\", \"role\": \"Role\u002FTitle\", \"context\": \"One sentence about their role in the article\"}}\n  ],\n  \"organizations\": [\n    {{\"name\": \"Org Name\", \"type\": \"company|government|ngo|other\", \"context\": \"role in article\"}}\n  ],\n  \"locations\": [\n    {{\"name\": \"Location Name\", \"type\": \"city|state|country|address\", \"context\": \"mention\"}}\n  ],\n  \"events\": [\n    {{\"name\": \"Event\", \"date\": \"date if available\", \"description\": \"brief description\"}}\n  ],\n  \"relationships\": [\n    {{\"subject\": \"Entity A\", \"relation\": \"relation type\", \"object\": \"Entity B\"}}\n  ]\n}}\"\"\"\n\n    try:\n        response = req.post(\n            OPENROUTER_ENDPOINT,\n            headers={\n                \"Authorization\": f\"Bearer {OPENROUTER_API_KEY}\",\n                \"Content-Type\": \"application\u002Fjson\",\n            },\n            json={\n                \"model\": \"google\u002Fgemini-2.5-flash-lite\",\n                \"messages\": [{\"role\": \"user\", \"content\": prompt}],\n                \"max_tokens\": 2000,\n                \"temperature\": 0.1,  # low for structured extraction\n            },\n            timeout=30,\n        )\n        response.raise_for_status()\n        content = response.json()['choices'][0]['message']['content']\n        content = re.sub(r'^```json\\s*|\\s*```$', '', content.strip())\n        return json.loads(content)\n    except (json.JSONDecodeError, KeyError, req.RequestException) as e:\n        return {\n            'error': str(e),\n            'people': [], 'organizations': [],\n            'locations': [], 'events': [], 'relationships': []\n        }\n    finally:\n        time.sleep(0.3)  # rate limiting between calls\n```\n\n### 5.2 Chunked Extraction (long articles)\n\n```python\ndef extract_entities_chunked(text: str, metadata: dict) -> dict:\n    \"\"\"For long articles, extract entities per chunk and merge with deduplication.\"\"\"\n    chunks = chunk_for_llm(text, max_chars=3000)\n    merged = {'people': [], 'organizations': [], 'locations': [], 'events': [], 'relationships': []}\n\n    for chunk in chunks:\n        chunk_entities = extract_entities_llm(chunk, metadata)\n        for key in merged:\n            merged[key].extend(chunk_entities.get(key, []))\n\n    # Deduplicate by name (case-insensitive)\n    for key in ['people', 'organizations', 'locations']:\n        seen = set()\n        deduped = []\n        for item in merged[key]:\n            name = item.get('name', '').lower().strip()\n            if name and name not in seen:\n                seen.add(name)\n                deduped.append(item)\n        merged[key] = deduped\n\n    return merged\n```\n\n### 5.3 Recommended LLM Models (via OpenRouter)\n\n| Model | Speed | Cost | Quality (PT-BR) | Use case |\n|---|---|---|---|---|\n| `google\u002Fgemini-2.5-flash-lite` | Very fast | Very low | Great | Bulk extraction |\n| `google\u002Fgemini-2.5-flash` | Fast | Low | Excellent | Complex articles |\n| `anthropic\u002Fclaude-haiku-4-5` | Fast | Medium | Excellent | High precision |\n| `openai\u002Fgpt-4o-mini` | Medium | Medium | Very good | Alternative |\n\n**Always use `temperature: 0.1` for structured extraction.** Higher values produce hallucinated entities.\n\n---\n\n## Rate Limiting and Anti-Bot\n\n### Exponential Backoff per Domain\n\n```python\nimport time, random\n\nclass RateLimiter:\n    def __init__(self, base_delay: float = 0.5, max_delay: float = 30.0):\n        self.base_delay = base_delay\n        self.max_delay = max_delay\n        self._attempts: dict[str, int] = {}\n\n    def wait(self, domain: str):\n        attempts = self._attempts.get(domain, 0)\n        delay = min(self.base_delay * (2 ** attempts), self.max_delay)\n        delay *= random.uniform(0.8, 1.2)  # jitter +\u002F-20%\n        time.sleep(delay)\n\n    def on_success(self, domain: str):\n        self._attempts[domain] = 0\n\n    def on_failure(self, domain: str):\n        self._attempts[domain] = self._attempts.get(domain, 0) + 1\n```\n\n### Rotating User-Agents\n\n```python\nUSER_AGENTS = [\n    'Mozilla\u002F5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit\u002F537.36 (KHTML, like Gecko) Chrome\u002F120.0.0.0 Safari\u002F537.36',\n    'Mozilla\u002F5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\u002F537.36 (KHTML, like Gecko) Chrome\u002F120.0.0.0 Safari\u002F537.36',\n    'Mozilla\u002F5.0 (X11; Linux x86_64) AppleWebKit\u002F537.36 (KHTML, like Gecko) Chrome\u002F120.0.0.0 Safari\u002F537.36',\n]\n```\n\n---\n\n## Incremental Saving and Checkpointing\n\nNever wait to process all URLs before saving. A crash mid-processing can lose hours of work.\n\n```python\nimport json\nfrom pathlib import Path\nfrom datetime import datetime\n\ndef save_incremental(results: list, output_path: Path, every: int = 50):\n    \"\"\"Saves results every N articles processed.\"\"\"\n    if len(results) % every == 0:\n        output_path.write_text(json.dumps(results, ensure_ascii=False, indent=2))\n\ndef load_checkpoint(output_path: Path) -> tuple[list, set]:\n    \"\"\"Loads checkpoint and returns (results, already-processed URLs).\"\"\"\n    if output_path.exists():\n        results = json.loads(output_path.read_text())\n        processed_urls = {r['url'] for r in results}\n        return results, processed_urls\n    return [], set()\n```\n\n### Output Directory Structure\n\n```\noutput\u002F\n├── {domain}\u002F\n│   ├── articles_YYYY-MM-DD.json    # full articles with text\n│   ├── entities_YYYY-MM-DD.json    # entities only (for quick analysis)\n│   └── failed_YYYY-MM-DD.json      # failed URLs (for retry)\n```\n\n---\n\n## Result Schema\n\nEvery result MUST include quality and provenance metadata:\n\n```python\ndef build_result(url: str, content: dict, entities: dict, method: str) -> dict:\n    return {\n        'url': url,\n        'method': method,                     # static|playwright|scrapy|failed\n        'paywall': content.get('paywall', 'none'),\n        'data_quality': _assess_quality(content, entities),\n        'title': content.get('title'),\n        'author': content.get('author'),\n        'date_published': content.get('date_published'),\n        'word_count': len((content.get('text') or '').split()),\n        'text': content.get('text'),\n        'entities': entities,\n        'schema': content.get('schema', {}),\n        'crawled_at': datetime.now().isoformat(),\n    }\n\ndef _assess_quality(content: dict, entities: dict) -> str:\n    text = content.get('text') or ''\n    has_text = len(text.split()) >= 100\n    has_entities = any(entities.get(k) for k in ['people', 'organizations'])\n    has_meta = bool(content.get('title') and content.get('date_published'))\n\n    if has_text and has_entities and has_meta:\n        return 'high'\n    elif has_text or has_entities:\n        return 'medium'\n    return 'low'\n```\n\n---\n\n## Python Dependencies\n\n```bash\npip install \\\n  requests \\\n  beautifulsoup4 \\\n  lxml html5lib \\\n  scrapy \\\n  playwright \\\n  trafilatura \\\n  pyyaml \\\n  python-dateutil\n\n# Chromium browser for Playwright\nplaywright install chromium\n```\n\n| Library | Min version | Responsibility |\n|---|---|---|\n| `requests` | 2.31+ | Static HTTP, API calls |\n| `beautifulsoup4` | 4.12+ | Tolerant HTML parsing |\n| `lxml` | 4.9+ | Robust alternative parser |\n| `html5lib` | 1.1+ | Ultra-tolerant parser (broken HTML) |\n| `scrapy` | 2.11+ | Parallel crawling at scale |\n| `playwright` | 1.40+ | JS\u002FSPA rendering |\n| `trafilatura` | 1.8+ | Article extraction (boilerplate removal) |\n| `pyyaml` | 6.0+ | Declarative extraction config |\n| `python-dateutil` | 2.9+ | Multi-format date parsing |\n\n---\n\n## Best Practices (DO)\n\n- **Cascade methods:** always try lightest first (static -> playwright)\n- **Incremental save:** save every 50 articles to avoid losing progress on crash\n- **Resume mode:** check already-processed URLs before starting (`load_checkpoint`)\n- **Rate limiting:** minimum 0.5s between requests on same domain; exponential backoff on failures\n- **Document quality:** include `data_quality` and `method` in every result\n- **Separation of concerns:** crawling -> cleaning -> entities (never all at once)\n- **Declarative config:** use YAML for CSS selectors, not hard-coded Python\n- **Graceful fallback:** if LLM fails, return empty structure with `error` field — never raise unhandled exceptions\n- **Clean text for LLM:** always pass extracted and normalized text, never raw HTML\n\n## Anti-Patterns (AVOID)\n\n- Passing raw HTML to the LLM (wastes tokens, lower entity precision)\n- Using only regex for entity extraction (fragile for natural text variations)\n- Hard-coding CSS selectors in Python (sites change layouts frequently)\n- Ignoring encoding (UTF-8 vs Latin-1 causes silent data corruption)\n- Infinite retries (use exponential backoff with max attempt limit)\n- Processing all pages before saving (risk of losing everything on crash)\n- Mixing score scales without explicit normalization (e.g., 0-1 vs 0-100)\n- Using `wait_until='load'` in Playwright for lazy content (use `'networkidle'`)\n\n---\n\n## Safety Rules\n\n- NEVER scrape pages behind authentication without explicit user approval.\n- ALWAYS respect `robots.txt` (Scrapy does this by default; for requests\u002FPlaywright, check manually).\n- ALWAYS implement rate limiting — minimum 0.5s between requests to the same domain.\n- NEVER store API keys in generated scripts — always use `os.environ.get()`.\n- NEVER bypass hard paywalls — extract only publicly available content.\n- For soft paywalls, only reveal content that was already sent to the client (DOM manipulation only, no server-side bypass).\n",{"name":5,"description":7,"user-invocable":24},true,"main","f9d3fe7cf9ac8f1ea63a0d96e98e1f510a3814db","skills\u002Fguifav\u002Fweb-scraper",1,"https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills","https:\u002F\u002Fgithub.com\u002Fjavimosch","intrane.fr","Building robust, open-source infrastructure for the commons. AI-leveraged, self-hosted, built to last.","2026-06-07 03:34:58",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":24},[36,39,42],{"tool":37,"command":38},"npx","npx skills add javimosch\u002Fopen-claw-skills --skill web-scraper",{"tool":40,"command":41},"bunx","bunx skills add javimosch\u002Fopen-claw-skills --skill web-scraper",{"tool":43,"command":44},"pnpm","pnpm dlx skills add javimosch\u002Fopen-claw-skills --skill web-scraper","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fguifav\u002Fweb-scraper\u002FSKILL.md",[],[48,56,63,70,77,84],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":55},"01M778GGXG2VQ0YF31W2MKGMQZ","crowd-prompting","A marketplace where AI agents improve prompts, system instructions, tool descriptions, and other text-based content with domain expertise from real-world operations — and earn tokens for valuable contributions.","https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzzadrian\u002Fcrowd-prompting\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":55},"01M778G7BH8SBJ9FJ6C3G7CB1K","ceaser","Interact with the Ceaser privacy protocol on Base L2 using the ceaser-mcp MCP tools. This skill uses the ceaser-mcp npm package for ALL operations -- shield, unshield, note management, and protocol queries. All ceaser tool calls use CLI subcommands (npx -y ceaser-mcp \u003Csubcommand>). Ceaser is a privacy-preserving ETH wrapper using Noir\u002FUltraHonk zero-knowledge proofs on Base L2 (chain ID 8453).","https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzyra-v21\u002Fceaser\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":55},"01M778FYCJQZWFKKX5FYMK3S47","ceaser-send","Fully automated private ETH transfer via Ceaser Protocol on Base L2 using the ceaser-mcp MCP tools. This skill uses the ceaser-mcp npm package for ALL operations -- all ceaser tool calls use CLI subcommands (npx -y ceaser-mcp \u003Csubcommand>). WARNING -- creates observable on-chain links between user wallet and hot wallet (see Privacy Warning). Generates an ephemeral hot wallet with BIP-39 mnemonic recovery, user funds it, agent signs and broadcasts the Shield TX automatically. Exactly one manual step required (funding the hot wallet with ETH). Uses Noir\u002FUltraHonk zero-knowledge proofs.","https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzyra-v21\u002Fceaser-send\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":55},"01M778FQQNSEYA3HJKZBPQ4M9Z","dilemm-ai","Compete in DilemmAI, the prisoner's dilemma AI arena at dilemm.ai. Use when an OpenClaw agent wants to create an account, design and submit strategy prompts for their bot, enter matchmaking, analyze historical matches and leaderboards, and iterate on bot strategy. Requires headless browser automation (no API available yet).","https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzyori\u002Fdilemm-ai\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":55},"01M778FGVZX7QA2TF9BFMM37FY","moldium","Post and manage content on the Moldium blog platform. Triggered by \"post to Moldium\", \"write a blog post\", \"publish an article\", etc.","https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzyom45\u002Fmoldium\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":55},"01M778F88D8PQ9MQ0KNW2TJ8ZH","arxiv-paper-reviews","Interact with arXiv Crawler API to fetch papers, read reviews, submit comments, search papers, and import papers. Use when working with arXiv papers, fetching paper lists by date\u002Fcategory\u002Finterest, viewing paper details with comments, submitting paper reviews, searching papers by title, or importing papers from arXiv URLs via API at http:\u002F\u002Fweakaccept.top:8000\u002F.","https:\u002F\u002Fgithub.com\u002Fjavimosch\u002Fopen-claw-skills\u002Fblob\u002Fmain\u002Fskills\u002Fzxrys\u002Farxiv-paper-reviews\u002FSKILL.md",[],[]]