3 回答

TA贡献1820条经验 获得超10个赞
您可以使用page.evaluate:
const myDiv = await page.evaluate(() => {
const divs = Array.from(document.querySelectorAll('.myDiv'))
return divs.map(d => d.textContent)
});
传递给的函数page.evaluate将被序列化并发送到浏览器,因此它在浏览器上下文(而不是节点)中执行。

TA贡献1828条经验 获得超3个赞
由于您没有提供更多代码,因此这个答案非常自以为是,可能无法解决您的问题。但它向您展示了一种了解正在发生的事情的方法。
特别是在开发过程中,结合使用page.exposeFunction()和page.evaluate()来查看浏览器以及节点/木偶操纵者中发生的事情非常有帮助。这是一个草稿,我希望它能帮助你理解。
(async () => {
function executedInNodeContext(result) {
//this prints in the Node Console
console.log(result);
}
function executedInBrowserContext() {
console.log('Im in the Browser');
const myDiv = [...document.querySelectorAll('.myDiv')];
window.nameOfNodeFunction(myDiv);
}
// See the browser
const browser = await puppeteer.launch({ headless: false });
// Create a new page
const page = await browser.newPage();
// Callback in Node Context
await page.exposeFunction('nameOfNodeFunction', executedInNodeContext);
// Send puppeteer to a Url
await page.goto('http://localhost/awesome/URL');
// Function executed in the Browser on the given page
await page.evaluate(executedInBrowserContext);
})();

TA贡献1811条经验 获得超4个赞
page.$$eval()
在其回调中发送一个包含元素的数组,因此您需要这样的东西来获取所有元素数据:
const myDivs = await page.$$eval(".myDiv", divs => divs.map(div => div.textContent));
添加回答
举报