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 | 选择器 | 要查询页面的 selector。CSS 选择器 可以按原样传递,Puppeteer 特定的选择器语法 允许通过 text、a11y 角色和名称、xpath 和 跨影子根组合这些查询 进行查询。或者,你可以使用 prefix 指定选择器类型。 |
options | (可选的)可选等待参数 |
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: none
或visibility: hidden
CSS 属性。默认为false
。¥
visible
: A boolean wait for element to be present in DOM and to be visible, i.e. to not havedisplay: none
orvisibility: hidden
CSS properties. Defaults tofalse
. -
hidden
:等待元素在 DOM 中找不到或被隐藏,即具有display: none
或visibility: hidden
CSS 属性。默认为false
。¥
hidden
: Wait for element to not be found in the DOM or to be hidden, i.e. havedisplay: none
orvisibility: hidden
CSS properties. Defaults tofalse
. -
timeout
:等待的最长时间(以毫秒为单位)。默认为30000
(30 秒)。通过0
禁用超时。可以使用 Page.setDefaultTimeout() 方法更改默认值。¥
timeout
: maximum time to wait for in milliseconds. Defaults to30000
(30 seconds). Pass0
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();
})();