我的网页上有一个按钮,如下所示:
<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:
是对的,页面上有3个按钮。我只想点击第一个。
谢谢!
你的代码应该没问题,假设你
await
.click()
操作:
const playwright = require("playwright"); // ^1.42.1
const html = `<button aria-label="Toggle Comment Thread"></button>`;
let browser;
(async () => {
browser = await playwright.firefox.launch();
const page = await browser.newPage();
await page.setContent(html);
await page
.locator('button[aria-label="Toggle Comment Thread"]')
.first()
.click();
})()
.catch(err => console.error(err))
.finally(() => browser?.close());
请分享一个最小的、可重现的示例。