NodeJS 人偶师:有没有可能设置选择器选项的唯一性?

im9ewurl  于 2023-06-22  发布在  Node.js
关注(0)|答案(1)|浏览(139)

存在如下结构:

<div class="masterselector">
   <div class="selector_what_me_need selector01 selector02"><div>not need value</div></div>
   <div class="selector_what_me_need"><div>need value</div></div>
</div>

如何在类为selector_what_me_needdiv元素中仅选择第二个文本“需要值”?
upd.解决方案(我有很多这个块):

await page.$$eval('.masterselector .selector_what_me_need:not(.selector01):not(.selector02) div', el => el.map(e => e.textContent));
gcmastyq

gcmastyq1#

有很多方法可以选择它,这里有一些:

.selector_what_me_need:not(.selector01)
div:not(.selector01):not(.masterselector)
div[class$=need]

代码:

const puppeteer = require("puppeteer");

const html = `
    <div class="masterselector">
    <div class="selector_what_me_need selector01 selector02">not need value</div>
    <div class="selector_what_me_need">need value</div>
    </div>
`;

let browser;
(async () => {
    browser = await puppeteer.launch({headless: false});
    // const page = await browser.newPage();
    const [page] = await browser.pages();
    await page.setContent(html);

    //let selector = ".selector_what_me_need:not(.selector01)";
    //let selector = "div:not(.selector01):not(.masterselector)";
    let selector = "div[class$=need]";  // means ends with
    let text = await page.$eval(selector, el => el.textContent);     
    console.log(text);

    await browser.close();

})().catch(err => console.error(err));

相关问题