Skip to main content
Version: 23.8.0

ElementHandle.waitForSelector() 方法

¥ElementHandle.waitForSelector() method

等待与给定选择器匹配的元素出现在当前元素中。

¥Wait for an element matching the given selector to appear in the current element.

Frame.waitForSelector() 不同,此方法不适用于跨导航或元素与 DOM 分离的情况。

¥Unlike Frame.waitForSelector(), this method does not work across navigations or if the element is detached from DOM.

签名

¥Signature

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

参数

¥Parameters

范围

类型

描述

selector

选择器

要查询和等待的选择器。

options

WaitForSelectorOptions

(可选的)用于自定义等待行为的选项。

Returns:

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

与给定选择器匹配的元素。

¥An element matching the given selector.

异常

¥Exceptions

如果未出现与给定选择器匹配的元素,则抛出该异常。

¥Throws if an element matching the given selector doesn't appear.

示例

¥Example

import puppeteer from 'puppeteer';

(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
let currentURL;
page
.mainFrame()
.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();
})();