本文介绍了page.evaluate中的puppeteer引用错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨我正在学习木偶无头浏览器,但有些东西我不明白

Hi im learning puppeteer headless browser, but there is something that i dont understand

1)为什么我不能使用变量作为选择器?

1) why i cant use a variable as a selector?

这是有效的

  const lastUpdate = await page.evaluate(() => document.querySelector('body > table > tbody > tr:nth-child(2) > td > table > tbody > tr:nth-child(3) > td:nth-child(2) > strong').textContent);

但是这给了我参考错误LAST_UPDATE SELECTOR未定义

but this give me reference error LAST_UPDATE SELECTOR is not defined

const LAST_UPDATE_SELECTOR = 'body > table > tbody > tr:nth-child(2) > td > table > tbody > tr:nth-child(3) > td:nth-child(2) > strong';
const lastUpdate = await page.evaluate(() => document.querySelector(LAST_UPDATE_SELECTOR).textContent);

我做错了什么?也许有一些我需要学习的东西

What im doing wrong? maybe there is something new that i need to learn

谢谢!

推荐答案

将变量作为参数传递给 evaluate 函数。

Pass the variable to the evaluate function as an argument.

const selector = '#someSelector';

// 2. read the passed data
const lastUpdate = await page.evaluate((selector) => { 

  // 3. use it here
  document.querySelector(selector).textContent, 

// 1. Pass it here
}, selector); 

发生了什么事?

.evaluate 接受两个参数, pageFunction ,其余参数序列化 args 。当运行pageFunction时,它将参数传递给它,然后它在浏览器上下文中可用。

.evaluate accepts two arguments,pageFunction, and the rest are serialized args. When running the pageFunction, it passes the arguments to that, and then it becomes available inside the browser context.

在puppeteer上了解更多关于它的信息。

Learn more about it on the puppeteer API docs.

这篇关于page.evaluate中的puppeteer引用错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 22:28