TypeError: 使用Playwright的.first()时'Locator'对象不可调用

2 投票
1 回答
133 浏览
提问于 2025-04-14 16:27

我在网页上有一个按钮,长得像这样:

<button rpl="" aria-controls="comment-children" aria-expanded="true" aria-label="Toggle Comment Thread" class="text-neutral-content-strong bg-neutral-background overflow-visible w-md h-md
button-small px-[var(--rem6)]
button-plain


icon
items-center justify-center
button inline-flex "> <!--?lit$747127195$--><!----><span class="flex items-center justify-center"> <!--?lit$747127195$--><span class="flex"><!--?lit$747127195$--><svg rpl="" fill="currentColor" height="16" icon-name="leave-outline" viewBox="0 0 20 20" width="16" xmlns="http://www.w3.org/2000/svg"> <!--?lit$747127195$--><!--?lit$747127195$--><path d="M14 10.625H6v-1.25h8v1.25ZM20 10a10 10 0 1 0-10 10 10.011 10.011 0 0 0 10-10Zm-1.25 0A8.75 8.75 0 1 1 10 1.25 8.76 8.76 0 0 1 18.75 10Z"></path><!--?--> </svg></span> <!--?lit$747127195$--> </span> <!--?lit$747127195$--><!--?--><!----><!----><!----> </button>

我想在我的Python代码中用Playwright来点击这个按钮。我写了:

page.locator('button[aria-label="Toggle Comment Thread"]').first().click()

可惜的是,它给我报了个错,错误信息是 TypeError: 'Locator' object is not callable。当我不使用 first() 的时候,它说:

Error: Error: strict mode violation: locator("button[aria-label=\"Toggle Comment Thread\"]") resolved to 3 elements:

这没错,页面上确实有三个这样的按钮。我只想点击第一个。

1 个回答

4

试试用 .first 而不是 .first()

page.locator('button[aria-label="Toggle Comment Thread"]').first.click()

可运行的例子:

from playwright.sync_api import sync_playwright # 1.40.0

html = '<button aria-label="Toggle Comment Thread"></button>'

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.set_content(html)
    page.locator('button[aria-label="Toggle Comment Thread"]').first.click()
    browser.close()

不过,建议使用 get_by_role

page.get_by_role("button", name="Toggle Comment Thread").first.click()

而且尽量避免使用 .first;找一种更严格的方法来唯一识别这个元素(可以考虑用它的其他属性),而不是依赖页面上元素的顺序,因为这个顺序可能会意外改变。

撰写回答