
最基础的输入操作,用fill()就能搞定:
import timefrom playwright.sync_api import sync_playwrightDEMO_HTML = "E:/PythonProject/Playwrigh/04/demo_page_form.html"with sync_playwright() as p: browser = p.chromium.launch(headless=False) page = browser.new_page(viewport={"width": 1280, "height": 900}) page.goto(f"file:///{DEMO_HTML}")# 使用 fill() 直接填写 page.get_by_test_id("username-input").fill("admin") page.get_by_test_id("email-input").fill("admin@example.com") time.sleep(5) print("输入完成") browser.close()
有些输入框需要模拟按键输入,而不是直接fill(),比如搜索框需要触发键盘事件才会显示搜索建议。这种时候用press_sequentially()逐字输入:
# 模拟真人逐字输入,触发搜索建议search_input = page.get_by_label("搜索")search_input.press_sequentially("Playwright", delay=100)# 100ms 表示每输入一个字符停顿 100 毫秒# 等待搜索建议出现page.wait_for_selector("#search-suggestions", state="visible")知识点:
fill() - 直接填写,速度快
press_sequentially() - 逐字输入,触发键盘事件
delay - 参数控制输入速度,更像真人操作
密码框本质上就是一个type="password"的输入框,Playwright 的操作方式和普通文本框完全一样。
# 填写密码password_input = page.get_by_test_id("password-input")password_input.fill("my_secure_password")# 读取密码值(用于调试)pwd_value = password_input.input_value()print("密码是:", pwd_value)# 确认密码page.get_by_test_id("confirm-password-input").fill("my_secure_password")
读取值的方法:
input_value() - 读取 input/textarea 的当前值
get_attribute("value")- 读取 value 属性(不推荐用于密码框)
03、复选框勾选
勾选框用check()取消勾选用uncheck():
# 勾选"同意协议"agree_checkbox = page.get_by_test_id("agree-checkbox")agree_checkbox.check()# 判断当前是否已勾选is_checked = agree_checkbox.is_checked()print("是否已勾选:", is_checked) # True# 取消勾选agree_checkbox.uncheck()print("是否已勾选:", agree_checkbox.is_checked()) # False
批量勾选示例:
# 勾选多个兴趣标签interests = ["interest-python", "interest-javascript", "interest-go"]for interest in interests: page.get_by_test_id(interest).check()# 验证勾选状态print(page.get_by_test_id("interest-python").is_checked()) # Trueprint(page.get_by_test_id("interest-java").is_checked()) # Falsecheck()
check() 的特点:check()不会报错04、单选按钮
单选按钮的选中同样用check()方法:
# 选择性别为"男"page.get_by_test_id("gender-male").check()# 判断某个选项是否被选中is_male_selected = page.get_by_test_id("gender-male").is_checked()is_female_selected = page.get_by_test_id("gender-female").is_checked()print(f"男: {is_male_selected}, 女: {is_female_selected}")# 切换到"女"page.get_by_test_id("gender-female").check()print(f"男: {page.get_by_test_id('gender-male').is_checked()}") # False
注意事项:
is_checked()验证选中状态05、下拉选择框
这里下拉选择框分两种情况:一种是原生的 <select>标签,可以用select_option()方法;另一种是用 div 或 ul 模拟的下拉菜单,需要用点击的方式操作。
先说原生下拉框:
# 用 value 值来选择country_select = page.get_by_test_id("country-select")country_select.select_option(value="jp") # 选择日本# 用 label(显示文字)来选择country_select.select_option(label="德国")# 编程经验选择experience_select = page.get_by_test_id("experience-select")experience_select.select_option(value="3") # 3-5年
多选下拉框
# 多选下拉框 - 同时选择多个技能skills_select = page.get_by_test_id("skills-select")skills_select.select_option(value=["python", "javascript", "golang"])# 验证选中的值selected_values = skills_select.input_value()print("已选技能:", selected_values)
select_option()三种参数:

