Skip to main content
Version: 24.38.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

范围

🌐 Parameter

类型

🌐 Type

描述

🌐 Description

selector

选择器

🌐 Selector

要查询和等待的选择器。

🌐 The selector to query and wait for.

options

WaitForSelectorOptions

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

🌐 (Optional) Options for customizing waiting behavior.

返回:

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';

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();