如何在节点js中执行类似于goto语句的操作,或者如何在异步函数中创建和调用函数?

时间:2019-07-20 08:47:11

标签: javascript node.js asynchronous tesseract puppeteer

我正在通过操纵up的人进行自动测试,该人填写了表格并也检查了验证码。如果验证码不正确,它将刷新为新图像,但是我需要再次处理整个图像,并达到先前用于处理它的功能。

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

  /*-----------NEED TO COME BACK HERE-----------*/
  const tessProcess = utils.promisify(tesseract.process);
  await page.setViewport(viewPort)
  await page.goto('http://www.example.com')
  await page.screenshot(options)
  const text = await tessProcess('new.png');
  console.log(text.trim());
  await page.$eval('input[id=userEnteredCaptcha]', (el, value) => el.value = value, text.trim())
  await page.$eval('input[id=companyID]', el => el.value = 'val');
  const submitBtn = await page.$('[id="data"]');
  await submitBtn.click();


  try {
   var x =  await page.waitFor("#msgboxclose");
    console.log("Captcha error")
}
catch (e) {
    console.error('No Error');
}
if(x){
  await page.keyboard.press('Escape');

  /*---------GO FROM HERE--------*/
}

})()

我想创建一个循环,以便每当验证码错误时可以再次处理图像

1 个答案:

答案 0 :(得分:1)

声明一个布尔变量,该布尔变量指示是否需要重试,并将重复的功能放入检查该变量的while循环中。如果循环末尾的x条件不满足,请将tryAgain设置为false,这样就不会发生进一步的迭代:

(async function example() {
  const browser = await puppeteer.launch({headless: false})
  const page = await browser.newPage()
  let tryAgain = true;  // <--------------------------
  while (tryAgain) {    // <--------------------------
    /*-----------NEED TO COME BACK HERE-----------*/
    const tessProcess = utils.promisify(tesseract.process);
    await page.setViewport(viewPort)
    await page.goto('http://www.example.com')
    await page.screenshot(options)
    const text = await tessProcess('new.png');
    console.log(text.trim());
    await page.$eval('input[id=userEnteredCaptcha]', (el, value) => el.value = value, text.trim())
    await page.$eval('input[id=companyID]', el => el.value = 'val');
    const submitBtn = await page.$('[id="data"]');
    await submitBtn.click();


    try {
      var x =  await page.waitFor("#msgboxclose");
      console.log("Captcha error")
    }
    catch (e) {
      console.error('No Error');
    }
    if(x){
      await page.keyboard.press('Escape');
      /*---------GO FROM HERE--------*/
    } else {
      tryAgain = false;   // <--------------------------
    }
  }

})()