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

范围

🌐 Parameter

类型

🌐 Type

描述

🌐 Description

selector

选择器

🌐 Selector

selector 用于查询页面。CSS selectors 可以按原样传递,Puppeteer-specific selector syntax 允许通过 texta11y role and namexpath 查询,并且可以 combining these queries across shadow roots。或者,你可以使用 prefix 指定选择器类型。

options

WaitForSelectorOptions

(可选) 可选的等待参数

🌐 (Optional) Optional waiting parameters

返回:

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

当通过选择器字符串指定的元素被添加到 DOM 时,Promise 将被解决。如果在等待隐藏状态时选择器在 DOM 中未找到,则解析为 nulltrue

🌐 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
  • hidden:等待元素在 DOM 中找不到或被隐藏,即具有 display: nonevisibility: hidden CSS 属性。默认值为 false
  • timeout:等待的最长时间(以毫秒为单位)。默认为 30000(30 秒)。传入 0 可禁用超时。默认值可以通过使用 Page.setDefaultTimeout() 方法更改。
  • signal:一个信号对象,允许你取消 waitForSelector 调用。

示例

🌐 Example

此方法适用于多种导航:

🌐 This method works across navigations:

import puppeteer from 'puppeteer';

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