AI 代理如何讀取網頁(ReAct,版本 9)?
我們的代理來到版本 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 金鑰。
- 在 Visual Studio Code 中開啟這個資料夾。
- 在終端機逐行執行以下三行:
uv python pin 3.12.10uv syncuv run ReAct09.py - 你應該會看到句子總數,然後每行一句,並附有編號。
如果你還未設定好 uv,請先看 如何安裝 Visual Studio Code?,然後看 uv 筆記的 Windows 或 Mac 版本。
限制
- 它只讀一頁就停。程式不會跟隨連結,所以如果一個網頁只是 指向其他網頁,代理就拿不到甚麼可用的內容。
-
有些網頁送來時幾乎是空的。如果網頁是由瀏覽器裡的 JavaScript
建立,文字並不在
requests下載到的 HTML 裡,程式就甚麼也 找不到。 - 選單和頁尾也算作句子。清單項目或段落裡的任何東西都會 保留,不管是真正的文章還是頁面標籤。
-
做一個有禮貌的訪客。保留
User-Agent標頭, 讓網站知道誰在呼叫;並閱讀歡迎閱讀的網頁,而不是禁止閱讀的網頁。
延伸閱讀
- Requests — 文件 — 如何下載網頁、設定標頭和逾時。
- BeautifulSoup — 文件 —
find_all、get_text,以及其他搜尋 HTML 的方法。 - 程式如何把一段文字切成句子?(ReAct,版本 8) — 本篇筆記重用的斷句規則。