Skip to main content

Generating Automation Scripts

Web Agent can automatically generate automation scripts based on the actions you perform. This feature allows you to convert manual browser interactions into reusable code for testing, automation, and CI/CD pipelines.

Supported Script Types

Playwright Scripts

  • JavaScript/TypeScript: Modern browser automation
  • Python: Cross-platform testing scripts
  • C#: .NET integration
  • Java: Enterprise testing frameworks

Selenium Scripts

  • Python: Most popular web automation
  • JavaScript: Node.js automation
  • Java: Enterprise-grade testing
  • C#: .NET framework integration

Custom Frameworks

  • Cypress: Modern end-to-end testing
  • Puppeteer: Chrome-specific automation
  • WebDriver: Cross-browser compatibility
  • Custom: Your own automation framework

How Script Generation Works

1. Perform Actions in Web Agent

First, use Web Agent to perform the actions you want to automate:

Go to https://example.com, click "Login", fill username with "testuser", 
fill password with "testpass", and click "Submit"

2. Request Script Generation

After completing your automation workflow, ask Web Agent to generate a script:

Generate a Playwright script for the actions I just performed

3. Customize the Output

Specify your preferences for the generated script:

Create a Python Playwright script with proper error handling and comments

Script Generation Examples

Basic Navigation Script

Web Agent Actions:

Go to https://github.com and take a screenshot

Generated Playwright Script:

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

(async () => {
// Launch browser
const browser = await chromium.launch({ headless: false });
const context = await browser.newContext();
const page = await context.newPage();

try {
// Navigate to GitHub
await page.goto('https://github.com');

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

// Take screenshot
await page.screenshot({ path: 'github-homepage.png' });

console.log('Successfully navigated to GitHub and took screenshot');

} catch (error) {
console.error('Error during automation:', error);
} finally {
// Clean up
await browser.close();
}
})();

Form Automation Script

Web Agent Actions:

Go to https://example.com/contact, fill name with "John Doe", 
email with "[email protected]", message with "Test message", and submit

Generated Python Playwright Script:

from playwright.sync_api import sync_playwright

def run_contact_form_automation():
with sync_playwright() as p:
# Launch browser
browser = p.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()

try:
# Navigate to contact form
page.goto('https://example.com/contact')

# Wait for form to be visible
page.wait_for_selector('form')

# Fill form fields
page.fill('input[name="name"]', 'John Doe')
page.fill('input[name="email"]', '[email protected]')
page.fill('textarea[name="message"]', 'Test message')

# Submit form
page.click('button[type="submit"]')

# Wait for success message
page.wait_for_selector('.success-message')

print('Form submitted successfully')

except Exception as e:
print(f'Error during form automation: {e}')
finally:
browser.close()

if __name__ == '__main__':
run_contact_form_automation()

E-commerce Workflow Script

Web Agent Actions:

Go to https://shop.example.com, search for "laptop", click first result, 
add to cart, go to cart, and proceed to checkout

Generated Selenium Script:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys

class EcommerceAutomation:
def __init__(self):
self.driver = webdriver.Chrome()
self.wait = WebDriverWait(self.driver, 10)

def run_shopping_workflow(self):
try:
# Navigate to shop
self.driver.get('https://shop.example.com')

# Search for laptop
search_box = self.wait.until(
EC.presence_of_element_located((By.NAME, 'search'))
)
search_box.send_keys('laptop')
search_box.send_keys(Keys.RETURN)

# Click first result
first_result = self.wait.until(
EC.element_to_be_clickable((By.CSS_SELECTOR, '.product-item:first-child'))
)
first_result.click()

# Add to cart
add_to_cart_btn = self.wait.until(
EC.element_to_be_clickable((By.ID, 'add-to-cart'))
)
add_to_cart_btn.click()

# Go to cart
cart_link = self.wait.until(
EC.element_to_be_clickable((By.ID, 'cart-link'))
)
cart_link.click()

# Proceed to checkout
checkout_btn = self.wait.until(
EC.element_to_be_clickable((By.ID, 'checkout'))
)
checkout_btn.click()

print('Successfully completed shopping workflow')

except Exception as e:
print(f'Error during shopping automation: {e}')
finally:
self.driver.quit()

if __name__ == '__main__':
automation = EcommerceAutomation()
automation.run_shopping_workflow()

Advanced Script Features

Error Handling and Retries

Generate a robust Playwright script with retry logic and comprehensive error handling

Generated Script with Advanced Features:

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

class WebAutomation {
constructor() {
this.maxRetries = 3;
this.timeout = 30000;
}

async retry(fn, retries = this.maxRetries) {
try {
return await fn();
} catch (error) {
if (retries > 0) {
console.log(`Retrying... ${retries} attempts left`);
await this.sleep(2000);
return this.retry(fn, retries - 1);
}
throw error;
}
}

async sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

async run() {
const browser = await chromium.launch({ headless: false });
const context = await browser.newContext();
const page = await context.newPage();

try {
// Set default timeout
page.setDefaultTimeout(this.timeout);

// Navigate with retry
await this.retry(async () => {
await page.goto('https://example.com');
await page.waitForLoadState('networkidle');
});

// Perform actions with error handling
await this.retry(async () => {
await page.click('#login-button');
await page.waitForSelector('#username');
});

console.log('Automation completed successfully');

} catch (error) {
console.error('Automation failed:', error);
// Take screenshot for debugging
await page.screenshot({ path: 'error-screenshot.png' });
} finally {
await browser.close();
}
}
}

