Skip to content

Commit

Permalink
Add headless browser script
Browse files Browse the repository at this point in the history
  • Loading branch information
Zechereh committed Oct 29, 2024
1 parent c9ea375 commit 8525e4e
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
17 changes: 17 additions & 0 deletions javascript-sdk/examples/run-script-in-headless-browser/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Example script: run the script in headless browser with AgentQL

This example demonstrates how to run the script in headless browser.

## Run the script

- [Install AgentQL SDK](https://docs.agentql.com/javascript-sdk/installation)
- Save this Javascript file locally as **run_in_headless_browser.js**
- Run the following command from the project's folder:

```bash
node run_in_headless_browser.js
```

## Play with the query

Install the [AgentQL Debugger Chrome extension](https://docs.agentql.com/installation/chrome-extension-installation) to play with the AgentQL query. [Learn more about the AgentQL query language](https://docs.agentql.com/agentql-query/query-intro)
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/* This example demonstrates how to run the script in a headless browser. */

const { wrap, configure } = require('agentql');
const { chromium } = require('playwright');

// Define the URL of the page to scrape.
const URL = "https://scrapeme.live/shop/";

// Define the queries to locate the search box and fetch the stock number.
const SEARCH_QUERY = `
{
search_products_box
}
`;

const STOCK_NUMBER_QUERY = `
{
number_in_stock
}
`;


(async () => {
// Set the AgentQL API key via the `configure` method.
configure({ apiKey: process.env.AGENTQL_API_KEY });

// Launch a headless browser using Playwright.
const browser = await chromium.launch({ headless: true });

// Wrap a new page to use the AgentQL API.
const page = wrap(await browser.newPage());

await page.goto(URL);

let response;
// Use queryElements() method to locate the search box from the page.
response = await page.queryElements(SEARCH_QUERY);

// Use Playwright's API to fill the search box and press Enter.
await response.search_products_box.type("Charmander");
page.keyboard.press("Enter");

// Use queryData() method to fetch the stock number from the page.
response = await page.queryData(STOCK_NUMBER_QUERY);
console.log(response);

await browser.close();
})();

0 comments on commit 8525e4e

Please sign in to comment.