# agent-web-fetch

Adopt this skill: https://proskills.md/skills/other/mrlong0129-agent-web-fetch-skill

Page: https://proskills.md/skills/other/mrlong0129-agent-web-fetch-skill
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: skill/SKILL.md
size: 8320
sha: 870239ce0b5e09a03db825177aa06b25754bb4da
upstream: https://github.com/mrlong0129/agent-web-fetch/blob/main/skill/SKILL.md

````text
---
name: agent-web-fetch
description: Read a public web page reliably and honestly. Use whenever the user gives you a URL to read, summarise, or extract from (articles, blog posts, WeChat 公众号 links, GitHub repos, X posts, JS-heavy pages). Escalates from a plain request to client rotation, structured-data extraction, alternates (AMP/RSS) and a headless browser only when blocked, and reports exactly why a page could not be read instead of bypassing logins, paywalls or CAPTCHAs.
---

# Reading the web: the escalation playbook

Goal: get the real content of a public page with the least effort and the fewest requests, and if you cannot, tell the user precisely why. Never summarise a verification page, login page or error page as if it were the article.

## 0. If the `awf` tool is available, use it

- MCP: call `fetch_page(url)`; for HTML you already have, `extract_from_html(html, url)`.
- CLI: `awf fetch <url> --format json` (or `--format md`). Exit code 2 means blocked/empty; the reason is in `blocked_reason`.
- Not installed but `uv` is available? Run it with zero install/config: `uvx --from git+https://github.com/mrlong0129/agent-web-fetch awf fetch <url> --format json`.
- Check `ok`. If `ok` is false, read `blocked_reason` and `fetch_attempts`, then follow "When you are blocked" below.
- `extraction_method` tells you where the text came from; `meta` means you only got a summary, so say so.

Everything below is the same strategy done by hand (with `curl`, a fetch tool, or a browser tool), for when the package is not installed.

## 1. Use a public API when the site has one (cheapest, most reliable)

- GitHub repo: `https://api.github.com/repos/{owner}/{repo}/readme` with header `Accept: application/vnd.github.raw`, or `https://raw.githubusercontent.com/{owner}/{repo}/HEAD/README.md`.
- X/Twitter single post: `https://cdn.syndication.twimg.com/tweet-result?id={id}&token=a` (JSON), fallback `https://publish.twitter.com/oembed?url=https://twitter.com/i/status/{id}`. Profiles, timelines and search need login: report that, do not scrape x.com.
- Prefer a site's RSS/Atom feed for blogs when the HTML is hard to read.

## 2. One plain request that looks like a normal browser

Send a coherent header set, not a library default (`python-requests` and empty UAs are often refused):

```
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8
```

Most public pages succeed here.

## 3. Check what you actually got (after EVERY request)

Look at the status code, the `<title>`, and how much visible text there is. If the page is short and says any of these, it is not the content:

| Signal | Meaning | What to do |
|---|---|---|
| title "Just a moment...", `cf-mitigated: challenge`, `/cdn-cgi/challenge-platform` on a near-empty 403/503 page | Cloudflare challenge | try another client; a real browser may pass it |
| reCAPTCHA / hCaptcha / Turnstile / GeeTest / DataDome (`captcha-delivery.com`) / TCaptcha | CAPTCHA | stop; never solve or outsource a CAPTCHA; report |
| "环境异常", "完成验证后即可继续访问", "unusual traffic", "verify you are human" | verification wall | try another client once; otherwise report |
| HTTP 401, redirect to `/login`, "sign in to continue", password form on an empty page, "请登录" | login required | stop; ask the user to open it or paste the content |
| "subscribe to continue reading", JSON-LD `isAccessibleForFree: false` with a teaser | paywall | stop; report |
| HTTP 429, "too many requests", `Retry-After` | rate limited | wait `Retry-After` (if short) then retry once; otherwise report |
| HTTP 404/410, or 200 with title "Page not found" | not found / soft 404 | stop; report |
| "该内容已被发布者删除", "此内容因违规无法查看", "post was deleted" | content removed | stop; report |
| almost no text, `<div id="root"></div>` / `<div id="__next"></div>`, many scripts | JavaScript shell | go to step 5 first, then 6 |

Caution: an article that merely mentions "captcha" or "login" is fine. Only trust these signals when the page has little real text. Cloudflare injects `challenge-platform` scripts into many normal pages too.

## 4. Blocked for a retryable reason? Change the client, politely

Try, in order, with a pause of at least 1 second between requests to the same site:

1. Mobile Safari: `Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1`, plus `Referer: https://<same-site>/`
2. Android Chrome.
3. An in-app browser if the content was made for one. WeChat articles (`mp.weixin.qq.com/s/...`) are built for WeChat's browser, so for them start with:
   `Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.47(0x18002f2f) NetType/WIFI Language/zh_CN` with `Accept-Language: zh-CN,zh;q=0.9`.
   A different network egress (e.g. your own machine instead of a cloud fetch service) also often helps.

Do NOT impersonate search-engine crawlers (Googlebot etc.), forge cookies or tokens, or reuse someone's logged-in session. Do not retry non-retryable verdicts (CAPTCHA, login, paywall, 404, removed): a different client will get the same answer.

## 5. Extract with several strategies and keep the richest

The visible HTML is not the only place text lives. Check all of these and keep the longest real body:

1. Main content (readability-style): the `<article>` / main text block without nav, footer, ads.
2. JSON-LD: `<script type="application/ld+json">` objects of type `NewsArticle`, `Article`, `BlogPosting` often contain the full `articleBody` (also check inside `@graph`).
3. Embedded JS state: `<script id="__NEXT_DATA__">` (Next.js, look under `props.pageProps`), `__NUXT__` / `__NUXT_DATA__`, `window.__INITIAL_STATE__`, `__APOLLO_STATE__`, YouTube `ytInitialPlayerResponse` (`videoDetails.shortDescription`). Look for long prose under keys like `content`, `body`, `articleBody`, `html`, `text`, `description`.
4. Meta: `og:title`, `og:description`, `twitter:description`, `article:published_time`, `author`. Usually only a summary: label it as such.
5. Site rules. WeChat: long articles are in `#js_content` (images in `data-src`); short text posts have an empty `#js_content` and the full text in the JS variable `content_noencode` (decode `\x0a` etc.) and often in `og:title`. Author is `author`, account name `nick_name`, time `ori_create_time` (Unix seconds) or `create_time` (China time, +08:00).

If the result is still thin, try the page's AMP version (`<link rel="amphtml">`) and its RSS/Atom feed (`<link rel="alternate" type="application/rss+xml">`), matching the entry by URL.

Tell the user which source you used when it matters ("from the page's structured data", "only the meta description was available").

## 6. Last resort: a real (headless) browser

If you have a browser tool and the failure was retryable (JS shell, Cloudflare wait page, thin content), open the page like a normal visitor, wait for it to settle, scroll once, then run steps 3 and 5 on the rendered HTML. If a CAPTCHA or login is still shown, stop and report. Never click through CAPTCHAs.

## When you are blocked

Tell the user plainly, in one or two sentences: what you tried, what you hit, and what they can do. Examples:

- "That page is behind a login (it redirected me to the sign-in page), so I can't read it. If you paste the text or a screenshot, I'll work from that."
- "Reuters showed me a DataDome CAPTCHA. I don't solve CAPTCHAs; could you open it and paste the article?"
- "WeChat returned its '环境异常' verification page. Sending the article text or opening it in WeChat and sharing the content would work."

Never present a block page, cookie banner or error text as the article's content.

## Responsible use

Only public content. Respect robots.txt (always for crawls, batch jobs and schedules; for a single link the user handed you, note it if robots.txt disallows), the site's terms, rate limits (≥1 s between requests to one site, back off on 429/503), and copyright (summarise and cite; don't republish whole articles).
````

## File: README.md
upstream: https://github.com/mrlong0129/agent-web-fetch/blob/main/README.md

````text
# agent-web-fetch

> 给 AI Agent 用的网页读取工具：**先用最便宜的办法，被挡住了才升级；读不到时，明确告诉你为什么。**
>
> A web-reading toolkit for AI agents: cheapest first, escalate only when blocked, and always report *why* a page could not be read.

