メインコンテンツへスキップ
バージョン: 22.5.0

Page.$$eval() メソッド

このメソッドは、ページ内で Array.from(document.querySelectorAll(selector)) を実行し、その結果を最初の引数として pageFunction に渡します。

シグネチャ:

class Page {
$$eval<
Selector extends string,
Params extends unknown[],
Func extends EvaluateFuncWith<
Array<NodeFor<Selector>>,
Params
> = EvaluateFuncWith<Array<NodeFor<Selector>>, Params>,
>(
selector: Selector,
pageFunction: Func | string,
...args: Params
): Promise<Awaited<ReturnType<Func>>>;
}

パラメータ

パラメータ説明
selectorSelectorクエリ対象のセレクタ
pageFunctionFunc | stringページコンテキストで評価される関数。Array.from(document.querySelectorAll(selector)) の結果が最初の引数として渡されます。
argsParamspageFunction に渡す追加の引数。

戻り値

Promise<Awaited<ReturnType<Func>>>

pageFunction の呼び出し結果。要素を返す場合は ElementHandle でラップされ、それ以外の場合は元の値が返されます。

備考

pageFunction が promise を返す場合、$$eval は promise が解決されるのを待ってからその値を返します。

例 1

// get the amount of divs on the page
const divCount = await page.$$eval('div', divs => divs.length);

// get the text content of all the `.options` elements:
const options = await page.$$eval('div > span.options', options => {
return options.map(option => option.textContent);
});

TypeScript を使用している場合は、pageFunction の最初の引数に明示的な型を指定する必要がある場合があります。デフォルトでは Element[] として型付けされていますが、より具体的なサブタイプを指定する必要がある場合があります。

例 2

// if you don't provide HTMLInputElement here, TS will error
// as `value` is not on `Element`
await page.$$eval('input', (elements: HTMLInputElement[]) => {
return elements.map(e => e.value);
});

コンパイラは、提供した pageFunction から戻り値の型を推論できるはずです。推論できない場合は、ジェネリック型を使用して、$$eval から期待される戻り値の型をコンパイラに伝えることができます。

例 3

// The compiler can infer the return type in this case, but if it can't
// or if you want to be more explicit, provide it as the generic type.
const allInputValues = await page.$$eval<string[]>(
'input',
(elements: HTMLInputElement[]) => elements.map(e => e.textContent)
);