Article·induced.ai
ai-agentsautomationweb-developmentpythonmachine-learningplaywrightselenium
Induced AI
Automate web browser tasks using intelligent AI agents. This Action Pack guides you through setting up Playwright and running a Python script to mimic human interaction for tasks like navigation and form filling, boosting efficiency.
beginner10 min4 steps
The play
- Install Playwright and Browser BinariesOpen your terminal or command prompt and install the Playwright Python library. Then, install the necessary browser binaries (Chromium, Firefox, WebKit) that Playwright uses for automation.
- Create Your First Automation ScriptCreate a new Python file (e.g., `browser_bot.py`) and paste the provided 'Copy-Paste Starter' code into it. This script will launch a browser, navigate to Google, type a search query, and press Enter.
- Run Your Browser AutomationExecute the Python script from your terminal. Observe the browser opening (if `headless=False`) and performing the defined actions. The script will print the page titles before and after the search.
- Customize and Extend InteractionsModify the `simple_browser_task` function to interact with different websites or perform more complex actions. Experiment with changing the URL, filling other form fields, clicking buttons, or extracting information from the page. Set `headless=False` in `p.chromium.launch()` to visually debug your automation.
Starter code
import asyncio
from playwright.async_api import sync_playwright
async def simple_browser_task():
async with sync_playwright() as p:
browser = await p.chromium.launch(headless=True) # Set headless=False to see the browser
page = await browser.new_page()
await page.goto("https://www.google.com")
print(f"Navigated to {await page.title()}")
# Simulate typing a search query
await page.fill('textarea[name="q"]', "Browser automation AI")
await page.press('textarea[name="q"]', 'Enter')
# Wait for navigation and network to be idle
await page.wait_for_load_state('networkidle')
print(f"Page title after search: {await page.title()}")
await browser.close()
asyncio.run(simple_browser_task())Source