Develop a Python script to automate browser actions with Playwright.
- User
Develop a Python script to automate browser actions with Playwright.
Assistant
Analyzing Automation Requirements
I've started by defining the end goal: crafting a Python script with Playwright to control a browser. Now, I'm delving into the prerequisites. Specifically, verifying Python and Playwright installation are the initial, crucial steps. This will ensure smooth execution.
Structuring the Implementation Steps
I'm presently building the specific actions for the script. I've chosen a scenario involving an e-commerce site, aiming for a login, add-to-cart, and verification sequence. Now, I'm mentally breaking down these actions into manageable Playwright steps. First, I have to import the library and instantiate the browser.
Decomposing Core Functionality
I'm now focusing on the essential Playwright operations. My thought process involves launching the engine, opening a browser instance (initially non-headless for clarity), and setting up a context with a page. I'm exploring navigating to a demo e-commerce site, aiming to cover user login and product addition. Then, I need to implement assertions and include error handling techniques.
Planning the Code Components
I'm presently building the specific actions for the script. I've chosen a scenario involving an e-commerce site, aiming for a login, add-to-cart, and verification sequence. I'm mentally breaking down these actions into manageable Playwright steps. I'll need to write about locators, and assertions. I also need to provide the terminal commands for installation.
Here is a complete guide to creating a Python script for browser automation using Playwright.
I have provided two examples: a Basic Synchronous Script (easiest to start with) and an Asynchronous Script (better for performance or scraping).
Prerequisites
First, install Playwright and the browser binaries via your terminal:
pip install playwright playwright install
1. The Basic Script (Synchronous)
This script will navigate to a website, search for something, take a screenshot, and print the page title. This uses the
sync_api, which allows you to write code line-by-line like a standard script.File:
bot.pyfrom playwright.sync_api import sync_playwright import time def run(): with sync_playwright() as p: # 1. Launch the browser # headless=False means you will actually SEE the browser open. # Set to True to run in background. browser = p.chromium.launch(headless=False, slow_mo=500) # 2. Create a new browser context and page context = browser.new_context() page = context.new_page() # 3. Navigate to a URL print("Navigating to Wikipedia...") page.goto("https://www.wikipedia.org/") # 4. Interact with elements (Type and Click) # Playwright waits automatically for elements to be ready page.fill("input[name='search']", "Python (programming language)") page.press("input[name='search']", "Enter") # 5. Validations & Assertions # Wait for the heading to ensure page load page.wait_for_selector("#firstHeading") title = page.title() print(f"Page Title is: {title}") # 6. Extract Data # Get the text of the main heading heading_text = page.locator("#firstHeading").inner_text() print(f"Heading found: {heading_text}") # 7. Take a full page screenshot page.screenshot(path="wiki_python.png", full_page=True) print("Screenshot saved as 'wiki_python.png'") # 8. Close the browser browser.close() if __name__ == "__main__": run()
2. Advanced Script (Asynchronous)
If you are building a web scraper or integrating with web frameworks (like FastAPI/Django), you should use the
async_api.File:
async_bot.pyimport asyncio from playwright.async_api import async_playwright async def main(): async with async_playwright() as p: # Launch browser browser = await p.firefox.launch(headless=True) page = await browser.new_page() # Navigate await page.goto("https://example.com") # Get page title print(await page.title()) # Click a link (Selector based on text content) # This creates a promise to verify navigation happening await page.click("text=More information") # Wait for the new page to load await page.wait_for_load_state("networkidle") print("New URL:", page.url) await browser.close() if __name__ == "__main__": asyncio.run(main())
Key Features Explained
1. Selectors (Locators)
Playwright is very smart about finding elements. You can mix CSS, XPath, and Text selectors.
page.click("text=Log in") # Text selector page.fill("#username", "john") # CSS ID page.click("button:has-text('Submit')") # Combined page.click("//button[@id='submit']") # XPath2. Auto-waiting
Unlike Selenium, you rarely need
time.sleep(). Playwright automatically waits for an element to be visible and actionable before clicking or typing.3. Headless Mode
headless=True(Default): Runs faster, no UI visible. Good for servers/scraping.headless=False: Opens the browser window. Good for debugging.
4. Video Recording & Tracing
You can record a video of the bot execution by adding just one argument to the context:
context = browser.new_context(record_video_dir="videos/") # ... perform actions ... context.close() # Video saves on close
Pro Tip: Use Code Generation
The easiest way to write these scripts is to let Playwright write them for you. Run this command in your terminal:
playwright codegen wikipedia.orgA browser window and a code inspector will open. Whatever you click or type in the browser will be instantly translated into Python code in the inspector window, which you can copy and paste into your script.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.