[英]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.