new WebAutomation().run();

Data-Driven Testing

Create a Playwright script that can run with different test data sets

Generated Data-Driven Script:

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

// Test data
const testData = [
{ username: 'user1', password: 'pass1', expectedResult: 'success' },
{ username: 'user2', password: 'pass2', expectedResult: 'success' },
{ username: 'invalid', password: 'invalid', expectedResult: 'error' }
];

async function runLoginTest(data) {
const browser = await chromium.launch({ headless: false });
const page = await browser.newPage();

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

// Fill login form
await page.fill('#username', data.username);
await page.fill('#password', data.password);
await page.click('#login-button');

// Verify result
if (data.expectedResult === 'success') {
await page.waitForSelector('.dashboard');
console.log(`✅ Login successful for ${data.username}`);
} else {
await page.waitForSelector('.error-message');
console.log(`✅ Expected error shown for ${data.username}`);
}

} catch (error) {
console.error(`❌ Test failed for ${data.username}:`, error);
} finally {
await browser.close();
}
}

// Run tests for all data sets
(async () => {
for (const data of testData) {
await runLoginTest(data);
}
})();

Framework-Specific Generation

Cypress Test Generation

Generate a Cypress test for the user registration flow I just completed

Generated Cypress Test:

describe('User Registration Flow', () => {
beforeEach(() => {
cy.visit('https://example.com/register');
});

it('should successfully register a new user', () => {
// Fill registration form
cy.get('#firstName').type('John');
cy.get('#lastName').type('Doe');
cy.get('#email').type('[email protected]');
cy.get('#password').type('SecurePassword123');
cy.get('#confirmPassword').type('SecurePassword123');

// Accept terms
cy.get('#terms').check();

// Submit form
cy.get('#register-button').click();

// Verify success
cy.get('.success-message').should('be.visible');
cy.url().should('include', '/welcome');
});

it('should show validation errors for invalid data', () => {
// Submit empty form
cy.get('#register-button').click();

// Check validation errors
cy.get('.error-message').should('contain', 'First name is required');
cy.get('.error-message').should('contain', 'Email is required');
});
});

Puppeteer Script Generation

Create a Puppeteer script for web scraping the product information

Generated Puppeteer Script:

const puppeteer = require('puppeteer');

async function scrapeProducts() {
const browser = await puppeteer.launch({ headless: false });
const page = await browser.newPage();

try {
await page.goto('https://example-shop.com/products');

// Wait for products to load
await page.waitForSelector('.product-item');

// Extract product information
const products = await page.evaluate(() => {
const productElements = document.querySelectorAll('.product-item');
return Array.from(productElements).map(element => ({
name: element.querySelector('.product-name')?.textContent?.trim(),
price: element.querySelector('.product-price')?.textContent?.trim(),
image: element.querySelector('.product-image')?.src,
link: element.querySelector('.product-link')?.href
}));
});

// Save to file
const fs = require('fs');
fs.writeFileSync('products.json', JSON.stringify(products, null, 2));

console.log(`Scraped ${products.length} products`);

} catch (error) {
console.error('Scraping failed:', error);
} finally {
await browser.close();
}
}

scrapeProducts();

Customizing Generated Scripts

Adding Custom Configuration

Generate a Playwright script with custom browser settings and mobile emulation

Including Test Assertions

Create a script with comprehensive test assertions and reporting

Integration with CI/CD

Generate a script that can run in GitHub Actions with proper reporting

Best Practices for Script Generation

1. Be Specific About Requirements

Generate a TypeScript Playwright script with:
- Page Object Model pattern
- Custom error handling
- Screenshot on failure
- JSON test report generation

2. Include Environment Configuration

Create a script that works with different environments (dev, staging, prod)

3. Add Proper Documentation

Generate a well-documented script with inline comments explaining each step

4. Consider Maintenance

Create a modular script that's easy to maintain and extend

Exporting and Using Scripts

Save Generated Scripts

Web Agent can save scripts directly to your project:

Save the generated Playwright script to ./tests/automation/login-test.js

Create Test Suites

Generate a complete test suite with multiple test cases for the user workflows

Integration Examples

Show me how to integrate this script with Jest testing framework

Next Steps

Troubleshooting Script Generation

Common Issues

Generated Script Doesn't Work

  • Check selectors: Ensure CSS selectors are still valid
  • Update timeouts: Adjust wait times for slow-loading elements
  • Verify URLs: Make sure target URLs are accessible

Missing Dependencies

  • Install packages: Run npm install playwright or equivalent
  • Check versions: Ensure compatible framework versions
  • Update imports: Verify import statements are correct

Browser Compatibility

  • Test different browsers: Chrome, Firefox, Safari compatibility
  • Check headless mode: Some sites block headless browsers
  • Update user agents: Some sites require specific user agents

For more help with script generation, join our Discord community.