提问者:小点点

如何用nodeJS在puppeteer中调用异步函数之外函数


如何在puppeteer中调用在异步方法之外传递页面对象的函数。

我想实现一个功能,如果在页面上找到某个值,它应该播放音乐。我在异步方法之外定义了playmusic()功能。

const puppeteer = require('puppeteer');

const playmusic = ()=>{
   page.goto('http://www.noiseaddicts.com/free-samples-mp3/?id=2544');
   page.click('span.map_play');
}

(async () => {
  const browser = await puppeteer.launch({headless : false});
  
  const page = await browser.newPage();

 
  await page.goto('DesiredURL');
  const pricing = await page.evaluate(()=>{
    let pricesOnPage=document.querySelectorAll(".span_price_wrap");
    const priceList=[...pricesOnPage];
    return priceList.map(h=>h.innerText);
    
  });
  console.log(pricing[1]);

  if(pricing[1]>=2316)
  {
    await page.evaluate(() => {
      playmusic ();
    });
  }

 await browser.close();
})();

我正在低于错误

\index.js
2346.75
(node:17316) UnhandledPromiseRejectionWarning: Error: Evaluation failed: ReferenceError: playmusic is not defined
    at __puppeteer_evaluation_script__:2:6
    at ExecutionContext._evaluateInternal (\jswebscrapping\node_modules\puppeteer\lib\cjs\puppeteer\common\ExecutionContext.js:217:19)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async ExecutionContext.evaluate (\jswebscrapping\node_modules\puppeteer\lib\cjs\puppeteer\common\ExecutionContext.js:106:16)
    at async index.js:24:4
(node:17316) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:17316) [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.

分享可行的代码:感谢大家的帮助,我已经在以下几个地方改进了我的代码

>

  • 添加了播放音乐前后的等待时间。

    转换后的float返回值(以前它被视为字符串)

    常量puppeteer=require('puppeteer');

    常量playmusic=async(页面)=>{await page.goto('http://www.noiseaddicts.com/free-samples-mp3/?id=2544');await page.waitfor(4000);await page.click('span.map_play');await page.waitfor(12000);}

    (async()=>{const browser=await puppeteer.launch({headless:false});

    常量页=等待Browser.NewPage();

    await page.goto(“MyURL”);const pricing=await page.evaluate(()=>{let pricesonpage=document.QuerySelectorAll(“.span_price_wrap”);const pricelist=[...pricesonpage];return pricelist.map(H=>H.innertext);

    });console.log(定价[1]);let pricingfloat=parseFloat(定价[1]);

    if(PricingFloat<;=21){await playmusic(page);
    }else{console.log(“no Music for you”);}

    等待Browser.Close();})();


  • 共1个答案

    匿名用户

    您需要替换

    const playmusic = ()=>{
       page.goto('http://www.noiseaddicts.com/free-samples-mp3/?id=2544');
       page.click('span.map_play');
    }
    

    const playmusic = (page) => {
       page.goto('http://www.noiseaddicts.com/free-samples-mp3/?id=2544');
       page.click('span.map_play');
    }
    

        await page.evaluate(() => {
          playmusic ();
        });
    

        await page.evaluate(() => {
          playmusic (page);
        });
    

    由于page存在时的范围受到限制,并且当您定义函数playmusic时,此函数无权访问变量page。您可以阅读更多关于JS中的variablescopes的内容。

    链接到一篇伟大的文章:

    https://www.sitepoint.com/demystifyingy-javascript-variable-scope-hoosting/

    更新

    在分析了错误代码之后,我认为您需要添加一个try-catch块。比如。

    try {
        await page.evaluate(() => {
          playmusic (page);
        });
    } catch(e) {
       console.log(e);
       process.exit(1)
    }
    

    你也应该检查木偶演员是否有未被拒绝的承诺:

    https://pptr.dev/#?product=puppeteer&version=v5.3.0&show=api-class-page

    例如,你可以写:

    const playmusic = async (page) => {
       await page.goto('http://www.noiseaddicts.com/free-samples-mp3/?id=2544');
       return page.click('span.map_play');
    }
    

    在主代码中:

    try {
        await page.evaluate(async () => {
          try {
             await playmusic();
          } catch(e) {
              console.log(e);
              process.exit(1);
          }
        });
    } catch(e) {
       console.log(e);
       process.exit(1)
    }