【问题标题】:Puppeteer: How do I get the value from the loop?Puppeteer:我如何从循环中获取价值?
【发布时间】:2020-11-23 19:35:03
【问题描述】:

我需要在页面上加载代码,该代码将在循环中检查一个元素的值,并在需要之后返回该值。 我怎样才能正确地做到这一点?

【问题讨论】:

    标签: javascript node.js asynchronous async-await puppeteer


    【解决方案1】:

    你的问题真的很模糊,所以我确定我是否理解正确,但你可能正在寻找 page.evaluate()。使用此函数,您可以在浏览器上下文中执行代码,然后返回一些信息。

    例如:

    var output = await page.evaluate(() => {
            let urlSelector= '#someId > tbody > tr:nth-child(1) > td:nth-child(2) > a';
            let desiredUrl = document.querySelector(urlSelector).href;
            console.log(desiredUrl);//print the url in browser console
            return desiredUrl;
    });
    console.log(output);//prints the url in node console
    

    在本例中,我在浏览器上下文中执行了代码,并将所需的 url 返回到脚本中的“输出”变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-16
      • 1970-01-01
      • 2021-08-14
      相关资源
      最近更新 更多