如何为 AI 代理创建网页抓取工具?

林邦源 · AI 笔记 · 2026年11月15日 · 阅读时间约 4 分钟

English 繁體中文 简体中文

AI 代理可以规划、选择函数并使用答案,但它无法自己打开网页。若你问它一个它从未读过的 页面,它会说不知道,或者编出一个听起来很合理的答案。

工具(tool)就是填补这个缺口的方法:一个代理可以调用的普通 Python 函数。 本文创建代理工具箱里的网页抓取工具。它下载页面、保留可读文字、把文字存成文件,然后 返回文件名。整个工具共 31 行。

步骤 1:函数与它的说明

def scrape_webpage(url: str, file_path: str) -> str:
    """
    Fetch a webpage and save its visible text content into a .txt file.

    Args:
        url (str): The webpage URL to scrape.
        file_path (str): Destination path for the .txt file.

    Returns:
        str: The file path that was written.
    """

第一行命名函数 scrape_webpage,并列出它需要什么:url 是网址, file_path 是保存位置。结尾的 -> str 表示函数会返回文字, 这里是它写入的文件名。

三个引号之间的文字是说明字符串(docstring),它不是注释。当这个函数被 提供给代理时,说明字符串就成为模型决定是否调用它之前所读的描述。它说明工具做什么、两个 输入是什么、会返回什么,这正是模型正确使用工具所需的信息。

步骤 2:下载网页

response = requests.get(url, timeout=10)

requests 包负责从互联网下载页面。requests.get 向网站索取 url 上的页面,响应存放在 response。timeout=10 表示十秒后放弃,不再无休止地等待。若网址错误或网站拒绝,requests 会以错误 停止程序,而不是返回一个空白页面。

步骤 3:只保留可读的文字

soup = BeautifulSoup(response.text, "html.parser")
text = soup.get_text(separator="\n", strip=True)

下载回来的是 HTML,即描述页面的代码。BeautifulSoup(来自 bs4 包)把这些代码读成程序可以检查的结构,结果命名为 soup。 "html.parser" 是 Python 内置的解析器,所以不需额外安装。

get_text 丢掉所有标签,只留下文字。separator="\n" 把每段文字 放在单独一行,strip=True 移除每段文字前后的空白。结果是一个长字符串,命名为 text。

步骤 4:把文字存入文件

    with open(file_path, "w", encoding="utf-8") as file:
        file.write(text)
    return file_path

open(file_path, "w") 创建文件;若已有同名文件,则替换它。 encoding="utf-8" 是让各种语言的字母(包括中文)保持正确的设置。 file.write(text) 把文字写入文件,而缩进区块结束时 Python 会自动关闭文件, 这就是 with 的作用。

最后一行 return file_path 是代理关心的地方:函数返回文件名,让代理可以把这个 名字交给下一步。

步骤 5:调用工具并读回文件

result = scrape_webpage(
    "https://pongyuenlam.github.io/biography.html",
    "tool05_scraper.txt",
)
print(result)

with open(result, "r", encoding="utf-8") as file:
    contents = file.read()
    print(contents)

第一条语句用两个值调用工具:要读取的页面,以及要写入的文件。返回的文件名存入 result,print(result) 显示它。第二个区块用 "r" (读取)打开同一个文件,读回内容并打印,让你可以确认页面真的下载成功。

实际运行会打印以下内容,只保留首尾部分:

tool05_scraper.txt
Biography | Howard Lam, PhD
Howard Lam, PhD
Home
Biography
Research
Cases
Books
AI Notes
Links
Glossary
Biography
Howard Pong Yuen Lam (林邦源), PhD has spent over three decades turning bold ideas
    into measurable results across the boardroom and the classroom. A
    scholar, educator, and marketing strategist, he combines rigorous
    thinking, creative innovation, and hands-on leadership to lasting effect.
...
© 2026 Howard Pong Yuen LAM, PhD
Email
GitHub
Google Scholar
ORCID
LinkedIn

第一行是文件名。之后是页面的纯文字版本:共 56 行,真正的个人简介在中间,菜单与页脚链接 则环绕在外。

完整程序

把以上各部分放回一起。这是完整文件,共 31 行:

# https://pypi.org/project/beautifulsoup4/
import requests
from bs4 import BeautifulSoup
def scrape_webpage(url: str, file_path: str) -> str:
    """
    Fetch a webpage and save its visible text content into a .txt file.

    Args:
        url (str): The webpage URL to scrape.
        file_path (str): Destination path for the .txt file.

    Returns:
        str: The file path that was written.
    """
    response = requests.get(url, timeout=10)
    soup = BeautifulSoup(response.text, "html.parser")
    text = soup.get_text(separator="\n", strip=True)

    with open(file_path, "w", encoding="utf-8") as file:
        file.write(text)
    return file_path

result = scrape_webpage(
    "https://pongyuenlam.github.io/biography.html",
    "tool05_scraper.txt",
)
print(result)

with open(result, "r", encoding="utf-8") as file:
    contents = file.read()
    print(contents)

在自己的电脑上运行

下载 zip 文件并解压到一个文件夹。 zip 内有程序和一个 pyproject.toml 文件,列出它需要的两个包。在 Visual Studio Code 中打开该文件夹,然后在终端逐行输入以下三行:

uv python pin 3.12.10
uv sync
uv run tool05_scraper.py

第一行记录这个文件夹使用哪个 Python 版本。第二行把 requests 和 beautifulsoup4 安装到一个独立环境。第三行运行程序,并打印上面显示的输出。

这三行只需要做一次。下次想再运行这个程序,只需输入 uv run tool05_scraper.py。

如果你还没有设置 uv,请先从 如何安装 Visual Studio Code?开始,然后看 uv 笔记: Windows 或 Mac。

限制

延伸阅读