Nâng caoHướng dẫnClaude APINguồn: Anthropic

Browser Use Demo — Claude tự động hóa trình duyệt

Nghe bài viết
00:00

Điểm nổi bật

Nhấn để đến mục tương ứng

  1. 1 Khi triển khai tại sao browser use tốt hơn computer use cho web?, điều cốt lõi là Tiêu chí Computer Use Browser Use Độ chính xác click Dựa vào tọa độ pixel Dựa vào CSS selector / XPath Responsive layout Dễ bị sai khi layout thay đổi Luôn đúng vì dựa vào DOM Extract data OCR từ — hiểu đúng nguyên lý này giúp bạn tránh sai lầm phổ biến và đạt kết quả tốt hơn ngay từ đầu.
  2. 2 Góc nhìn thực tế về setup: puppeteer với node.js: -y puppeteer @anthropic-ai/sdk Cấu trúc project: browser-agent/ index.js -- Agent chính browser-tools.js -- Tool implementations schemas.js -- Tool schemas cho Claude — hiệu quả phụ thuộc nhiều vào cách triển khai và ngữ cảnh sử dụng cụ thể.
  3. 3 Chi tiết triển khai tool schemas cho claude: // schemas.js const browserToolSchemas name: "navigate", description: "Dieu huong trinh duyet den URL", input_schema: type: "object", properties: url: type: "string", description: "URL day du, bat dau bang http:// hoac https://" , required: "url" , name: "click" — pattern này giúp code sạch hơn, dễ bảo trì và mở rộng về sau.
  4. 4 Bước thực hành then chốt trong agent chính: // index.js const Anthropic require'@anthropic-ai/sdk' const tools require'./browser-tools' const schemas require'./schemas' const client new Anthropic const SYSTEM_PROMPT 'Ban la mot web automation agent chuyen nghiep. Su dung Puppeteer de tuong tac voi trang web — nắm vững điều này giúp bạn triển khai nhanh hơn và giảm thiểu lỗi thường gặp.
  5. 5 Điểm cần cân nhắc khi sử dụng error handling và retry logic: // Wrapper voi retry tu dong async function robustActionactionFn, maxRetries 3 for let attempt 1 attempt &lt maxRetries attempt++ try return await actionFn catch e console.log"Attempt " + attempt + " failed:", e — không phải mọi trường hợp đều phù hợp, cần đánh giá bối cảnh cụ thể trước khi áp dụng.
stack of books on table

Trong khi Computer Use cho Claude toàn quyền kiểm soát desktop, Browser Use tập trung riêng vào việc tự động hóa trình duyệt — một use case phổ biến hơn, an toàn hơn, và hiệu quả hơn cho hầu hết bài toán web automation.

Với Puppeteer hoặc Playwright, Claude có thể điều hướng website, điền form, click button, scrape dữ liệu, và thực hiện web research tự động — tất cả với độ chính xác cao nhờ hiểu ngữ nghĩa trang web.

Tại sao Browser Use tốt hơn Computer Use cho web?

Tiêu chí Computer Use Browser Use
Độ chính xác click Dựa vào tọa độ pixel Dựa vào CSS selector / XPath
Responsive layout Dễ bị sai khi layout thay đổi Luôn đúng vì dựa vào DOM
Extract data OCR từ screenshot Đọc trực tiếp từ DOM
Tốc độ Chậm (chờ render) Nhanh (truy cập DOM trực tiếp)
Setup Cần X11, scrot, xdotool Chỉ cần npm install

Setup: Puppeteer với Node.js

npm init -y
npm install puppeteer @anthropic-ai/sdk

Cấu trúc project:

browser-agent/
  index.js          -- Agent chính
  browser-tools.js  -- Tool implementations
  schemas.js        -- Tool schemas cho Claude

Browser Tools — Triển khai các thao tác

// browser-tools.js
const puppeteer = require('puppeteer');

let browser = null;
let page = null;

async function initBrowser() {
  if (!browser) {
    browser = await puppeteer.launch({
      headless: "new",
      args: ['--no-sandbox', '--disable-setuid-sandbox']
    });
    page = await browser.newPage();
    await page.setViewport({ width: 1366, height: 768 });
  }
  return page;
}

// Tool 1: Dieu huong den URL
async function navigate(url) {
  const p = await initBrowser();
  await p.goto(url, { waitUntil: 'networkidle2', timeout: 30000 });
  const title = await p.title();
  return JSON.stringify({ success: true, title, url: p.url() });
}

// Tool 2: Click element
async function click(selector) {
  const p = await initBrowser();
  try {
    await p.waitForSelector(selector, { timeout: 5000 });
    await p.click(selector);
    return JSON.stringify({ success: true, clicked: selector });
  } catch (e) {
    return JSON.stringify({ success: false, error: e.message });
  }
}

// Tool 3: Nhap text vao input
async function typeText(selector, text) {
  const p = await initBrowser();
  try {
    await p.waitForSelector(selector, { timeout: 5000 });
    await p.click(selector);
    await p.keyboard.down('Control');
    await p.keyboard.press('a');
    await p.keyboard.up('Control');
    await p.type(selector, text);
    return JSON.stringify({ success: true, typed: text });
  } catch (e) {
    return JSON.stringify({ success: false, error: e.message });
  }
}

// Tool 4: Extract text tu element
async function extractText(selector) {
  const p = await initBrowser();
  try {
    await p.waitForSelector(selector, { timeout: 5000 });
    const text = await p.$eval(selector, el => el.innerText);
    return JSON.stringify({ success: true, text: text.trim() });
  } catch (e) {
    return JSON.stringify({ success: false, error: e.message });
  }
}

// Tool 5: Extract nhieu elements (cho scraping)
async function extractAll(selector, attribute) {
  const p = await initBrowser();
  try {
    const items = await p.$$eval(selector, (els, attr) => {
      return els.map(el => attr === 'text' ? el.innerText : el.getAttribute(attr));
    }, attribute);
    return JSON.stringify({ success: true, items, count: items.length });
  } catch (e) {
    return JSON.stringify({ success: false, error: e.message });
  }
}

// Tool 6: Lay HTML cua trang hien tai (rut gon)
async function getPageContent() {
  const p = await initBrowser();
  const content = await p.content();
  // Rut gon de tranh vuot context window
  const trimmed = content.substring(0, 8000);
  return JSON.stringify({ success: true, html: trimmed, url: p.url() });
}

// Tool 7: Scroll trang
async function scrollPage(direction, amount) {
  const p = await initBrowser();
  const pixels = (direction === 'down' ? 1 : -1) * (amount || 300);
  await p.evaluate((px) => window.scrollBy(0, px), pixels);
  return JSON.stringify({ success: true, scrolled: pixels });
}

// Tool 8: Chup screenshot (cho debugging)
async function screenshot() {
  const p = await initBrowser();
  const buffer = await p.screenshot({ encoding: 'base64' });
  return buffer; // tra ve base64 de embed vao message
}

module.exports = {
  navigate, click, typeText, extractText,
  extractAll, getPageContent, scrollPage, screenshot
};

Tool Schemas cho Claude

// schemas.js
const browserToolSchemas = [
  {
    name: "navigate",
    description: "Dieu huong trinh duyet den URL",
    input_schema: {
      type: "object",
      properties: {
        url: { type: "string", description: "URL day du, bat dau bang http:// hoac https://" }
      },
      required: ["url"]
    }
  },
  {
    name: "click",
    description: "Click vao element theo CSS selector",
    input_schema: {
      type: "object",
      properties: {
        selector: { type: "string", description: "CSS selector, vi du: '#submit-btn', '.nav-link'" }
      },
      required: ["selector"]
    }
  },
  {
    name: "typeText",
    description: "Nhap text vao input field",
    input_schema: {
      type: "object",
      properties: {
        selector: { type: "string", description: "CSS selector cua input" },
        text: { type: "string", description: "Text can nhap" }
      },
      required: ["selector", "text"]
    }
  },
  {
    name: "extractText",
    description: "Lay text tu mot element",
    input_schema: {
      type: "object",
      properties: {
        selector: { type: "string", description: "CSS selector" }
      },
      required: ["selector"]
    }
  },
  {
    name: "extractAll",
    description: "Lay tat ca elements khop voi selector (cho scraping danh sach)",
    input_schema: {
      type: "object",
      properties: {
        selector: { type: "string", description: "CSS selector" },
        attribute: { type: "string", description: "'text' de lay text, hoac ten attribute (href, src, ...)" }
      },
      required: ["selector", "attribute"]
    }
  },
  {
    name: "getPageContent",
    description: "Lay HTML cua trang hien tai (rut gon 8000 ky tu)",
    input_schema: {
      type: "object",
      properties: {},
      required: []
    }
  },
  {
    name: "scrollPage",
    description: "Scroll trang len hoac xuong",
    input_schema: {
      type: "object",
      properties: {
        direction: { type: "string", enum: ["up", "down"] },
        amount: { type: "integer", description: "So pixel can scroll, mac dinh 300" }
      },
      required: ["direction"]
    }
  }
];

module.exports = browserToolSchemas;

Agent chính

// index.js
const Anthropic = require('@anthropic-ai/sdk');
const tools = require('./browser-tools');
const schemas = require('./schemas');

const client = new Anthropic();

const SYSTEM_PROMPT = 'Ban la mot web automation agent chuyen nghiep.
Su dung Puppeteer de tuong tac voi trang web.
Truoc tien, lay HTML trang de hieu cau truc DOM.
Dung CSS selectors chinh xac khi click hoac extract.
Neu selector khong hoat dong, thu selector khac.
Tra ve ket qua co cau truc, ro rang.';

