我试图将变量传递到Puppeteer中的page.evaluate()函数中,但是当我使用以下非常简单的示例时,该变量未定义。evalVar
page.evaluate()
evalVar
我是Puppeteer的新手,找不到任何可构建的示例,因此我需要帮助将该变量传递到page.evaluate()函数中,以便在内部使用它。
const puppeteer = require('puppeteer'); (async() => { const browser = await puppeteer.launch({headless: false}); const page = await browser.newPage(); const evalVar = 'WHUT??'; try { await page.goto('https://www.google.com.au'); await page.waitForSelector('#fbar'); const links = await page.evaluate((evalVar) => { console.log('evalVar:', evalVar); // appears undefined const urls = []; hrefs = document.querySelectorAll('#fbar #fsl a'); hrefs.forEach(function(el) { urls.push(el.href); }); return urls; }) console.log('links:', links); } catch (err) { console.log('ERR:', err.message); } finally { // browser.close(); } })();
您必须pageFunction像这样将变量作为参数传递给:
pageFunction
const links = await page.evaluate((evalVar) => { console.log(evalVar); // should be defined now … }, evalVar);