简体   繁体   中英

Puppeteer How to check if class exists on a page

I am trying to use puppeteer to check if a class exists on a webpage. For example let us just say you wanted to scrape certain data and you knew the data was being stored in a certain class. To grab the data you need to use the classname to grab it. Here is the code I am trying to use. It does not work.

        let pageClicked = document.querySelector('.classIAmTryingToFind')

        if(pageClicked){
            console.log('False')
            await browser.close() 
        }else{
            console.log('True')
            await browser.close() 
        }

I get this error when I run the code.

UnhandledPromiseRejectionWarning: Error: Protocol error (Runtime.callFunctionOn): Target closed.

I am not sure where or how you are executing your sample code. If we assume it is inside an 'evaluate' function's callback, this should work:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch()
  const page = await browser.newPage()

  await page.goto('https://stackoverflow.com/', { waitUntil: 'networkidle0' }) // check networkidle0 parameter and others here: https://pptr.dev/#?product=Puppeteer&version=v2.1.1&show=api-pagegotourl-options
  const pageClicked = await page.evaluate(() => {
    return !!document.querySelector('.classIAmTryingToFind') // !! converts anything to boolean
  })
  if (pageClicked) { // you had the condition reversed. Not sure if it was intended.
    console.log('True')
  } else {
    console.log('False')
  }
  await browser.close()
})()

I hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM