Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add headless browser script #85

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,41 @@
/* This example demonstrates how to run the script in a headless browser. */

const { wrap } = 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 () => {
// Launch a headless browser using Playwright.
const browser = await chromium.launch({ headless: false });
// Create a new page in the browser and wrap it to get access to the AgentQL's querying API
const page = await wrap(await browser.newPage());
await page.goto(URL);

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

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

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

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