English 繁體中文 简体中文

AI 代理如何讀取網頁(ReAct,版本 9)?

林邦源博士 · AI 筆記 · 2026 年 11 月 9 日 · 約 4 分鐘閱讀

我們的代理來到版本 9,做了一件新事:讀取真實的網頁。網頁本身並不是文字。 它送來的時候是 HTML,裡面滿是告訴瀏覽器如何顯示內容的標籤,代理無法直接 使用。兩個小工具負責清理 — 一個下載網頁,另一個找出裝着句子的部分。 然後交給版本 8 的斷句規則完成最後一步。

兩個工具,各司其職

import re
import requests
from bs4 import BeautifulSoup

requests 是下載器:它向網站要求一個網頁,然後把伺服器送來的 東西交回。來自 bs4 套件的 BeautifulSoup 是閱讀器: 它把那段 HTML 變成程式可以搜尋的東西,於是我們可以說「把所有標題和段落 交給我」,而不必逐個標籤去翻。

第一步:下載網頁

url = "https://pongyuenlam.github.io/"
USER_AGENT = "ReAct09-class-demo"   # tells the website who is visiting

response = requests.get(url, headers={"User-Agent": USER_AGENT}, timeout=10)
soup = BeautifulSoup(response.text, "html.parser")

requests.get 向伺服器索取 url 上的網頁。 timeout=10 的意思是「十秒之後就放棄」,所以程式不會一直卡住。 User-Agent 是一個隨請求一起送出的簡短名稱,讓網站知道是誰 來訪,而不是收到一個匿名點擊。回來的內容存放在 response.text:未經處理的 HTML。最後一行把這段 HTML 倒進 soup,隨時可以搜尋。

第二步:只留下裝着句子的部分

blocks = []
for element in soup.find_all(["h1", "h2", "h3", "p", "li"]):
    text = element.get_text(" ", strip=True)   # keeps the text, drops the tags
    text = re.sub(r"\s+", " ", text)           # many spaces become one
    if text:
        blocks.append(text)

find_all 接受一串標籤名稱,回傳所有帶有其中任何一個名稱的 元素:標題、段落和清單項目。網頁的句子就藏在這些地方。 get_text(" ", strip=True) 丟掉標籤、留下文字,用一個空格把 各片段接起來,並去掉首尾的空白。 re.sub(r"\s+", " ", text) 再把連續的空格和換行變成一個空格, 因為 HTML 裡滿是這些東西。最後兩行檢查每一個區塊是否真的有文字,空的就 跳過。

第三步:把每個區塊切成句子

sentences = []
for block in blocks:
    sentences.extend(re.split(r"(?<=[.!?])\s+", block))

這一行來自版本 8,完全沒有改動。每個區塊會在緊接 .、 ! 或 ? 之後的空格處切開,標點留在原來那句之中。 extend 把每一句加進同一個清單,所以整頁最後變成一個句子 清單。版本 8 逐字解釋了這一行。

第四步:為每句編號並印出

print(f"=== {len(sentences)} sentences from {url} ===")
for number, sentence in enumerate(sentences, start=1):
    print(f"{number}. {sentence}")

第一行說明找到多少句,以及它們來自哪一頁。 enumerate(..., start=1) 在走過清單時逐句數數,由 1 開始。 編號很重要:日後代理可以指着「第 17 句」,而不必把整段文字複製過來。

輸出結果

=== 24 sentences from https://pongyuenlam.github.io/ ===
1. Home
2. Biography
3. Research
4. Cases
5. Books
6. AI Notes
7. Links
8. Glossary
9. Howard Lam, PhD
10. AI Marketing Researcher, Educator, Developer
11. A marketing PhD who spent two decades in brand management at Coca-Cola, McDonald's, and P&G before conducting case research, writing, and teaching at The Chinese University of Hong Kong and City University of Hong Kong, I now research how AI is reshaping marketing.
12. This site links to my work: peer-reviewed research (including the Journal of Marketing), business cases published through Harvard Business Impact and Ivey Publishing, open-source AI tools and code, and curated resources on AI and machine learning.
13. Links
...
19. © 2026 Howard Pong Yuen LAM,PhD
20. Email
21. GitHub
22. Google Scholar
23. ORCID
24. LinkedIn

看頭八句:Home、Biography、Research、Cases、Books、AI Notes、Links、Glossary。 那就是網站的選單。選單是一個清單,而第二步被要求保留清單項目,所以選單 也變成句子送上來。第 11 句很長,那是個人簡介的段落,因為它的逗號不是句末, 所以整段保留。最後幾句是頁尾的連結。

完整程式

# Read a web page with requests + BeautifulSoup and print each sentence.
# No AI model here: this is the "reading" step an agent needs before it can use a web page.
import re
import requests
from bs4 import BeautifulSoup

url = "https://pongyuenlam.github.io/"
USER_AGENT = "ReAct09-class-demo"   # tells the website who is visiting

# 1) Download the page, then let BeautifulSoup turn the HTML into something we can search
response = requests.get(url, headers={"User-Agent": USER_AGENT}, timeout=10)
soup = BeautifulSoup(response.text, "html.parser")

# 2) Take the text of each block: headings, paragraphs and list items
blocks = []
for element in soup.find_all(["h1", "h2", "h3", "p", "li"]):
    text = element.get_text(" ", strip=True)      # " " joins the text of links inside the block
    text = re.sub(r"\s+", " ", text)              # turn line breaks and extra spaces into one space
    if text:
        blocks.append(text)

# 3) Split each block into sentences: after . ! or ? followed by a space
sentences = []
for block in blocks:
    sentences.extend(re.split(r"(?<=[.!?])\s+", block))

# 4) Print each sentence with a number
print(f"=== {len(sentences)} sentences from {url} ===")
for number, sentence in enumerate(sentences, start=1):
    print(f"{number}. {sentence}")

在自己的電腦上執行

下載示範程式 (Folder-AI-ReAct09.zip)。zip 內有三個檔案: ReAct09.py(完整腳本)、pyproject.toml 和 README.md。安裝需要連接互聯網,因為程式用到兩個外部套件, 但不需要 API 金鑰。

  1. 在 Visual Studio Code 中開啟這個資料夾。
  2. 在終端機逐行執行以下三行:
    uv python pin 3.12.10
    uv sync
    uv run ReAct09.py
  3. 你應該會看到句子總數,然後每行一句,並附有編號。

如果你還未設定好 uv,請先看 如何安裝 Visual Studio Code?,然後看 uv 筆記的 Windows 或 Mac 版本。

限制

延伸閱讀