Frontend Development 7 min read

Playwright Guide: Form Filling, File Upload/Download, Keyboard Shortcuts, and Validation in UI Automation

This article demonstrates how to use Playwright for UI automation by showing how to fill various form fields, upload and download files, simulate keyboard shortcuts and combinations, and handle form validation and errors, providing complete Python code examples for each scenario.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Playwright Guide: Form Filling, File Upload/Download, Keyboard Shortcuts, and Validation in UI Automation

Introduction: In UI automation testing, simulating user interactions such as filling forms, uploading files, and using keyboard shortcuts is essential, and Playwright provides convenient APIs for these tasks.

1. Filling Form Fields Playwright offers simple APIs to locate and populate various form elements. The example code demonstrates launching a Chromium browser, navigating to a form page, filling text inputs, selecting dropdown options, checking boxes, clicking radio buttons, and submitting the form.

from playwright.sync_api import sync_playwright
def run(playwright):
    browser = playwright.chromium.launch(headless=False)
    page = browser.new_page()
    # 导航到包含表单的网页
    page.goto("https://example.com/form")
    # 填写文本框
    page.fill('input[name="username"]', 'myUsername')
    page.fill('input[name="password"]', 'myPassword')
    # 选择下拉菜单中的选项
    page.select_option('select[name="country"]', 'China')
    # 复选框
    page.check('input[name="agreeTerms"]')
    # 单选按钮
    page.click('input[type="radio"][value="male"]')
    # 提交表单
    page.click('button[type="submit"]')
    browser.close()
with sync_playwright() as playwright:
    run(playwright)

The code shows how to handle different form elements and submit the form.

2. File Upload and Download Playwright supports both uploading files via an <input type="file"> element and downloading files by configuring the browser’s download path. Example snippets illustrate setting input files and triggering a download, with a pause to wait for completion.

# 上传文件
page.set_input_files('input[type="file"]', 'path/to/file.txt')
browser = playwright.chromium.launch(headless=False, downloads_path='./downloads')
page = browser.new_page()
# 触发下载操作
page.click('a.download-link')
# 等待文件下载完成(这里需要根据实际情况添加等待逻辑)
import time
time.sleep(5)  # 暂停几秒等待下载完成
browser.close()

After triggering a download, you can listen for download events or inspect the download directory to verify success.

3. Simulating Keyboard Shortcuts and Combinations Playwright can simulate complex keyboard actions such as typing text, pressing Enter, and using shortcuts like Ctrl+A, Ctrl+C, and Ctrl+V. For macOS users, replace “Control” with “Meta”.

# 输入文本并按回车键
page.type('textarea[name="message"]', 'Hello World')
page.press('textarea[name="message"]', 'Enter')
# 使用Ctrl+A全选文本
page.press('textarea[name="message"]', 'Control+A')
# 使用Ctrl+C复制选中文本
page.press('textarea[name="message"]', 'Control+C')
# 使用Ctrl+V粘贴文本
page.press('textarea[name="message"]', 'Control+V')

4. Form Validation and Error Handling Real‑world forms often have front‑end validation rules. The article shows how to catch exceptions when submitting incomplete forms, retrieve error messages, and use Playwright assertions to verify element visibility and input values.

try:
    # 尝试提交未填写完整信息的表单
    page.click('button[type="submit"]')
except Exception as e:
    print(f"Error occurred: {e}")
# 查找并打印错误消息
error_message = page.text_content('.error-message')  # 假设错误消息位于带有.error-message类的元素中
print(error_message)
# 确认某个元素存在
assert page.locator('.success-message').is_visible(), "成功消息未显示"
# 验证输入框的值
expected_value = "Expected Value"
actual_value = page.input_value('input[name="username"]')
assert actual_value == expected_value, f"Expected '{expected_value}', but got '{actual_value}'"

Proper error handling and assertions improve the reliability and accuracy of automated test scripts.

Conclusion: By following this guide you should be able to use Playwright to fill form fields, upload and download files, simulate keyboard shortcuts, and handle validation errors, thereby increasing test coverage and quality.

PythonUI automationFile UploadPlaywrightForm Testingkeyboard shortcuts
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.