跳到正文
DEV Community· Axidort·· 5 小時前AI 評分63

如何用 Playwright 腳本模擬 AI 購物智能體測試自家網店

Test your own store like an AI buying agent (Playwright script)

AI 導讀

Axidort 作者提供約 60 行 Playwright 腳本,模擬自動化訪客檢查自家網店的購物流程,並指出首個失敗步驟。腳本依次檢查搜尋、商品頁、價格、庫存和加入購物車,不會登入、填寫個人或付款資料,也不會提交訂單。作者指出,這只是粗略測試,真實購物智能體在識別方式、連線來源和讀取網頁的方式上可能有所不同。

正文

Short answer: you can find out where an automated visitor gets stuck on your store with about 60 lines of Playwright. The script below identifies itself with a declared user agent, searches, opens a product, looks for a price and a stock word in the visible text, and tries to add the item to the cart. It prints the first step that fails. It is a smoke test, not a replica of any real AI agent.

Disclosure: we built Axidort, a tool that scans sites with a real AI agent, and I link to our free score at the end. The script needs nothing from us.

What this measures, and what it does not

It measures whether a declared headless browser can complete the early steps of a purchase journey on your site. A real buying agent may behave differently: different user agent, different IP ranges, a different way of reading the page. So treat a pass as encouraging and a stop as a lead worth investigating.

Safety rules before you run it:

  • Run it against a store you own or are allowed to test.
  • It stops at the cart. It never fills in checkout, personal or payment details, and it never submits an order.
  • Keep the pace slow. It makes a handful of requests.

Setup

mkdir agent-journey-test && cd agent-journey-test
npm init -y
npm install playwright
npx playwright install chromium

Set "type": "module" in package.json so the import line works.

The script

// journey.mjs  |  usage: node journey.mjs https://your-store.com shirt
import { chromium } from 'playwright';

const [, , site, query = 'shirt'] = process.argv;
const UA = 'MyJourneyCheck/0.1 (+https://your-store.com/contact)';

const stop = (step, note = '') => {
  console.log(`STOP  ${step} ${note}`);
  return false;
};
const pass = (step, note = '') => {
  console.log(`PASS  ${step} ${note}`);
  return true;
};

const browser = await chromium.launch();
const context = await browser.newContext({ userAgent: UA });
const page = await context.newPage();

async function run() {
  // 1. Does the site answer a declared bot?
  const res = await page.goto(site, { waitUntil: 'domcontentloaded' });
  if (!res || !res.ok()) return stop('home page', `status ${res && res.status()}`);
  pass('home page', `status ${res.status()}`);

  // 2. Can the search box be found by its role, like an assistive tool would?
  const box = page.getByRole('searchbox').first();
  if ((await box.count()) === 0) return stop('search', 'no element with role searchbox');
  await box.fill(query);
  await box.press('Enter');
  await page.waitForLoadState('domcontentloaded');
  pass('search', page.url());

  // 3. Is there a product link in the results?
  const product = page.locator('a[href*="/product"]').first();
  if ((await product.count()) === 0) return stop('results', 'no link containing /product');
  await product.click();
  await page.waitForLoadState('domcontentloaded');
  pass('product page', page.url());

  // 4. Are price and stock plain text on the page?
  const text = await page.locator('body').innerText();
  const price = text.match(/[$€£]\s?\d[\d,]*(\.\d{2})?/);
  if (!price) return stop('price', 'no currency amount in visible text');
  pass('price', price[0]);
  const stock = text.match(/in stock|out of stock|sold out|back ?order|available/i);
  if (!stock) return stop('stock', 'no stock word in visible text');
  pass('stock', stock[0]);

  // 5. Can it add to cart with a real button, and does the page confirm it?
  const add = page.getByRole('button', { name: /add to (cart|bag|basket)/i }).first();
  if ((await add.count()) === 0) return stop('add to cart', 'no button with that accessible name');
  await add.click();
  const seen = await page
    .getByText(/added|in your cart|view cart|checkout/i)
    .first()
    .isVisible({ timeout: 5000 })
    .catch(() => false);
  if (!seen) return stop('cart confirmation', 'no visible confirmation within 5s');
  return pass('cart', 'reached. Stopping here on purpose.');
}

await run();
await browser.close();

Run it:

node journey.mjs https://your-store.com shirt

How to read the output

Each line is one step. The first STOP is the one that matters, because an agent stopping there never sees the later steps.

Stops at Common causes worth checking
home page, status 403 / 429 / 503 CDN or WAF bot rules refusing the declared user agent; a JavaScript challenge in front of the page
search Search built from a clickable icon and a plain input with no role or label; search only reachable after a popup is dismissed
results Product links injected by script after load, or links that are not real a elements
price Price in an image, or filled in late by a script; price shown only after choosing a variant
stock Availability shown only as a colour or an icon
add to cart Icon-only button with no accessible name, a custom element that is not a button, or a cookie wall covering it
cart confirmation The cart updates silently with no visible feedback

The selectors are generic on purpose and will not fit every site. If it stops at results, change the product link selector to match your URLs before concluding anything. A stop on home page with a 200 status may still be a challenge page: print await page.title() to check.

A second pass without JavaScript

Some agents only fetch HTML. Repeat the price and stock checks with scripts off:

const ctx = await browser.newContext({ userAgent: UA, javaScriptEnabled: false });
const p = await ctx.newPage();
await p.goto('https://your-store.com/products/your-product');
console.log(await p.locator('body').innerText());

If the price or stock disappears, those facts depend on scripts. Axidort's guide to making a website agent friendly puts it as: send the facts in the first HTML response. Its structured data guide adds that markup injected after load is invisible to agents that do not run scripts.

Limits of this approach

  • Your own IP and a Chromium user agent are not the same as a verified bot from a vendor's published ranges, so bot protection may treat them differently.
  • It does not log in, check B2B contract prices or test pages behind an account.
  • Different runs can differ if a site shows popups at random.

FAQ

Is this the same as how ChatGPT or other assistants shop?
No. It is a rough approximation of the early journey. Real agents differ in how they identify themselves, where they connect from and how they read a page.

Should I let every bot through if it fails?
No. The aim is to decide which declared agents you welcome and make sure that decision is enforced where you think it is. Keep abuse protection on.

Can I run it against a competitor?
Do not test sites you do not own or have permission to test.

Do I need llms.txt to pass?
No. Axidort's own FAQ calls it a cheap extra signal, not a requirement.

If you would rather not maintain a script

Our free Axidort Score runs a declared browser agent (AxidortAgentCheck) through search, product, price and stock, plus a separate no-browser reader agent, and shows the step where it stopped, in about three minutes. It never orders, pays or logs in, and the result is an automated opinion from one scan at one moment, not a verdict on your store.

If you run a business and want help fixing what the test finds, you can talk to our team.

來源:DEV Community · dev.to