Skip to main content
Version: 23.5.0

Page.waitForSelector() 方法

¥Page.waitForSelector() method

等待 selector 出现在页面中。如果在调用该方法时 selector 已经存在,该方法将立即返回。如果等待 timeout 毫秒后 selector 没有出现,函数将抛出异常。

¥Wait for the selector to appear in page. If at the moment of calling the method the selector already exists, the method will return immediately. If the selector doesn't appear after the timeout milliseconds of waiting, the function will throw.

签名

¥Signature

class Page {
waitForSelector<Selector extends string>(
selector: Selector,
options?: WaitForSelectorOptions
): Promise<ElementHandle<NodeFor<Selector>> | null>;
}

参数

¥Parameters

范围

类型

描述

selector

选择器

要查询页面的 selectorCSS 选择器 可以按原样传递,Puppeteer 特定的选择器语法 允许通过 texta11y 角色和名称xpath跨影子根组合这些查询 进行查询。或者,你可以使用 prefix 指定选择器类型。

options

WaitForSelectorOptions

(可选的)可选等待参数

Returns:

Promise<ElementHandle<NodeFor<Selector>> | null>

当选择器字符串指定的元素添加到 DOM 时解析的 Promise。如果等待隐藏则解析为 null:在 DOM 中找不到 true 和选择器。

¥Promise which resolves when element specified by selector string is added to DOM. Resolves to null if waiting for hidden: true and selector is not found in DOM.

备注

¥Remarks

参数 options 中的可选参数是:

¥The optional Parameter in Arguments options are:

  • visible:布尔值等待元素出现在 DOM 中并且可见,即不具有 display: nonevisibility: hidden CSS 属性。默认为 false

    ¥visible: A boolean wait for element to be present in DOM and to be visible, i.e. to not have display: none or visibility: hidden CSS properties. Defaults to false.

  • hidden:等待元素在 DOM 中找不到或被隐藏,即具有 display: nonevisibility: hidden CSS 属性。默认为 false

    ¥hidden: Wait for element to not be found in the DOM or to be hidden, i.e. have display: none or visibility: hidden CSS properties. Defaults to false.

  • timeout:等待的最长时间(以毫秒为单位)。默认为 30000(30 秒)。通过 0 禁用超时。可以使用 Page.setDefaultTimeout() 方法更改默认值。

    ¥timeout: maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout. The default value can be changed by using the Page.setDefaultTimeout() method.

示例

¥Example

此方法适用于多种导航:

¥This method works across navigations:

import puppeteer from 'puppeteer';
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
let currentURL;
page
.waitForSelector('img')
.then(() => console.log('First URL with image: ' + currentURL));
for (currentURL of [
'https://example.com',
'https://google.com',
'https://bbc.com',
]) {
await page.goto(currentURL);
}
await browser.close();
})();