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) —— 本笔记重用的断句规则。