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 版本。

限制

延伸閱讀