You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Playwright输入日期字段时出现Locator无法JSON序列化的TypeError

解决向日期字段输入DDMMYYYY格式时的TypeError错误

向日期字段输入DDMMYYYY格式日期时,触发如下错误:

TypeError: Object of type Locator is not JSON serializable

你的代码如下:

searchBy_start_date_created_field = page.locator("#s_startcreateddate")  #locator

page.wait_for_selector(self.searchBy_start_date_created_field) #waiting for locator
searchBy_start_date_created_field.clear() #clear field
searchBy_start_date_created_field.clear().fill(datecreatedstart) #enter data into date field

问题原因

  1. wait_for_selector参数错误:page.wait_for_selector()需要传入选择器字符串,你错误传入了Locator对象(还误用self.引用局部变量),导致系统尝试序列化Locator对象时失败,抛出TypeError。
  2. 冗余的链式调用:虽然Playwright支持Locator方法链式调用,但clear().fill()的写法容易引发逻辑混淆,且若clear()执行异常会直接影响后续填充操作。

修正后的代码

方案一:使用Locator自身的wait方法(推荐)

searchBy_start_date_created_field = page.locator("#s_startcreateddate")

# 等待定位器对应元素加载完成,替代page.wait_for_selector
searchBy_start_date_created_field.wait_for()

searchBy_start_date_created_field.clear()
searchBy_start_date_created_field.fill(datecreatedstart)

方案二:正确使用page.wait_for_selector

selector = "#s_startcreateddate"
# 传入选择器字符串而非Locator对象
page.wait_for_selector(selector)

searchBy_start_date_created_field = page.locator(selector)
searchBy_start_date_created_field.clear()
searchBy_start_date_created_field.fill(datecreatedstart)

额外处理建议

如果日期格式输入仍有异常,可尝试模拟键盘逐字符输入:

searchBy_start_date_created_field.clear()
searchBy_start_date_created_field.press_sequence(datecreatedstart)

内容的提问来源于stack exchange,提问作者Manoj Soundarrajan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 13:20:03