如何在Node.js中处理同步浏览器仿真

时间:2019-02-01 04:29:58

标签: node.js browser emulation nightmare

我正在编写一个脚本,该脚本旨在从.txt文件中加载某些内容,然后对具有node.js浏览器模拟器噩梦的网站执行多个请求(循环)。

我从txt文件中读取文件没有问题,所以没有,但是设法使其保持同步并且没有例外。

function visitPage(url, code) {
new Promise((resolve, reject) => {
    Nightmare
      .goto(url)
      .click('.vote')
              .insert('input[name=username]', 'testadmin')
              .insert('.test-code-verify', code)
      .click('.button.vote.submit')
      .wait('.tag.vote.disabled,.validation-error')
      .evaluate(() => document.querySelector('.validation -error').innerHTML)
      .end()
      .then(text => {
          return text;
      })
});
}


async function myBackEndLogic() {
try {
    var br = 0, user, proxy, current, agent;


    while(br < loops){

        current = Math.floor(Math.random() * (maxLoops-br-1));

        /*...getting user and so on..*/




        const response = await visitPage('https://example.com/admin/login',"code")

        br++;
    }


} catch (error) {
    console.error('ERROR:');
    console.error(error);
}
}

myBackEndLogic();

发生的错误是: UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“ webContents”

问题是几个:

1)如何解决异常

2)如何使它实际上每次地址都同步并仿真(如上一次尝试(我没有保存,我修复了该异常,但实际上并未打开浏览器,并且基本上跳过了该操作<) / p>

3)(不是很重要)是否可以选择一些对象

.wait('.class1,.class2,.validation-error')

将每个值保存在不同的变量中,还是仅从出现的第一个中获取文本? (如果这些都没有发生,则返回0)

1 个答案:

答案 0 :(得分:0)

我发现上面的代码有一些问题。

  1. visitPage函数中,您将返回一个Promise。很好,除非您不必创建包装承诺!噩梦似乎为您带来了希望。今天,您正在丢弃一个错误,该错误会通过包装来保证返回。相反-只需使用异步功能即可!
async function visitPage(url, code) {
  return Nightmare
      .goto(url)
      .click('.vote')
              .insert('input[name=username]', 'testadmin')
              .insert('.test-code-verify', code)
      .click('.button.vote.submit')
      .wait('.tag.vote.disabled,.validation-error')
      .evaluate(() => document.querySelector('.validation -error').innerHTML)
      .end();
}
  1. 您可能不想将此方法的内容包装在“ try / catch”中。只要兑现承诺:)
async function myBackEndLogic() {
  var br = 0, user, proxy, current, agent;
  while(br < loops){
    current = Math.floor(Math.random() * (maxLoops-br-1));
    const response = await visitPage('https://example.com/admin/login',"code")
    br++;
  }
}
  1. 运行方法时-请确保包含一个陷阱!还是一个!否则,您的应用可能会提早退出。
myBackEndLogic()
  .then(() => console.log('donesies!'))
  .catch(console.error);

我不确定这是否能解决您的特定问题,但希望它能使您走上正确的路:)