简体   繁体   English

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

[英]How do I call function outside async function in puppeteer with nodeJS

how do I call a function passing the page object outside async method in puppeteer.如何在 puppeteer 中调用在异步方法之外传递页面对象的函数。

I want to implement a functionality where if a certain value is found on page it should play a music.我想实现一个功能,如果在页面上找到某个值,它应该播放音乐。 I have defined playmusic() functionality outside async method .我在 async method 之外定义了 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();
})();

I m getting below error我得到以下错误

\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.

------------------------------UPDATE-------------------------------------------- - - - - - - - - - - - - - - - 更新 - - - - - - - - - - -------------------------

Sharing the workable code: Thanks everyone for helping I have improved my code in couple of places such as分享可行的代码:感谢大家帮助我在几个地方改进了代码,例如

  1. added wait time before and after playing the music .在播放音乐之前和之后增加了等待时间。
  2. Converted return value in float ( earlier it was treated as string )以 float 形式转换的返回值(之前它被视为字符串)
const puppeteer = require('puppeteer');

 const playmusic = async (page)=>{
  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});
  
  const page = await 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(pricing[1]);
  let PricingFloat= parseFloat(pricing[1]);

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

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

You need to replace你需要更换

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

by经过

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

and

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

by经过

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

Because of range when page exists is constrained and when you define function playmusic then this function do not have access to variable page .由于page存在时的范围受到限制,并且当您定义函数playmusic此函数无权访问变量page You can read more about variables scopes in JS.您可以阅读有关 JS 中variables scopes更多信息。

Link to a great article:链接到一篇很棒的文章:

https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/ https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/


UPDATE更新

After analyzing your code of error I think you need to add a try-catch block.在分析您的错误代码后,我认为您需要添加一个 try-catch 块。 For example.例如。

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

You should also check if the puppeteer does not have unrejected promised:您还应该检查木偶操纵者是否没有未拒绝的承诺:

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

For example, you can write:例如,您可以编写:

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

and in your main code:并在您的主要代码中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM