简体   繁体   English

如何使用Nightmare.js JavaScript转到()URL数组

[英]How to goto() an array of URLs with Nightmare.js JavaScript

I'm getting an array of URLs returned. 我收到返回的URLs数组。 How do i loop through the array and use goto() function you go to each URL and execute code then close and do the next one? 我如何遍历数组并使用 goto()函数,您转到每个URL并执行代码,然后关闭并执行下一个?

Heres my code: 这是我的代码:

var Nightmare = require('nightmare');
var vo = require('vo');

vo(function*() {
  var nightmare = Nightmare();
  var title = yield nightmare
    .goto('https://www.example.com/l/los_angeles-california')
    .inject('js', `node_modules/jquery/dist/jquery.js`)
    .evaluate(function() {
      var hrefs = [];
      $('.ItemsListCard').find('a').each(function() {
        hrefs.push($(this).attr('href'));
      });

      return hrefs //array of urls

      for (var i = 0; i < hrefs.length; i++) {
        nightmare.goto(hrefs[i].href)
          .wait(5000)
          .click('.ItemListingActionButtons')
          .type('.ThreadViewInput__input', 'Hey! ')
          .click('.ThreadViewInput__send')
      }

    });
  console.log(title);
  yield nightmare.end();

})(function(err, result) {
  if (err) return console.log(err);
});

Note there is a difference between code you're asking Nightmare to execute (via .execute() ) in the browser context, and code you're running in the controller in nodejs. 请注意,您要求Nightmare在浏览器上下文中执行(通过.execute() )的代码与您在nodejs的控制器中运行的代码之间存在差异。 You have the right idea here, but after returning hrefs , the rest of the code to iterate over them should be in the controller, like so: 您在这里有一个正确的想法,但是在返回hrefs ,用于迭代它们的其余代码应在控制器中,如下所示:

const hrefs = yield nightmare
    .goto('https://www.example.com/l/los_angeles-california')
    .inject('js', `node_modules/jquery/dist/jquery.js`)
    .evaluate(function() {
      var hrefs = [];
      $('.ItemsListCard').find('a').each(function() {
        hrefs.push($(this).attr('href'));
      });

      return hrefs; //array of urls
    });
for (var i = 0; i < hrefs.length; i++) {
   yield nightmare.goto(hrefs[i].href)
     .wait(5000)
     .click('.ItemListingActionButtons')
     .type('.ThreadViewInput__input', 'Hey! ')
     .click('.ThreadViewInput__send');
}

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

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