06、文件上传
文件上传在 Playwright 里只需要一行set_input_files():
import osimport timefrom playwright.sync_api import sync_playwrightDEMO_HTML = "E:/PythonProject/Playwrigh/04/demo_page_form.html"with sync_playwright() as p: browser = p.chromium.launch(headless=False) page = browser.new_page(viewport={"width": 1280, "height": 900}) page.goto(f"file:///{DEMO_HTML}") time.sleep(5) print("\n[6] 文件上传 - set_input_files()")# 6.1 创建测试文件(与 HTML 同目录) test_dir = "E:/PythonProject/Playwrigh/04/test_files" os.makedirs(test_dir, exist_ok=True) test_file1 = f"{test_dir}/test_upload.txt" test_file2 = f"{test_dir}/test_doc.pdf"# 写入测试内容with open(test_file1, "w", encoding="utf-8") as f: f.write("This is a test file for Playwright upload.")with open(test_file2, "w", encoding="utf-8") as f: f.write("Test PDF content.") print(f" 测试文件已创建: {test_file1}, {test_file2}")# 6.2 单文件上传 avatar_input = page.get_by_test_id("avatar-input") avatar_input.set_input_files(test_file1) print(" 头像已上传: test_upload.txt")# 6.3 多文件上传 docs_input = page.get_by_test_id("documents-input") docs_input.set_input_files([test_file1, test_file2]) print(" 文档已上传: 2 个文件") time.sleep(5) print("输入完成") browser.close()
07、日期选择器
日期选择器比较麻烦,因为不同网站的日期控件实现方式差异很大。原生日期输入框最简单,直接fill()就行:
# 直接输入日期值(格式必须是 YYYY-MM-DD)birthday_input = page.get_by_test_id("birthday-input")birthday_input.fill("1995-06-15")# 读取日期值date_value = birthday_input.input_value()print("选择的日期:", date_value) # 1995-06-15# 入职日期page.get_by_test_id("hire-date-input").fill("2024-01-15")# 项目起止日期page.get_by_test_id("start-date-input").fill("2026-04-01")page.get_by_test_id("end-date-input").fill("2026-06-30")
自定义日期控件:
有些网站用 JavaScript 实现日历弹窗,需要点击操作:
# 点击日期框打开日历page.locator(".date-picker").click()# 选择年份page.locator(".year-select").select_option("2026")# 选择月份page.locator(".month-select").select_option("3") # 4月# 选择日期page.get_by_text("15", exact=True).click()提示:自定义日期控件实现方式各异,建议先用开发者工具查看 HTML 结构。
08、完整实战:模拟注册表单
把上面的操作串起来,模拟一个完整的注册流程:
import timefrom playwright.sync_api import sync_playwrightimport osDEMO_HTML = "E:/PythonProject/Playwrigh/04/demo_page_form.html"with sync_playwright() as p: browser = p.chromium.launch(headless=False) page = browser.new_page(viewport={"width": 1280, "height": 900}) page.goto(f"file:///{DEMO_HTML}") time.sleep(2)# 滚动到注册表单区域 page.evaluate("document.getElementById('register-section').scrollIntoView()") time.sleep(2)# 1. 填写基本信息 page.get_by_test_id("reg-username").fill("demo_user_2026") page.get_by_test_id("reg-email").fill("demo_user@example.com") time.sleep(2)# 2. 填写密码 page.get_by_test_id("reg-password").fill("DemoPass123!") page.get_by_test_id("reg-confirm").fill("DemoPass123!") time.sleep(2)# 3. 填写个人信息 page.get_by_test_id("reg-realname").fill("Demo User") page.get_by_test_id("reg-birthday").fill("1990-01-01") time.sleep(2)# 4. 选择性别 page.get_by_test_id("reg-gender-male").check() time.sleep(2)# 5. 选择国家 page.get_by_test_id("reg-country").select_option(value="cn") time.sleep(2)# 6. 选择兴趣 page.get_by_test_id("reg-interest-coding").check() page.get_by_test_id("reg-interest-reading").check() time.sleep(2)# 7. 填写简介 page.get_by_test_id("reg-bio").fill("Playwright automation enthusiast.") time.sleep(2)# 8. 上传头像 test_file = "E:/PythonProject/Playwrigh/04/test_files/test_upload.txt" page.get_by_test_id("reg-avatar").set_input_files(test_file) time.sleep(2)# 9. 勾选协议 page.get_by_test_id("reg-agree").check() time.sleep(2)# 10. 提交表单 page.get_by_test_id("reg-submit-btn").click() page.wait_for_selector("#register-success", state="visible", timeout=5000) print("注册成功!") time.sleep(10) browser.close()
问题:get_by_label("用户名")匹配到多个元素,报 strict mode violation 错误。
解决:
get_by_test_id()更精确exact=True精确匹配# 可能匹配多个page.get_by_label("用户名").fill("test")# 使用 testidpage.get_by_test_id("username-input").fill("test")# 或精确匹配page.get_by_label("用户名", exact=True).fill("test")问题:get_by_label("密码")同时匹配密码输入框和"显示密码"按钮。
解决:使用exact=True或 testid
# 匹配两个元素page.get_by_label("密码").fill("pass")# 精确匹配page.get_by_label("密码", exact=True).fill("pass")# 使用 testidpage.get_by_test_id("password-input").fill("pass")问题:select_option(label="Germany")找不到选项。
原因:HTML 中显示的是"德国",不是"Germany"。
解决:使用正确的 label 或直接用 value
# 找不到(HTML 中文字是"德国")select.select_option(label="Germany")# 使用正确的中文 labelselect.select_option(label="德国")# 或使用 value(HTML 中 <option value="de">德国</option>)select.select_option(value="de")问题:文件上传失败,找不到文件。
解决:使用绝对路径,确保文件存在。
import osfile_path = "E:/PythonProject/Playwrigh/04/test_files/test.txt"if os.path.exists(file_path): page.get_by_test_id("avatar-input").set_input_files(file_path)else:print("文件不存在!")喜欢小居的文章,点赞、关注、转发,点个“在看”不迷路~
有问题找小居,小居看到马上回!
相关文件
- 测试页面:
demo_page_form.html练习脚本:Playwrigh_04.py源码获取:公众号回复「Playwright04」即可