DeepSeek与浏览器自动化AI-Agent构建指南
DeepSeek与浏览器自动化AI Agent构建指南
文章使用到的模型可以用硅基流动中的:
注册链接:
邀请码:FytHp9Xa
一、技术选型阶段
1 基础组件选择
- AI模型 :DeepSeek-R1开放API(对话/推理)或DeepSeek-Coder(代码生成)
- 浏览器控制 :Playwright(比Selenium更快的现代浏览器自动化库)
- 编排框架 :LangChain或Autogen(用于构建AI Agent工作流)
- 后端服务 :FastAPI(轻量级API框架)+ RabbitMQ(任务队列)
2 开发环境搭建
创建虚拟环境
python -m venv agent_env source agent_env/bin/activate
安装核心依赖
pip install deepseek-api playwright langchain python-dotenv playwright install chromium
二、架构设计阶段
1 系统架构图
[用户接口] ↓ [API网关] → (身份验证/请求分发) ↓ [任务队列] → RabbitMQ(保证任务有序执行) ↓ [AI Agent核心] ├─ 自然语言理解 → DeepSeek-R1 ├─ 代码生成 → DeepSeek-Coder └─ 浏览器控制 → Playwright Driver
2 核心工作流程
- 接收自然语言指令(如"获取亚马逊iPhone 15前3页价格")
- 通过DeepSeek-R1进行意图识别和任务分解
- 生成Playwright控制代码并验证安全性
- 执行浏览器自动化操作
- 结果清洗和结构化处理
- 生成最终自然语言报告
三、核心实现阶段
1 初始化模块
config.py
import os from dotenv import load_dotenv load_dotenv() DEEPSEEK_API_KEY = os.getenv(“DEEPSEEK_API_KEY”) BROWSER_HEADLESS = os.getenv(“HEADLESS”, “true”).lower() == “true”
2 DeepSeek集成模块
deepseek_integration.py
import requests class DeepSeekClient: def init(self, api_key): self.base_url = “ self.headers = { “Authorization”: f"Bearer {api_key}”, “Content-Type”: “application/json” } def generate_response(self, prompt, model=“deepseek-r1”): payload = { “model”: model, “messages”: [{“role”: “user”, “content”: prompt}], “temperature”: 0.7 } response = requests.post( f"{self.base_url}/chat/completions", json=payload, headers=self.headers ) return response.json()[“choices”][0][“message”][“content”]
3 浏览器控制模块
browser_controller.py
from playwright.sync_api import sync_playwright import json class BrowserAgent: def init(self, headless=True): self.playwright = sync_playwright().start() self.browser = self.playwright.chromium.launch(headless=headless) self.context = self.browser.new_context( user_agent=“Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36” ) self.page = self.context.new_page() def execute_actions(self, actions_json): try: for action in actions_json[“steps”]: method = getattr(self.page, action[“action”]) if action[“type”] == “click”: method(action[“selector”]) elif action[“type”] == “input”: method(action[“selector”], action[“value”]) self.page.wait_for_timeout(1000) # 适当等待 return self.page.content() except Exception as e: print(f"执行错误: {str(e)}") return None def close(self): self.context.close() self.browser.close() self.playwright.stop()
4 任务编排模块
task_orchestrator.py
from deepseek_integration import DeepSeekClient from browser_controller import BrowserAgent import json class TaskOrchestrator: def init(self): self.ai_client = DeepSeekClient(os.getenv(“DEEPSEEK_API_KEY”)) self.browser = BrowserAgent() def process_task(self, user_input):
步骤1:生成浏览器操作指令
prompt = f""" 用户请求:{user_input} 请生成Playwright操作步骤,格式要求: {{ “steps”: [ {{ “action”: “goto|click|fill”, “type”: “navigation|click|input”, “selector”: “CSS选择器”, “value”: “输入内容(可选)” }}, // 更多步骤… ] }} """
步骤2:获取结构化操作指令
action_plan = self.ai_client.generate_response(prompt)
步骤3:执行浏览器操作
try: actions = json.loads(action_plan) result_html = self.browser.execute_actions(actions)
步骤4:结果分析
analysis_prompt = f""" 原始网页内容:{result_html[:5000]}…(截断) 用户需求:{user_input} 请提取结构化数据并生成自然语言报告 """ final_report = self.ai_client.generate_response(analysis_prompt) return final_report except json.JSONDecodeError: return “操作指令生成失败,请重新尝试”
四、优化迭代阶段
1.性能优化技巧
- 使用Playwright的异步API
- 实现智能等待(替代固定等待时间): self.page.wait_for_selector(selector, state=“attached”, timeout=5000)
五、典型用例演示
场景:商品价格监控
orchestrator = TaskOrchestrator() result = orchestrator.process_task( “请访问亚马逊中国,搜索’iPhone 15’,获取前3页商品的价格和评价数” ) print(result)
执行流程:
- 生成导航到amazon.cn的操作指令
- 自动处理搜索框输入和搜索按钮点击
- 滚动翻页并提取数据
- 使用DeepSeek分析HTML结构并提取信息
- 生成包含价格趋势分析的Markdown报告
六、扩展方向建议
- 视觉集成 :结合Playwright的截图功能+视觉模型进行验证
- 身份管理 :实现多用户Cookie隔离存储
- RPA扩展 :集成桌面自动化库(如PyAutoGUI)突破浏览器限制
- 知识记忆 :使用向量数据库存储历史操作记录