English 繁體中文 简体中文

如何用 Python 搜索网页(Research,版本 1)?

林邦源博士 · AI 笔记 · 2026 年 11 月 9 日 · 约 4 分钟阅读

ReAct 笔记建立的是一个在循环中思考的代理;这批笔记要建立的,是一个会搜索、 会挑选,并写出附有资料来源的草稿的 AI 研究助理。版本 1 完全没有 AI 的成分。 它只做搜索,并把搜索回来的东西展示给你看。

这样安排是有意的。在让模型驾驶搜索之前,我们应该先清楚知道搜索到底会返回 什么 — 标题、链接,以及那个叫做分数的数字。本系列之后的每一步,都 建立在这些材料之上。

为什么先不用代理

搜索服务本身已经替我们阅读网络。Tavily 是为程序设计的:你把一个问题送过去, 它返回十个结果,而每个结果都附带网页的一小段文字。

第 1 步:读取密钥

import os
from dotenv import load_dotenv
load_dotenv()
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")

搜索服务要知道是谁在提问,所以会发出一条密钥。load_dotenv() 从名为 .env 的文件读取这条密钥,os.getenv 再把它 放进一个程序可以使用的变量。密钥本身从不出现在代码里。

第 2 步:调用 Tavily 一次

from tavily import TavilyClient

tavily_client = TavilyClient(api_key=TAVILY_API_KEY)
response = tavily_client.search("What is the population of Hong Kong?")

两行代码完成工作。第一行用我们的密钥连上 Tavily。第二行送出问题,整个响应 就落在 response 之中。

第 3 步:返回的是什么

response 再次装着那个问题,名称是 query,另外还有 一个叫做 results 的列表。每个结果都是一个小包裹,里面有四样 东西:

最值得留意的是分数。在下面的输出中,它由 0.94 一路降到 0.11,而那些低分并 不是垃圾:它们是官方网页,只是刚好对我们这个具体问题说得比较少。

第 4 步:打印每个结果

print(f"Query: {response['query']}\n")
for i, r in enumerate(response["results"], start=1):
    print(f"{i}. {r['title']}  (score: {r['score']:.2f})")
    print(f"   {r['url']}")
    print(f"   {r['content'][:200].replace(chr(10), ' ')}...\n")

四行,每行各做一件事。
enumerate(..., start=1) 把结果编成 1、2、3, 方便我们之后指向其中一个。
{r['score']:.2f} 把分数显示到两个小数位,于是 0.9234 会变成 0.92。
{r['content'][:200]} 只保留网页文字最前面的 200 个字符。[:200] 是 [0:200] 的简写,意思是第 0 到 第 199 个字符:Python 从 0 开始数,并且不算最后那个数字,所以切到 199 为止。
replace(chr(10), ' ') 把换行换成空格,让一个 结果保持整齐的三行,不会一直往下溢出屏幕。
最后的 ...\n 会打印 ... 和一个换行字符。

输出结果

Query: What is the population of Hong Kong?

1. Hong Kong Population (2026) - Worldometer  (score: 0.92)
   https://www.worldometers.info/world-population/china-hong-kong-sar-population
   The current population of the Hong Kong Special Administrative Region of the People's Republic of China is 7,371,564 as of Sunday, October 18, 2026, based on Worldometer's elaboration of the latest Un...

2. Hong Kong Population 2026  (score: 0.94)
   https://worldpopulationreview.com/countries/hong-kong
   ### Request Data  Please enter your email address to receive this data in your inbox.  ## Hong Kong By the Numbers  As of 2026, Hong Kong has a total populationof 7,378,602, ranking as the 107th most...

3. Hong Kong Map, History & Population | Study.com  (score: 0.93)
   https://study.com/academy/lesson/hong-kong-facts-population.html
   The population of Hong Kong is 7.5 million. Two million people live in Kowloon, the southern part of the peninsula, and 1 million people live in the northern part of Hong Kong Island, called Victoria ...
...

十个结果,已经出现三个不同的数字:7,371,564、7,378,602 和 750 万。这是正常 的。每一页都是在不同日子写的,四舍五入的方式也各不相同。这里没有任何东西 能决定哪个数字才对 — 那是之后版本的工作,也是你的工作。

也请留意,结果并不是按分数排序:第 1 个结果得 0.92,第 2 个得 0.94。Tavily 用它自己的顺序返回结果,把相关程度和它认为读者会先觉得有用的东西混在一起。

完整程序

# RESEARCH, version 1: search the web from Python, with no AI agent.
# Before an agent can research, it needs material. This program gets that
# material: one question in, ten search results out.
import os
from dotenv import load_dotenv
load_dotenv()
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")

from tavily import TavilyClient

tavily_client = TavilyClient(api_key=TAVILY_API_KEY)
response = tavily_client.search("What is the population of Hong Kong?")

print(f"Query: {response['query']}\n")
for i, r in enumerate(response["results"], start=1):
    print(f"{i}. {r['title']}  (score: {r['score']:.2f})")
    print(f"   {r['url']}")
    print(f"   {r['content'][:200].replace(chr(10), ' ')}...\n")

# Try it: change the question, or the number of results:
#   tavily_client.search("What is the population of Hong Kong?", max_results=3)

在自己的电脑上运行

下载演示程序 (Folder-AI-Research01.zip)。zip 里有三个文件: research01.py(完整脚本)、pyproject.toml 和 README.md。这个版本不会调用语言模型,所以只需要一条 Tavily 密钥。

  1. 在 Visual Studio Code 中打开这个文件夹。
  2. 在文件夹里创建一个名为 .env 的文件,内容只有一行:
    TAVILY_API_KEY=your-tavily-key
    密钥可以从 Tavily 控制台获取。用量由供应商计费,所以运行之前,请先在那里查看当前的 收费条款。
  3. 在终端里逐行运行以下三行:
    uv python pin 3.12.10
    uv sync
    uv run research01.py
  4. 你应该会看到问题和十个编号的结果。这需要几秒钟。

如果你还没有配置好 uv,请先看 如何安装 Visual Studio Code?,然后看 uv 笔记的 Windows 或 Mac 版本。

局限

延伸阅读