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

Playwright Python点击Angular页面按钮报错:'Locator'对象不可调用

解决Playwright Python中'Locator' object is not callable报错

核心错误原因

你的代码中调用了.first(),但Playwright的Locator对象里,first是只读属性而非可调用方法,加括号会直接触发'Locator' object is not callable报错。

修正后的代码

把.first()改为.first即可正常运行:

button = page.locator("button.p-ripple").first
button.click()

也可以直接链式调用简化代码:

page.locator("button.p-ripple").first.click()

针对nth(index)的修正

你提到用nth(index)也失败,同样是用法错误:nth是需要传入索引参数的方法,正确写法为:

# 定位第一个元素(索引从0开始)
page.locator("button.p-ripple").nth(0).click()

更精准的定位方式(适配PrimeNG按钮)

由于目标是Angular PrimeNG的p-button组件,还可以用以下更可靠的定位逻辑:

  • 按按钮文本定位:
page.get_by_role("button", name="Button2").click()
  • 结合图标类名定位:
page.locator("button.p-ripple:has(.pi-search)").click()

验证依据

根据你提供的信息:

  • DOM查询document.querySelectorAll("button.p-ripple")能返回目标元素,说明选择器本身有效
  • 按钮HTML结构确认是带p-ripple类的button元素,定位方向正确

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 17:00:01