如何获得剧作家的元素集合?

Eug*_*ugZ 5 javascript node.js web-scraping playwright

如何使用剧作家获取页面上的所有图像?我只能ElementHandle通过以下代码获得一个 ( ),但不能获得一个集合。

const { chromium } = require("playwright");

class Parser {
  async parse(url) {
    const browser = await chromium.launch();
    const page = await browser.newPage();
    await page.goto(url);
    await page.waitFor("img");
    // TODO: get somehow collection of elements
    return await page.$("img");
  }
}

module.exports = Parser;
Run Code Online (Sandbox Code Playgroud)

在远处的另一个模块中的某处:

const Parser = require("./path/to/dir/Parser.js");
const parser = new Parser();

parser
    .parse(body.url)
    .then(elemHandle => {
      // here I get only one ElementHandle object, but suppose to get an array or collection
    })
    .catch(err => {
      throw new Error(err);
    });
Run Code Online (Sandbox Code Playgroud)

节点 v.12.16.1

Eug*_*ugZ 9

我已经找到了答案。需要使用page.$$(selector)而不是page.$(selector)去抢像document.querySelectorAll(selector)


Shu*_*rma 8

正如已接受的答案中提到的,您可以使用await page.$$(selector). 这是该页面的链接。$$ 官方文档

您还可以使用以下代码。

const result = await page.evaluate(selector => document.querySelectorAll(selector) , selector);
Run Code Online (Sandbox Code Playgroud)

这是页面的链接。evaluate 官方文档


Man*_*cal 7

您想要使用v1.29locator.all()中添加的新方法来迭代所有匹配元素:

// returns all images on the page & stores them in an array
const images = await page.getByRole('img').all();
Run Code Online (Sandbox Code Playgroud)

不鼓励使用await page.$$(selector);。请改用基于定位器page.locator()您可以在此处阅读有关该方法的信息。


nak*_*bag 6

对于计数,当试图避免使用 时await page.$$(selector);,另一种选择是直接使用 LocatorAssertion:

await expect(locator).toHaveCount(n);
Run Code Online (Sandbox Code Playgroud)

官方文档链接


小智 5

  • 供剧作家使用:await page.$$(selector);