1. Understand the Goal: The user wants a Python script to automate browser actions using the playwright-python library.
Identify the Prerequisites:
Python installed.
playwright library installed via pip.
Playwright browsers installed via the CLI command.
Determine the Scope/Content:
A simple "Hello World" example (opening a page, taking a screenshot).
A more advanced example (interacting with elements, clicking, typing, navigating).
Explanation of asynchronous vs. synchronous usage (Sync vs. Async).
Explanation of locators (how to find elements).
Explanation of assertions (verifying state).
Headless vs. Headed mode (seeing the browser vs. background).
Drafting the Script (Iterative Process):
Step 1: Installation instructions. This is crucial.
pip install playwrightplaywright install
Step 2: The Basic Sync Script. This is usually what beginners want.
Import sync_playwright.
Context manager with.
Launch browser (chromium).
New page.
goto url.
expect title or text.
Close.
Step 3: A specific use case (e.g., Google Search or filling a form). Let's do a generic "fill form" or "interact" example to show clicking and typing. Let's use a dummy site like https://www.example.com or https://playwright.dev/python for reliability. Let's stick to example.com for simplicity or a more complex interaction on a known sandbox like https://the-internet.herokuapp.com (classic automation testing ground).
Decision: Let's do a script that navigates to a website, searches for something (or clicks a link), and waits for a result.
Step 4: Structuring the Code.
Import necessary modules.
Define a main function.
Use the with statement for resource management.
Refining the Examples:
Example 1: Basic Navigation & Screenshot. Good for sanity check.
Example 2: Interaction (Clicking & Typing). This is the meat of automation.
Example 3: Headless vs. Headed. Explain how to see the browser.
Writing the Explanations:
Locators: Explain page.locator(). Mention text selectors and CSS selectors.
Assertions: Explain the expect library. This is vital for actual testing.
Async: Mention it exists but stick to sync for the primary example as it's easier for general scripting.
Review against Safety/Policy:
Is the request malicious? No, browser automation is a standard developer tool.
Does it target specific real people? No.
Is it for scraping private data? No context implies this; assume general automation/testing.
Final Polish (Self-Correction during drafting):
Correction: Make sure to include from playwright.sync_api import sync_playwright.
Correction: Make sure to emphasize the playwright install command, as that's the #1 error new users face.
Constructing the Final Output: (This aligns with the provided good response).
Prerequisites: pip install, browser install.
Script 1 (Basic): Open, screenshot.
Script 2 (Interaction): Navigate, type, click (using a sandbox site).
Key Concepts: Locators, Waiting, Headless mode.
Final Code Check:
python
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
page = browser.new_page()
page.goto("https://example.com")
# ... actions ...
Looks correct.
Output Generation: (Proceed to generate the response).
Here is a complete guide and a robust Python script to automate browser actions using Playwright.
Prerequisites
Before running the script, you need to install the library and the browser binaries. Open your terminal or command prompt and run:
bash
pip install playwright
playwright install
The Automation Script
This script demonstrates the core features of automation: opening a browser, navigating to a URL, handling keyboard input, clicking buttons, extracting data, and taking screenshots.
I have used Wikipedia as the target because it is stable, allows scraping, and doesn't require logging in.
Create a file named automation.py and paste the following:
python
import time
from playwright.sync_api import sync_playwright
def run_automation():
# 1. Initialize Playwright
with sync_playwright() as p:
# 2. Launch the browser
# headless=False means you will SEE the browser open.
# slow_mo adds a delay so you can watch the actions happen.
browser = p.chromium.launch(headless=False, slow_mo=50)
# 3. Create a new page context
page = browser.new_page()
print("--- Navigating to Wikipedia ---")
# 4. Navigate to a URL
page.goto("https://www.wikipedia.org/")
# 5. Interact with Elements
# Fill the search bar using the ID selector
search_input = page.locator("#searchInput")
search_input.fill("Python (programming language)")
# Click the search button
search_button = page.locator("button[type='submit']")
search_button.click()
# 6. Wait for navigation/page load
# Playwright auto-waits, but sometimes you need to explicitly wait for a specific element
page.wait_for_selector("#firstHeading")
# 7. Extract Data
title = page.locator("#firstHeading").text_content()
print(f"Page Title Found: {title}")
# 8. Take a Screenshot
screenshot_path = "wikipedia_python.png"
page.screenshot(path=screenshot_path)
print(f"Screenshot saved to {screenshot_path}")
# 9. Extract specific data (e.g., the first paragraph)
intro_text = page.locator("#mw-content-text > div.mw-parser-output > p:nth-child(1)").text_content()
print(f"Introduction: {intro_text[:100]}...") # Print first 100 chars
# Optional: Pause to keep browser open until user presses Enter
# useful for debugging.
# page.pause()
# 10. Close browser
browser.close()
if __name__ == "__main__":
run_automation()
How the Script Works
sync_playwright(): This starts the Playwright engine.
p.chromium.launch(...): This starts the browser.
headless=False: By default, Playwright runs invisibly (headless). Setting this to False lets you watch the automation in real-time.
slow_mo=50: Slows down operations by 50ms so you can see what is happening (useful for debugging).
Locators: Playwright uses "Locators" to find elements.
page.locator("#searchInput"): Finds the element with the ID searchInput.
Playwright auto-waits for elements to appear before trying to click or fill them, making the script much more stable than older tools like Selenium.
Data Extraction: .text_content() pulls the text out of the HTML element.
Advanced Features
If you want to take your automation further, here are three common modifications:
1. Using a specific browser
Playwright supports Chromium (Chrome/Edge), Firefox, and WebKit (Safari). You can swap them easily:
python
browser = p.firefox.launch(headless=False)
# OR
browser = p.webkit.launch(headless=False)
2. Handling Multiple Tabs
If a click opens a new tab, you can catch it like this:
python
# Wait for the popup event
with page.expect_popup() as popup_info:
page.get_by_text("Open New Tab").click()
new_page = popup_info.value
# Now interact with the new page
print(new_page.title())
3. Handling Dynamic Content
If the site uses heavy JavaScript, page.wait_for_selector() ensures the script doesn't crash by trying to click an element that hasn't loaded yet.