async function runBrowserAgent(task) {
  const messages = [
    { role: "user", content: task }
  ];

  console.log("Task:", task);
  console.log("=".repeat(60));

  for (let i = 0; i < 30; i++) {
    const response = await client.messages.create({
      model: "claude-sonnet-4-5",
      max_tokens: 4096,
      system: SYSTEM_PROMPT,
      tools: schemas,
      messages
    });

    messages.push({ role: "assistant", content: response.content });

    if (response.stop_reason === "end_turn") {
      const text = response.content
        .filter(b => b.type === "text")
        .map(b => b.text)
        .join("
");
      console.log("
Ket qua:", text);
      return text;
    }

    const toolResults = [];
    for (const block of response.content) {
      if (block.type === "tool_use") {
        console.log("  [" + block.name + "]", JSON.stringify(block.input).substring(0, 80));

        let result;
        const fn = tools[block.name];
        if (!fn) {
          result = JSON.stringify({ error: "Unknown tool: " + block.name });
        } else {
          try {
            const input = block.input;
            if (block.name === "navigate") result = await fn(input.url);
            else if (block.name === "click") result = await fn(input.selector);
            else if (block.name === "typeText") result = await fn(input.selector, input.text);
            else if (block.name === "extractText") result = await fn(input.selector);
            else if (block.name === "extractAll") result = await fn(input.selector, input.attribute);
            else if (block.name === "getPageContent") result = await fn();
            else if (block.name === "scrollPage") result = await fn(input.direction, input.amount);
            else result = JSON.stringify({ error: "Unhandled tool" });
          } catch (e) {
            result = JSON.stringify({ error: e.message });
          }
        }

        console.log("  ->", String(result).substring(0, 100));

        toolResults.push({
          type: "tool_result",
          tool_use_id: block.id,
          content: String(result)
        });
      }
    }

    messages.push({ role: "user", content: toolResults });
  }

  return "Timeout";
}

// Demo: Web research tu dong
runBrowserAgent(
  "Vao trang https://news.ycombinator.com, lay danh sach 5 bai viet dau tien " +
  "bao gom: tieu de, link, va so diem. Tra ve dang JSON."
).then(result => {
  console.log("
JSON Result:", result);
  process.exit(0);
});

Demo thực tế: Automated Web Research

Agent tự động nghiên cứu web — lấy dữ liệu từ nhiều nguồn:

// Research agent: tim kiem va tong hop thong tin
async function webResearch(topic) {
  return runBrowserAgent(
    "Thuc hien research ve chu de: '" + topic + "'.
" +
    "1. Vao google.com, tim kiem chu de nay
" +
    "2. Mo 3 ket qua dau tien
" +
    "3. Tu moi trang, extract diem chinh (200 tu)
" +
    "4. Tong hop thanh bao cao 500 tu bang tieng Viet"
  );
}

// Form automation: tu dong dien form
async function fillContactForm(data) {
  return runBrowserAgent(
    "Vao trang https://example.com/contact va dien form voi thong tin sau: " +
    "Ten: " + data.name + ", Email: " + data.email + ", Message: " + data.message + ". " +
    "Sau do click Submit va xac nhan form da duoc gui thanh cong."
  );
}

// Price monitoring: theo doi gia san pham
async function monitorPrice(productUrl) {
  return runBrowserAgent(
    "Vao trang: " + productUrl + ". " +
    "Tim gia hien tai cua san pham. " +
    "Tra ve: ten san pham, gia, tinh trang con hang, va URL trang."
  );
}

Error Handling và Retry Logic

// Wrapper voi retry tu dong
async function robustAction(actionFn, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await actionFn();
    } catch (e) {
      console.log("Attempt " + attempt + " failed:", e.message);
      if (attempt === maxRetries) throw e;
      // Doi truoc khi thu lai
      await new Promise(r => setTimeout(r, 1000 * attempt));
    }
  }
}

Playwright — Lựa chọn thay thế

Playwright có API tương tự Puppeteer nhưng hỗ trợ nhiều browser hơn:

// Cai dat Playwright
// npm install playwright

const { chromium } = require('playwright');

async function playwrightDemo() {
  const browser = await chromium.launch({ headless: true });
  const page = await browser.newPage();

  await page.goto('https://example.com');

  // Playwright dung locator thay vi selector
  await page.locator('text=More information').click();

  // Wait for navigation
  await page.waitForLoadState('networkidle');

  const title = await page.title();
  console.log('Title:', title);

  await browser.close();
}

Tổng kết

Browser Use với Claude cho phép bạn xây dựng:

  • Web scraper thông minh — hiểu ngữ nghĩa, không chỉ parse HTML
  • Form automation — điền form phức tạp theo ngữ cảnh
  • Research agent — tổng hợp thông tin từ nhiều nguồn
  • Monitoring tool — theo dõi giá, tin tức, changes tự động
  • Testing automation — test UI theo ngôn ngữ tự nhiên

Bước tiếp theo: Xem Customer Support Agent để thấy cách kết hợp browser automation với knowledge base để xây dựng hệ thống hỗ trợ production-grade, hoặc Computer Use Demo để tìm hiểu về desktop automation.


Bài viết liên quan

Tính năng liên quan:Browser AutomationWeb ScrapingForm Filling

Bai viet co huu ich khong?

Bản quyền thuộc về tác giả. Vui lòng dẫn nguồn khi chia sẻ.

Bình luận (0)
Ảnh đại diện
Đăng nhập để bình luận...
Đăng nhập để bình luận
  • Đang tải bình luận...

Đăng ký nhận bản tin

Nhận bài viết hay nhất về sản phẩm và vận hành, gửi thẳng vào hộp thư của bạn.

Bảo mật thông tin. Hủy đăng ký bất cứ lúc nào. Chính sách bảo mật.