Introduction
The Playwright Python Tutorial is the perfect starting point for anyone who wants to automate web applications using Python. Playwright is a modern browser automation framework developed by Microsoft that supports Chromium, Firefox, and WebKit. It is fast, reliable, and designed for testing modern web applications.
If you are a QA Automation Engineer, Selenium tester transitioning to Playwright, Python developer, or software testing student, learning Playwright Python will help you build powerful automation frameworks with less code. In this tutorial, you’ll learn how to use Playwright with Python, create your first automation script, understand enterprise framework concepts, and prepare for Playwright interview questions.
What is Playwright Python?
Playwright Python is the Python implementation of Microsoft’s Playwright framework. It allows you to automate browsers, perform end-to-end testing, and validate web applications across multiple browsers using Python.
With Playwright Python Automation, you can:
- Automate Chromium, Firefox, and WebKit
- Perform cross-browser testing
- Handle modern web applications
- Capture screenshots and videos
- Upload and download files
- Test responsive web applications
- Integrate with CI/CD pipelines
Unlike Selenium, Playwright includes built-in auto-waiting and better handling of dynamic web elements.
Why Use Python with Playwright?
Python is one of the easiest programming languages to learn, making it an excellent choice for automation testing.
Benefits of Playwright with Python
- Simple and readable syntax
- Fast automation execution
- Built-in auto waiting
- Cross-browser support
- Powerful locator strategies
- Easy integration with pytest
- Excellent reporting support
- Suitable for enterprise automation frameworks
Because of these advantages, many organizations are adopting Playwright Python Testing for modern automation projects.
Installing Playwright and Python Setup
Before writing your first script, install Python and Playwright.
Step 1: Install Python
Download and install Python from the official website.
Verify the installation:
python –version
Step 2: Install Playwright
pip install playwright
Step 3: Install Browser Dependencies
playwright install
This downloads Chromium, Firefox, and WebKit browsers required by Playwright.
Writing Your First Playwright Python Script
Create a file named login_test.py.
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”)
print(page.title())
browser.close()
Step-by-Step Explanation
Import Playwright
from playwright.sync_api import sync_playwright
Imports the synchronous Playwright API.
Start Playwright
with sync_playwright() as p:
Launches the Playwright environment.
Launch Browser
browser = p.chromium.launch(headless=False)
Opens the Chromium browser.
- headless=False displays the browser.
- Set it to True for background execution.
Create a New Page
page = browser.new_page()
Creates a new browser tab.
Open Website
page.goto(“https://example.com”)
Navigates to the application URL.
Print Page Title
print(page.title())
Displays the page title in the console.
Close Browser
browser.close()
Closes the browser after test execution.
Working with Locators and Web Elements
Playwright provides multiple locator strategies for interacting with web elements.
ID Locator
page.locator(“#username”).fill(“admin”)
Finds an element using its ID.
CSS Selector
page.locator(“.login-button”).click()
Finds an element using a CSS class.
Text Locator
page.get_by_text(“Login”).click()
Locates an element based on visible text.
Role Locator
page.get_by_role(“button”, name=”Login”).click()
Uses accessibility roles for reliable element identification.
Best Practice: Prefer get_by_role() or data-testid locators because they are more stable than XPath.
Handling Forms, Alerts, Frames, and Multiple Tabs
Filling a Form
page.fill(“#username”, “admin”)
page.fill(“#password”, “admin123”)
page.click(“#login”)
This script enters the username, password, and clicks the Login button.
Handling Alerts
page.on(“dialog”, lambda dialog: dialog.accept())
Automatically accepts JavaScript alert dialogs.
Working with Frames
frame = page.frame(name=”paymentFrame”)
frame.fill(“#cardNumber”, “123456789”)
Switches to an iframe before interacting with its elements.
Handling Multiple Tabs
new_page = page.context.new_page()
new_page.goto(“https://example.com”)
Creates and works with another browser tab.
Screenshots, Videos, and File Upload/Download
Capture Screenshot
page.screenshot(path=”homepage.png”)
Saves a screenshot of the current page.
Upload a File
page.set_input_files(“#upload”, “sample.pdf”)
Uploads a file using the file input element.
Download a File
with page.expect_download() as download_info:
page.click(“text=Download”)
download = download_info.value
download.save_as(“report.pdf”)
Waits for the download to complete and saves it locally.
Enterprise Playwright Python Framework Structure
A well-organized framework improves code maintenance and scalability.
PlaywrightPythonFramework
│
├── tests
│ login_test.py
│
├── pages
│ login_page.py
│ dashboard_page.py
│
├── fixtures
│ conftest.py
│
├── utils
│ read_data.py
│
├── test_data
│ users.json
│
├── reports
│
├── screenshots
│
└── requirements.txt
Folder Explanation
| Folder | Purpose |
| tests | Test scripts |
| pages | Page Object classes |
| fixtures | Shared setup and teardown |
| utils | Helper methods |
| test_data | Test data files |
| reports | HTML reports |
| screenshots | Failure screenshots |
This structure is commonly used in enterprise Playwright Python Frameworks.
Best Practices
Follow these best practices for successful Playwright Python Automation:
- Use the Page Object Model (POM).
- Keep locators inside page classes.
- Use reusable methods.
- Avoid duplicate code.
- Store test data separately.
- Prefer get_by_role() and data-testid locators.
- Use explicit assertions.
- Capture screenshots on failures.
- Generate HTML reports.
- Keep tests independent.
- Follow Python naming conventions.
- Use fixtures for common setup.
- Integrate with Git and CI/CD pipelines.
- Handle exceptions properly.
- Regularly refactor the framework.
Common Mistakes
Avoid these common issues:
- Hardcoding test data.
- Using unstable XPath locators.
- Mixing page logic with test logic.
- Ignoring synchronization.
- Writing duplicate code.
- Keeping all tests in one file.
- Not using assertions.
- Forgetting to close the browser.
Real-Time Automation Scenarios
Scenario 1: Login Automation
- Launch browser
- Open application
- Enter credentials
- Click Login
- Verify dashboard
Scenario 2: E-Commerce Website
Home Page
│
▼
Login
│
▼
Search Product
│
▼
Add to Cart
│
▼
Checkout
│
▼
Order Confirmation
This workflow is commonly automated in enterprise projects.
Scenario 3: File Upload Testing
- Open upload page
- Upload a document
- Verify successful upload
- Capture screenshot
Playwright Python Interview Questions
1. What is Playwright Python?
Playwright’s Python library used for browser automation.
2. Which browsers does Playwright support?
Chromium, Firefox, and WebKit.
3. Why is Playwright faster than Selenium?
Because it includes built-in auto waiting and modern browser automation APIs.
4. What is auto waiting?
Playwright automatically waits for elements to become ready before performing actions.
5. How do you launch a browser?
Use p.chromium.launch().
6. What is a locator?
A method used to identify web elements.
7. What is the Page Object Model?
A design pattern that separates page actions from test scripts.
8. How do you capture screenshots?
Use page.screenshot().
9. Can Playwright handle iframes?
Yes, using the frame() method.
10. Can Playwright automate file uploads?
Yes, using set_input_files().
FAQs
Is Playwright Python free?
Yes. Playwright is open source and free to use.
Is Python required for Playwright?
No. Playwright also supports JavaScript, TypeScript, Java, and .NET.
Is Playwright better than Selenium?
For many modern web applications, Playwright provides faster execution and built-in features such as auto waiting and tracing.
Can beginners learn Playwright Python?
Yes. Python’s simple syntax makes Playwright easy to learn.
Does Playwright support pytest?
Yes. Playwright integrates seamlessly with pytest.
Can Playwright run tests in parallel?
Yes. Parallel execution is supported.
Does Playwright support CI/CD?
Yes. It integrates with Jenkins, GitHub Actions, Azure DevOps, GitLab CI, and other CI/CD platforms.
Can Playwright capture videos?
Yes. Playwright can record videos during test execution.
