Introduction to Playwright-Python: Installation, Usage, and Automation Examples
This article introduces Microsoft’s open‑source Playwright‑Python library, explains how to install it, demonstrates recording and code generation, provides synchronous and asynchronous usage examples—including mobile device emulation—and discusses its advantages and current limitations for web automation testing.
Microsoft has open‑sourced the Playwright‑Python project, a powerful automation tool that can control Chromium, Firefox, and WebKit browsers through a single API, supporting both headless and headed modes on Linux, macOS, and Windows.
1. Playwright Overview
Playwright enables pure Python automation without writing low‑level code, offering fast, reliable, and cross‑browser testing capabilities, including mobile device emulation.
2. Playwright Usage
Installation
pip install playwright
python -m playwright installThe first command installs the Playwright library, and the second installs the required browser drivers.
Recording (codegen)
python -m playwright codegenRunning the above command opens a browser; user actions are recorded and translated into code.
Codegen Options
python -m playwright codegen --help
Usage: index codegen [options] [url]
Options:
-o, --output <file name> saves the generated script to a file
--target <language> language to use, one of javascript, python, python-async, csharp (default: "python")
-h, --help display help for command
Examples:
$ codegen
$ codegen --target=python
$ -b webkit codegen https://example.comExample generated script:
from playwright import sync_playwright
def run(playwright):
browser = playwright.chromium.launch(headless=False)
context = browser.newContext()
page = context.newPage()
page.goto("https://www.baidu.com/")
page.click("input[name=wd]")
page.fill("input[name=wd]", "jingdong")
page.click("text=京东")
with page.expect_navigation():
with page.expect_popup() as popup_info:
page.click("//a[normalize-space(.)='京东JD.COM官网 多快好省 只为品质生活']")
page1 = popup_info.value
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)Synchronous API Example
from playwright import sync_playwright
with sync_playwright() as p:
for browser_type in [p.chromium, p.firefox, p.webkit]:
browser = browser_type.launch()
page = browser.newPage()
page.goto('https://baidu.com/')
page.screenshot(path=f'example-{browser_type.name}.png')
browser.close()Asynchronous API Example
import asyncio
from playwright import async_playwright
async def main():
async with async_playwright() as p:
for browser_type in [p.chromium, p.firefox, p.webkit]:
browser = await browser_type.launch()
page = await browser.newPage()
await page.goto('http://baidu.com/')
await page.screenshot(path=f'example-{browser_type.name}.png')
await browser.close()
asyncio.get_event_loop().run_until_complete(main())Mobile Device Emulation
from playwright import sync_playwright
with sync_playwright() as p:
iphone_11 = p.devices['iPhone 11 Pro']
browser = p.webkit.launch(headless=False)
context = browser.newContext(
**iphone_11,
locale='en-US',
geolocation={'longitude': 12.492507, 'latitude': 41.889938},
permissions=['geolocation']
)
page = context.newPage()
page.goto('https://maps.google.com')
page.click('text="Your location"')
page.screenshot(path='colosseum-iphone.png')
browser.close()Playwright also integrates with pytest for test suites.
3. Summary
Advantages include support for all modern browsers (Chromium, Firefox, WebKit), cross‑platform execution, headless/headed modes, automatic waiting, robust selectors, network interception, and mobile emulation. Limitations are lack of support for legacy Edge/IE11, no Java or Ruby bindings yet, and reliance on desktop browsers for mobile simulation.
Despite these constraints, Playwright continues to evolve (currently at version 1.7.0) and remains a valuable tool for developers seeking a low‑learning‑curve, powerful automation solution.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.