首页 > 解决方案 > Getting a list of exclusive class name with a class name in puppeteer

问题描述

I am trying to get class names and check if at least one of the tags have red class or not. So, if at least one of them includes red class, the function must return true, otherwise, false.

The closest one is this:

const nodeList = await page.evaluate(() => {
    const arrynodeList = document.querySelectorAll('.an_panel_list')
    return arrynodeList
})

console.log('nodeList:', nodeList)

And I get

nodeList: { '0': {}, '1': {} }

For instance, the html looks like.

<div class="an_panel_list red">
<div class="an_panel_list">
<div class="an_panel_list">
<div class="an_panel_list">

And I get true.

标签: javascriptgoogle-chromepuppeteerwebautomation

解决方案


I would try to solve everything in the evaluate function:

const nodeList = await page.evaluate(() => {
    const arrynodeList = document.querySelectorAll('.an_panel_list');
    const redList = Array.prototype.slice.call(arrynodeList).filter(e => e.classList.contains("red"))
    return {
      divs: arrynodeList.length,
      reds: redList.length
    }
})

console.log(nodeList)

推荐阅读