Skip to main content
Version: 23.2.0

Page.click()方法

¥Page.click() method

此方法使用 selector 获取元素,如果需要,将其滚动到视图中,然后使用 Page.mouse 单击元素的中心。如果没有与 selector 匹配的元素,该方法将抛出错误。

¥This method fetches an element with selector, scrolls it into view if needed, and then uses Page.mouse to click in the center of the element. If there's no element matching selector, the method throws an error.

签名

¥Signature

class Page {
click(selector: string, options?: Readonly<ClickOptions>): Promise<void>;
}

参数

¥Parameters

范围

类型

描述

selector

string

要查询页面的 selectorCSS 选择器 可以按原样传递,Puppeteer 特定的选择器语法 允许通过 texta11y 角色和名称xpath跨影子根组合这些查询 进行查询。或者,你可以使用 prefix 指定选择器类型。如果有多个元素满足 selector,则点击第一个

options

只读<ClickOptions>

(可选的)Object

Returns:

Promise<void>

当成功单击与 selector 匹配的元素时,该 Promise 将会解析。如果没有匹配 selector 的元素,则 Promise 将被拒绝。

¥Promise which resolves when the element matching selector is successfully clicked. The Promise will be rejected if there is no element matching selector.

备注

¥Remarks

请记住,如果 click() 触发导航事件,并且有一个单独的 page.waitForNavigation() promise 需要解决,那么你最终可能会遇到产生意外结果的竞争条件。单击并等待导航的正确模式如下:

¥Bear in mind that if click() triggers a navigation event and there's a separate page.waitForNavigation() promise to be resolved, you may end up with a race condition that yields unexpected results. The correct pattern for click and wait for navigation is the following:

const [response] = await Promise.all([
page.waitForNavigation(waitOptions),
page.click(selector, clickOptions),
]);

page.mainFrame().click(selector[, options]) 的快捷方式。

¥Shortcut for page.mainFrame().click(selector[, options]).