繁体   English   中英

Puppeteer 如何检查页面上是否存在 class

[英]Puppeteer How to check if class exists on a page

我正在尝试使用 puppeteer 检查网页上是否存在 class。 例如,假设您想抓取某些数据,并且您知道数据存储在某个 class 中。 要抓取数据,您需要使用类名来抓取它。 这是我尝试使用的代码。 这没用。

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

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

运行代码时出现此错误。

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

我不确定您在哪里或如何执行您的示例代码。 如果我们假设它在“评估”函数的回调中,这应该有效:

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()
})()

我希望它有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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