"""网页抓取工具:拉取 URL 正文并转成纯文本(不依赖第三方库)。""" import html import os import re import sys import urllib.request sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from _protocol import serve # noqa: E402 TOOL = { "name": "web_fetch", "description": "抓取一个网页或接口返回的文本内容(自动去 HTML 标签)。需要看某个链接里的内容时使用。", "parameters": { "type": "object", "properties": { "url": {"type": "string", "description": "要抓取的 http/https 地址"}, "max_chars": {"type": "number", "description": "最多返回多少字符,默认 4000,上限 20000"}, }, "required": ["url"], }, } SCRIPT_RE = re.compile(r"<(script|style|noscript)[^>]*>.*?", re.S | re.I) TAG_RE = re.compile(r"<[^>]+>") SPACE_RE = re.compile(r"[ \t\r\f\v]+") BLANK_RE = re.compile(r"\n{3,}") def strip_html(raw): text = SCRIPT_RE.sub(" ", raw) text = re.sub(r"", "\n", text, flags=re.I) text = re.sub(r"", "\n", text, flags=re.I) text = TAG_RE.sub(" ", text) text = html.unescape(text) text = SPACE_RE.sub(" ", text) text = "\n".join(line.strip() for line in text.split("\n")) return BLANK_RE.sub("\n\n", text).strip() def run(args): url = str(args.get("url", "")).strip() if not url.startswith(("http://", "https://")): raise ValueError("url 必须是 http/https 开头") limit = max(200, min(20000, int(args.get("max_chars", 4000) or 4000))) req = urllib.request.Request( url, headers={ "User-Agent": "Mozilla/5.0 (compatible; doubao-kernel/0.1)", "Accept": "text/html,application/json;q=0.9,*/*;q=0.8", }, ) with urllib.request.urlopen(req, timeout=25) as resp: charset = resp.headers.get_content_charset() or "utf-8" raw = resp.read(2_000_000).decode(charset, errors="replace") content_type = resp.headers.get("Content-Type", "") if "json" in content_type.lower(): body = raw[:limit] else: body = strip_html(raw)[:limit] return { "url": url, "content_type": content_type, "truncated": len(body) >= limit, "content": body, } if __name__ == "__main__": serve(TOOL, run)