04Bread Browser · 第 3 章
总进度 24 / 33让模型选择一次浏览器动作
把这份快照和“进入登录页”的任务一起发给模型,让它从已列出的元素中选一个动作。
2026-09-28约 40 分钟220 行代码难度 ★★
如果想获取全套课程资料,请关注微信公众号 「AI面包君」,回复 「课程资料」 即可领取。
1. 根据当前页面,决定下一步
ch01 已经把网页变成 LLM 友好的纯文本:
[0] <a> Quotes to Scrape → https://quotes.toscrape.com/
[1] <a> Login → https://quotes.toscrape.com/login
...
把这份快照和“进入登录页”的任务一起发给模型,让它从已列出的元素中选一个动作。
LLM 通过 OpenAI tool_calls 机制回 click(index=1) —— 我们本地执行 → 浏览器跳到 /login。
这与 Bread Agent 的工具调用思路一致:模型选择工具,本地程序执行。本章只走一步,便于分别检查选择和执行是否正确。
下一章我们才把循环加上去。
<!-- bread-visual:start -->
<!-- bread-visual:end -->图解: 模型负责挑动作,Playwright 负责执行动作。 本章只做一步;click 的返回值和新页面快照,是检查是否成功的依据。
2. 跑起来
cd ch02_one_action
python main.py
需要 .env 配好对话 LLM(同 Bread Agent,复制即可)。
预期输出
=== 当前页面快照 ===
[0] <a> Quotes to Scrape → https://quotes.toscrape.com/
[1] <a> Login → https://quotes.toscrape.com/login
[2] <a> (about) → ...
...
=== 任务 ===
Click the 'Login' link to go to the login page.
=== LLM 选择 action ===
click({'index': 1})
=== 执行结果 ===
clicked element [1]
=== 执行后页面 (URL: https://quotes.toscrape.com/login) ===
现在抽到 7 个元素:
[0] <a> Quotes to Scrape → ...
[1] <a> Login → ...
[2] <input type="text" name="username">
[3] <input type="password" name="password">
[4] <input type="submit"> Login
...
3 个关键信号:
- LLM 选对了 —— 在 55 个元素里挑出
[1] Login - action 真的执行了 —— URL 从
/变成/login - 新页面被抽出来了 —— 你看到 login form 的输入框
但到这里就停了 —— 没有循环。下一章我们让它"继续:填用户名 / 填密码 / 提交"。
<!-- bread-visual:start -->
试读到这里 · 后续内容已封存
关注公众号,继续把这章学完
在「AI面包君」发送关键词「学习AI」拿到口令。验证一次,这个浏览器就能继续阅读全部课程。