rosshinkley / nightmare-examples

Examples and supplementary documentation for Nightmare
251 stars 46 forks source link

Loop inside a loop #23

Open funkyremi opened 8 years ago

funkyremi commented 8 years ago

Thanks for your examples, they really helped me! I tried to automate linkedin using promises but there's a loop inside another loop and when I try Array.reduce inside another Array.reduce it doesn't works. Here's the code:

var Nightmare = require('nightmare');

nightmare = Nightmare({
  show: true,
  alwaysOnTop: false,
  waitTimeout: 120000
});

var queries = [
  'automation',
  'python',
];

var filter = 'Relations de 2e niveau';

// Connection
console.log('Connection');
nightmare
  .viewport(1000, 800)
  .useragent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36")
  .goto('https://www.linkedin.com/uas/login')
  .wait('#main-search-box')
  .then(function() {
    queries.reduce(function(accumulator, query) {
      return accumulator.then(function(results) {
        // Search
        console.log('Going to index');
        return nightmare
          .goto('https://www.linkedin.com')
          .wait('#main-search-box') // Wait until user is connected (manual connection)
          .type('#main-search-box', query)
          .click('.search-button')
          .wait('#search-types')
          .click('#search-types > div > ul > li:nth-child(2) > a') // Filter by people
          .wait("#results-container")
          .then(function() {

            // Filter
            console.log('Applying filter');
            return nightmare
              .click('label[title="' + filter + '"]')
              .evaluate(function() {
                var links = [];
                $('#results > li.mod.result.people').find('.title.main-headline').each(function() {
                  links.push($(this).attr("href"));
                });
                return links;
              })
              .then(function(links) {
                console.log(links);
                // Doing a foreach link loop?
                return nightmare
                  .goto(link)
                  .wait()
                  .back()
                  .then(function() {
                    return nightmare.click('#results-pagination > ul > li.next > a').then(); // going to next page
                  });
              });
        });
      });
    }, Promise.resolve([])).then();
  });