【问题标题】:Extract parameter from jQuery to JavaScript function从 jQuery 提取参数到 JavaScript 函数
【发布时间】:2017-11-27 14:52:01
【问题描述】:

我目前正在使用 Puppeteer,每当我调用此函数时,“选择器”都是未定义的。

async function verifyTextPresent(page, selector){
  let myButton = await page.evaluate(() => document.querySelector(selector).innerText);
  console.log(myButton);
}

错误:

(node:6996) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Evaluation failed: ReferenceError: selector is not defined
    at <anonymous>:1:20
(node:6996) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the
Node.js process with a non-zero exit code.

【问题讨论】:

  • 这是在页面准备好之前调用的吗?
  • 是否必须将document 传递给evaluate 函数? page.evaluate(document =&gt; document.querySelector(selector).innerText)。 (另外,可能值得使用textContent 而不是innerText)。

标签: javascript jquery parameter-passing puppeteer


【解决方案1】:

您需要像这样将选择器传递给评估:

async function verifyTextPresent(page, selector){
    let myButton = await page.evaluate((selector) => {
        document.querySelector(selector).innerText);
    }
    console.log(myButton);
}

我也更喜欢使用 $eval 的快捷方式:

let myButton = await page.$eval(selector, e => e.innerText);

【讨论】:

  • 非常感谢劳尔!我最终得到了另一种解决方案,但会尝试你的,因为它更简单。另外,“e”是什么?
  • 没问题,用于个人参考的 e 是元素,但你可以给出任何名称,它是一个包含选择器的变量。
【解决方案2】:

我最终得到了这个解决方案,改变了它得到文本的锯子:

async function verifyTextPresent(page, selector){
  let myButton= await page.$(selector);
  let selectorText = await (await elementForText.getProperty('innerText')).jsonValue();
      console.log(selectorText);
    }

【讨论】:

    猜你喜欢
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    • 2010-10-05
    相关资源
    最近更新 更多