Playwright JavaScript无法填充含readonly属性的密码输入框求助
解决Playwright无法填充readonly密码输入框的问题
在注册流程中,使用Playwright的fill()方法填充带有readonly属性的密码输入框时触发超时错误,日志显示元素不可编辑,但相同操作在Selenium中可正常执行。
相关代码与报错信息
对应的HTML结构:
<div class="form-item RegistrationForm_password"> <label for="RegistrationForm_password" class="form-label"><span class="form-label-text">Password</span><span class="required-field">*</span></label><div class="form-field"> <span class="password-visibility-icon icon-hide"></span> <input type="password" id="RegistrationForm_password" name="RegistrationForm[password]" placeholder="" autocomplete="off" class="form-field-element" readonly="readonly"></div></div>
执行的Playwright代码:
await page.locator("//input[@id='RegistrationForm_password']").fill("Password")
触发的错误:
locator.fill: Test timeout of 30000ms exceeded.
日志关键内容:
- waiting for element to be visible, enabled and editable
- element is not editable
- retrying fill action, attempt #1
- element is not editable
原因分析
Playwright的fill()方法默认会严格校验元素是否处于**可编辑(editable)**状态,带有readonly属性的输入框不满足该条件,因此会持续重试直至超时;而Selenium的sendKeys()方法对readonly元素的交互限制更宽松,所以可以执行成功。
可行解决方案
1. 移除readonly属性后填充
通过JavaScript移除输入框的readonly属性,再调用fill()方法:
// 移除readonly属性 await page.locator("#RegistrationForm_password").evaluate(el => el.removeAttribute("readonly")); // 填充密码 await page.locator("#RegistrationForm_password").fill("Password");
2. 直接通过JavaScript设置输入框值
跳过Playwright的交互校验,直接用JS修改输入框的value属性:
await page.locator("#RegistrationForm_password").evaluate(el => el.value = "Password");
这种方式无需移除readonly属性,适合仅需设置值、无需模拟真实输入行为的场景。
3. 触发页面内置的可编辑逻辑(若存在)
观察HTML结构,密码输入框旁有password-visibility-icon元素,部分网站会在点击该图标时移除输入框的readonly属性以允许输入。可尝试先点击图标再填充:
// 点击密码可见性图标 await page.locator(".password-visibility-icon").click(); // 填充密码 await page.locator("#RegistrationForm_password").fill("Password");
该方案需结合页面实际交互逻辑判断是否适用。
内容的提问来源于stack exchange,提问作者Nakshatra
相关产品推荐
相关产品推荐

