NodeJS 如何使用“p选择器”来选择多个元素(内部阴影DOM)在 puppet 师?

f2uvfpb9  于 2023-06-29  发布在  Node.js
关注(0)|答案(1)|浏览(141)

我知道page.$$,但它使用document.querySelectorAll。我想在shadow DOM内部搜索,为此我使用了Puppeteer的扩展选择器语法(他们称之为“p选择器”)->>>。它在page.waitForSelector上工作得很好,但该API只返回第一个匹配,而不是ElementHandler的数组。对page.$$使用扩展语法不起作用。那么解决方案是什么呢?

y4ekin9u

y4ekin9u1#

您可以将>>>page.$$page.$$eval一起使用,就像使用pierce/一样
代码(示例):

const puppeteer = require("puppeteer");

let browser;
(async () => {
    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();
    let url = "https://webforms.garantibbva.com.tr/currency-convertor/?lang=en";

    await page.goto(url, { waitUntil: "networkidle0", timeout: 15000 });
    await page.waitForSelector("body");
    
    // ex. for page.$$eval
    //let selector = 'pierce/div.currency-table > div.row';
    let selector = "div >>> div.currency-table > div.row";
    let dataArr = await page.$$eval(selector, el => el.map(x => x.textContent.trim()));

    // ex. for page.$$
    let selector2 = "* >>> div.cellCurrTextLeft";
    let rows = await page.$$(selector2);
    let list =[];
    for (let row of rows) {
        let curr = await row.$eval("span", el => el.textContent);
        list.push(curr);
    }

    //ignore start (just formats the data recieved)
    dataArr = dataArr.slice(1);
    let data = dataArr.map((x, i, d) => { return d[i].replace(/,/g, '.').replace(/ +?/g, '').replace(/[\n]{2,}/g, "\n").split('\n'); });
    data = data.map((x, i, d) => [d[i][0], d[i][2], d[i][3]]);
    //ignore end

    console.log(data);
    console.log(list);

})().catch(err => console.error(err)). finally(() => browser ?. close());

如果你仍然有问题,请发布代码。

相关问题