[English](#english) · Python 库 · CLI (`awf`) · MCP Server (`awf-mcp`) · Agent Skill (`skill/SKILL.md`) · MIT

作者 [Yomin Ma](https://yomin.love) · GitHub [@mrlong0129](https://github.com/mrlong0129) · 姊妹项目：[wechat-article-fetcher](https://github.com/mrlong0129/wechat-article-fetcher)（专门读微信公众号文章） · [项目页](https://yomin.love/projects/agent-web-fetch/)

## Quick start for agents

不用安装、不用配置，复制一行就能用（需要 [uv](https://docs.astral.sh/uv/)；默认行为零配置）：

```bash
# 1) 直接读一个网页（不安装）
uvx --from git+https://github.com/mrlong0129/agent-web-fetch awf fetch <url>
uvx --from git+https://github.com/mrlong0129/agent-web-fetch awf fetch <url> --format json   # 结构化结果

# 2) Claude Code：一行注册 MCP server
claude mcp add agent-web-fetch -- uvx --from git+https://github.com/mrlong0129/agent-web-fetch awf-mcp
```

**Cursor**：写入 `~/.cursor/mcp.json`（全局）或项目里的 `.cursor/mcp.json`：

```json
{
  "mcpServers": {
    "agent-web-fetch": {
      "command": "uvx",
      "args": ["--from", "git+https://github.com/mrlong0129/agent-web-fetch", "awf-mcp"]
    }
  }
}
```

**Agent Skill**（不装包也能用，Agent 会照着手册用自己的工具读网页）：

```bash
# Claude Code
mkdir -p ~/.claude/skills/agent-web-fetch && curl -fsSL https://raw.githubusercontent.com/mrlong0129/agent-web-fetch/main/skill/SKILL.md -o ~/.claude/skills/agent-web-fetch/SKILL.md
# Cursor
mkdir -p ~/.cursor/skills/agent-web-fetch && curl -fsSL https://raw.githubusercontent.com/mrlong0129/agent-web-fetch/main/skill/SKILL.md -o ~/.cursor/skills/agent-web-fetch/SKILL.md
```

给编码 Agent 的完整说明见 [AGENTS.md](AGENTS.md)。

### 输出长什么样

```bash
awf fetch https://mp.weixin.qq.com/s/<article-id>
```

```text
---
title: "示例标题"
url: "https://mp.weixin.qq.com/s/<article-id>"
author: "示例作者"
published: "2026-10-05T23:59:51+08:00"
site_name: "示例公众号"
extraction_method: "wechat:content_noencode"
---

# 示例标题

正文（Markdown）……
```

读不到时，退出码为 `2`，stderr 里写明原因，例如 `blocked_reason: login_required`，以及每一步尝试了什么。

---

## 为什么要做这个

大多数给大模型用的"网页抓取"工具，逻辑都只有一步：发一个请求，拿到 HTML，转成文本。成功了很好；失败了，Agent 拿到的要么是一个报错，要么是一段"请完成验证"的页面文字，然后它会一本正经地"总结"这段验证页。

真实的网络不是这样的。**同一个链接，换一个"访问者"，拿到的可能完全是另一个页面**：

- 微信公众号文章：从云服务器请求，经常返回"环境异常，完成验证后即可继续访问"；用手机微信的身份请求，同一个链接返回完整文章。
- 很多新闻站：正文由 JavaScript 渲染，HTML 里只有一个空壳，但页面里藏着给搜索引擎看的 JSON-LD，里面就是全文。
- Next.js / Nuxt 站点：`<div id="__next"></div>` 是空的，正文在 `__NEXT_DATA__` 这段 JSON 里。
- YouTube：页面是重度 JS 应用，但视频标题和简介就在 `ytInitialPlayerResponse` 里。
- 有的页面压根不该读：需要登录、付费墙、验证码。这时候 Agent 最需要的不是"再试一次"，而是**知道原因**，好去问用户。

`agent-web-fetch` 把一个有经验的人读网页的思路，写成了一套 Agent 能直接调用的流程。

## 升级策略：先便宜，后昂贵

核心原则只有一句：**一条路不通就换下一条，先用最便宜的办法，不行再上更重的；每一步都检查自己拿到的到底是不是正文。**

```
 ┌──────────────────────────────────────────────────────────────────────┐
 │ 0. 站点适配器 API     GitHub README / X 公开嵌入接口        最便宜、最稳 │
 │ 1. 普通 HTTP 请求     一套真实、自洽的浏览器请求头                     │
 │ 2. 换身份重试         桌面 Chrome → 手机 Safari → Android / 微信内置浏览器│
 │                       + 同站 Referer、Accept-Language、礼貌退避重试    │
 │ 3. 每一步都做检测     Cloudflare？验证码？登录墙？付费墙？软 404？限流？ │
 │ 4. 多策略正文提取     trafilatura / readability / JSON-LD / JS 状态 /  │
 │                       og: 元数据 / 站点专用规则，挑最丰富的那个        │
 │    └ 正文太薄时        试 AMP 版本、RSS/Atom 订阅源                     │
 │ 5. 无头浏览器         Playwright（可选安装），真正把页面渲染出来   最贵 │
 └──────────────────────────────────────────────────────────────────────┘
```

### 第 0 层：能用官方/公开接口，就别解析 HTML

如果一个网站本来就提供了不需要登录的公开接口，那它永远比抓网页更快、更稳、更礼貌。

- **GitHub**：仓库地址直接走 `api.github.com` 拿 README 原文（Markdown），API 限额用完就退到 `raw.githubusercontent.com`。
- **X / Twitter**：单条推文走嵌入推文用的公开接口 `cdn.syndication.twimg.com`，不行再走官方 oEmbed。个人主页、时间线、搜索需要登录，工具会直接报告 `login_required`，不会去硬抓。

### 第 1 层：一次普通的请求，但要像个正常浏览器

很多工具默认的 User-Agent 是 `python-requests/2.x`，这本身就会被不少站点直接拒绝。我们发送的是一整套**自洽**的请求头：User-Agent、Accept、Accept-Language、`sec-ch-ua` 系列，彼此对得上，就像一个真的 Chrome。大部分公开页面在这一步就成功了，耗时几十到几百毫秒。

### 第 2 层：换一个"访问者"

被挡住时，最先要试的是换一个更合适的访问方式：

| 身份 | 适用场景 |
|---|---|
| `desktop_chrome` | 默认，绝大多数网站 |
| `mobile_safari` | 很多站点给手机版的是更轻、服务端渲染的页面 |
| `android_chrome` | 同上，另一种常见移动客户端 |
| `wechat_ios` | 微信内置浏览器。公众号文章就是为它设计的，所以微信适配器第一步就用它 |

从第二次尝试开始，会带上同站的 `Referer`（就像用户从网站首页点进来）。遇到 429 / 503 会读取 `Retry-After`，按指数退避礼貌地重试，并且对同一个站点的请求之间保持最小间隔。同一次抓取的多个尝试共享 Cookie，就像同一个浏览器会话。

### 第 3 层：每一步都检查"我拿到的到底是什么"

这是和普通抓取工具最大的区别。每次拿到响应，都会先判断它是不是正文，如果不是，给出一个机器可读的原因 `blocked_reason`：

| `blocked_reason` | 含义 | 换身份有用吗 |
|---|---|---|
| `cloudflare_challenge` | Cloudflare "Just a moment..." 等待页 | 可能（浏览器层可能通过） |
| `captcha` | reCAPTCHA / hCaptcha / Turnstile / GeeTest / DataDome / 腾讯验证码 | 否：不解、不换身份绕，立即停止并报告 |
| `verification_wall` | 环境验证页，例如微信"环境异常" | 可能 |
| `login_required` | 需要登录才能看 | 否，立即停止 |
| `paywall` | 付费墙（包括 JSON-LD 里 `isAccessibleForFree=false`） | 否，立即停止 |
| `rate_limited` | 429 或"请求过于频繁" | 稍后再试 |
| `forbidden` | 403 / 412 等，没有识别出具体的挑战页（例如风控） | 可能 |
| `not_found` / `soft_404` | 真 404，或 HTTP 200 但页面写着"找不到" | 否 |
| `content_removed` | 内容已被删除 / 违规无法查看 | 否 |
| `js_required` | 纯 JavaScript 空壳，需要浏览器渲染 | 交给浏览器层 |
| `robots_disallowed` | robots.txt 禁止，且使用了 `--robots strict` | 否 |

两条细节：

1. **关键词只在"页面很薄"时才算数**。一篇讨论验证码的技术文章不会被误判成验证码页。
2. **Cloudflare 会往很多正常页面里注入 `challenge-platform` 脚本**，所以光有这个标记不算被挡，必须同时满足"挑战状态码"或"页面几乎没有内容"。

遇到验证码、登录墙、付费墙、404、已删除这类"换谁来都一样"的情况，梯子会立刻停下来，不浪费请求，也不去绕。

### 第 4 层：多策略提取，挑最丰富的，并记录谁赢了

拿到真正的页面之后，同时跑多种提取策略（它们都在本地运行，比再发一次网络请求便宜得多）：

| 策略 | 擅长 |
|---|---|
| `trafilatura` | 通用的正文提取（readability 类算法），去掉导航、页脚、广告 |
| `readability` | Mozilla Readability 的 Python 移植，第二意见 |
| `json_ld` | 新闻站给搜索引擎准备的 `articleBody`，常常就是全文 |
| `js_state` | `__NEXT_DATA__`、`__NUXT__`、`window.__INITIAL_STATE__`、`__APOLLO_STATE__`、`ytInitialPlayerResponse` 等内嵌状态 |
| `meta` | `og:` / `twitter:` 描述，最后的兜底（通常只是摘要） |
| `wechat:*` 等 | 站点适配器自己的规则，例如公众号的 `js_content` / `content_noencode` / `og:title` |

按"文本长度 × 可信度权重"打分，选最高的。所有候选及其字数都写在 `extraction_candidates` 里，赢家写在 `extraction_method` 里，方便你调试，也方便 Agent 判断结果可不可靠。元数据（标题、作者、时间、站点名）则按字段合并：适配器 > JSON-LD > og 元数据 > trafilatura。

如果正文还是太薄，会尝试页面声明的 **AMP 版本**（`<link rel="amphtml">`），以及 **RSS/Atom 订阅源**里与当前链接匹配的那一条（订阅源本来就是给机器读的，又便宜又礼貌）。

### 第 5 层：真正打开一个浏览器

前面都不行、而且失败原因是"换个方式可能有用"的那一类时，才会启动 Playwright 无头浏览器，像普通访客一样把页面渲染出来，再走一遍检测和提取。它是可选依赖，没装就记录一条 `skipped` 然后跳过，不会报错。浏览器层**不解验证码、不做交互式挑战**；渲染后依然是验证码，就照实报告。

### 微信公众号：一个完整的例子

这个项目就是从读一篇公众号文章开始的。`wechat` 适配器把踩过的坑都写进去了：

1. 第一个尝试就用 iPhone 微信内置浏览器的 UA，`Accept-Language: zh-CN`。
2. 识别"环境异常 / 完成验证后即可继续访问"的验证页 → `verification_wall`；识别"该内容已被发布者删除""此内容因违规无法查看" → `content_removed`。
3. 长文：正文在 `#js_content` 里，图片地址在 `data-src` 里。
4. 短图文（`item_show_type=10`）：`#js_content` 是空的，全文在 `content_noencode` 这个 JS 变量里，`og:title` 里通常也有一份完整的。
5. 作者、公众号名、发布时间分别来自 `author`、`nick_name`、`ori_create_time`（没有时用 `create_time`），时间统一输出为带 `+08:00` 的 ISO 格式。

## 安装

```bash
# 从 GitHub 安装（发布到 PyPI 后可直接 pip install agent-web-fetch）
pip install "git+https://github.com/mrlong0129/agent-web-fetch"

# 可选：无头浏览器层
pip install "agent-web-fetch[browser] @ git+https://github.com/mrlong0129/agent-web-fetch"
playwright install chromium     # 或者系统里已有 Google Chrome 也可以，会自动尝试

# 不想装？用 uvx 直接跑
uvx --from git+https://github.com/mrlong0129/agent-web-fetch awf fetch https://example.com
```

需要 Python 3.10+。

## 使用

### CLI

```bash
awf fetch <url>                       # 默认输出 Markdown（带 front matter）
awf fetch <url> --format json         # 完整结构化结果
awf fetch <url> --format text         # 纯文本
awf fetch <url> --browser             # 直接用无头浏览器
awf fetch <url> --no-browser          # 永远不用浏览器
awf fetch <url> --adapter none        # 关闭站点适配器（auto | none | wechat | github | x）
awf fetch <url> --profile wechat_ios  # 指定身份（可重复，按顺序尝试）
awf fetch <url> --robots strict       # robots.txt 不允许就不抓（批量/爬取场景请用这个）
awf extract page.html --url <原链接>   # 对本地 HTML 做检测 + 提取，不联网
awf adapters                          # 列出适配器
awf reasons                           # 列出所有 blocked_reason
```

退出码：`0` 成功，`2` 被挡或没有内容（原因打印在 stderr），`1` 其他错误。

JSON 输出字段：`url`、`final_url`、`status`、`ok`、`ti
````
