前言你有没有遇到过这种情况想蹲一个限时抢购、想等某个网页更新、想监控价格变化……但总不能24小时盯着屏幕。你需要一个浏览器自动化机器人。今天我们用开源工具 OpenClaw热榜第一的项目手把手搭建一个网页监控机器人彻底搞懂· 浏览器自动化的工作原理· 如何让程序像人一样操作网页· 怎么把监控结果推送到微信/钉钉---一、OpenClaw是什么OpenClaw 是一个浏览器自动化框架可以· 模拟真实用户点击、输入、滚动· 抓取动态网页内容包括AJAX加载的数据· 执行JavaScript代码· 截图、录屏、保存HTML它的底层用的是 Playwright微软出品比传统的Selenium更快、更稳。核心原理你的代码 → OpenClaw API → Playwright → 浏览器驱动 → 真实浏览器↓执行操作、返回结果---二、快速上手安装与第一个脚本1. 安装OpenClawbash# 安装Python包pip install openclaw# 安装浏览器驱动playwright install chromium2. 第一个脚本打开百度并截图pythonfrom openclaw import Browser# 启动浏览器browser Browser(headlessFalse) # headlessFalse 可以看到浏览器界面# 打开网页page browser.new_page()page.goto(https://www.baidu.com)# 输入关键词page.fill(#kw, OpenClaw)# 点击搜索按钮page.click(#su)# 等待结果加载page.wait_for_selector(.result)# 截图page.screenshot(baidu_result.png)# 关闭browser.close()运行bashpython baidu_search.py你会看到一个浏览器窗口自动打开、输入、搜索、截图然后关闭。---三、实战案例网页监控机器人场景需求监控某个商品页面的价格变化当价格低于阈值时发送通知。完整代码pythonimport timeimport jsonimport requestsfrom openclaw import Browserfrom datetime import datetimeclass WebMonitor:def __init__(self, url, check_interval60):self.url urlself.interval check_intervalself.last_price Noneself.last_html_hash Nonedef get_page_content(self):获取页面内容browser Browser(headlessTrue) # 后台运行page browser.new_page()try:page.goto(self.url, timeout30000)page.wait_for_load_state(networkidle)# 获取HTMLhtml page.content()# 获取价格需要根据实际网页调整选择器price_element page.query_selector(.price, .current-price, [data-price])price Noneif price_element:price_text price_element.text()# 提取数字import rematch re.search(r[\d\.], price_text)if match:price float(match.group())# 截图保存timestamp datetime.now().strftime(%Y%m%d_%H%M%S)page.screenshot(fscreenshots/{timestamp}.png)return html, priceexcept Exception as e:print(f抓取失败: {e})return None, Nonefinally:browser.close()def calculate_hash(self, content):计算HTML哈希用于检测变化import hashlibreturn hashlib.md5(content.encode()).hexdigest()def send_notification(self, message):发送通知支持多种渠道# 方式1打印到控制台print(f[{datetime.now()}] {message})# 方式2发送到钉钉机器人webhook_url https://oapi.dingtalk.com/robot/send?access_tokenYOUR_TOKENheaders {Content-Type: application/json}data {msgtype: text,text: {content: message}}try:requests.post(webhook_url, jsondata, headersheaders, timeout5)except:pass# 方式3发送到Server酱微信# https://sct.ftqq.com/def check_and_notify(self):检查并通知变化content, price self.get_page_content()if not content:returncurrent_hash self.calculate_hash(content)# 检测内容变化if self.last_html_hash and current_hash ! self.last_html_hash:self.send_notification(f 网页内容更新了 {self.url})# 检测价格变化if price is not None:if self.last_price is not None and price ! self.last_price:direction ⬇️ 降 if price self.last_price else ⬆️ 涨self.send_notification(f 价格变化 {direction}了\nf原价: {self.last_price}\nf现价: {price}\nf链接: {self.url})# 价格低于阈值告警if price 100: # 阈值可配置self.send_notification(f 价格低于100元了当前价格: {price}\nf快去下单: {self.url})self.last_html_hash current_hashself.last_price priceprint(f[{datetime.now()}] 检查完成, 价格: {price})def run(self):持续运行print(f开始监控: {self.url})print(f检查间隔: {self.interval} 秒)# 创建截图目录import osos.makedirs(screenshots, exist_okTrue)while True:try:self.check_and_notify()except Exception as e:print(f错误: {e})time.sleep(self.interval)# 使用示例if __name__ __main__:# 监控商品页面monitor WebMonitor(urlhttps://example.com/product/12345,check_interval300 # 每5分钟检查一次)monitor.run()---四、高级技巧处理复杂场景1. 等待元素出现处理动态加载python# 等待特定元素出现最多10秒try:page.wait_for_selector(.product-detail, timeout10000)print(商品详情已加载)except:print(加载超时)2. 执行JavaScript获取隐藏数据python# 执行JS并获取返回值result page.evaluate(() {return {title: document.title,scrollHeight: document.body.scrollHeight,cookies: document.cookie};})print(result)3. 模拟登录保存登录状态python# 第一次手动登录browser Browser(headlessFalse)page browser.new_page()page.goto(https://example.com/login)# 等待用户手动输入账号密码input(请登录后按回车继续...)# 保存cookiescookies page.context.cookies()with open(cookies.json, w) as f:json.dump(cookies, f)# 后续加载cookies自动登录browser2 Browser()context browser2.new_context()context.add_cookies(cookies)page context.new_page()page.goto(https://example.com/dashboard)4. 处理验证码接入打码平台python# 截图验证码区域captcha_element page.query_selector(#captcha-img)captcha_element.screenshot(captcha.png)# 调用打码API如超级鹰、打码兔# code solve_captcha(captcha.png)# 输入验证码# page.fill(#captcha-input, code)---五、部署到服务器24小时运行1. 使用 systemd 守护进程创建服务文件 /etc/systemd/system/webmonitor.serviceini[Unit]DescriptionWeb Monitor ServiceAfternetwork.target[Service]TypesimpleUserubuntuWorkingDirectory/home/ubuntu/webmonitorExecStart/usr/bin/python3 /home/ubuntu/webmonitor/monitor.pyRestartalwaysRestartSec10[Install]WantedBymulti-user.target启动服务bashsudo systemctl enable webmonitorsudo systemctl start webmonitorsudo systemctl status webmonitor2. 使用 Docker 部署dockerfileFROM python:3.10-slimRUN pip install openclaw playwrightRUN playwright install chromiumWORKDIR /appCOPY monitor.py .CMD [python, monitor.py]bashdocker build -t webmonitor .docker run -d --name monitor webmonitor---六、腾讯云Lighthouse一键部署热榜文章提到的热榜上那篇《腾讯云Lighthouse一键部署OpenClaw》其实就是把上面的流程打包成了一键脚本bash# 腾讯云 Lighthouse 用户可以直接用这个脚本curl -sSL https://raw.githubusercontent.com/openclaw/lighthouse/main/install.sh | bash这个脚本会1. 安装 Docker 和 OpenClaw2. 配置开机自启3. 开放必要端口4. 启动监控服务---七、常见问题与解决方案问题 原因 解决元素找不到 页面未加载完成 用 wait_for_selector被反爬 检测到自动化特征 用 stealth 插件隐藏特征内存占用高 浏览器实例未关闭 每次用完 browser.close()中文乱码 编码问题 页面设置 page.set_viewport_size定时任务不执行 cron环境变量问题 用绝对路径 完整环境反爬绕过技巧python# 隐藏自动化特征from openclaw.stealth import stealth_asyncawait stealth_async(page)# 使用真实用户代理page.set_extra_http_headers({User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36})# 模拟人类行为page.mouse.move(100, 100)page.wait_for_timeout(500)page.mouse.click(100, 100)---八、扩展多网页并发监控pythonimport asynciofrom openclaw import Browserasync def monitor_one(url, callback):browser await Browser.launch()page await browser.new_page()await page.goto(url)content await page.content()await callback(url, content)await browser.close()async def monitor_all(urls):tasks [monitor_one(url, handle_result) for url in urls]await asyncio.gather(*tasks)def handle_result(url, content):print(f{url} 长度: {len(content)})# 运行asyncio.run(monitor_all([https://example.com/product1,https://example.com/product2,https://example.com/product3]))---九、总结通过这篇文章你学会了· OpenClaw 的基本使用方法· 如何写一个网页监控机器人· 处理动态加载、登录、验证码等复杂场景· 部署到服务器实现24小时监控· 并发监控多个网页浏览器自动化能做的事情远不止监控自动填表、批量发帖、数据采集、自动化测试……你可以用这套技术解决很多重复性工作。下一篇预告《从浏览器自动化到RPA让机器人帮你干完所有重复工作》---评论区分享你用自动化工具做过最有趣的事情