0

My title pretty much describes it. I have searched the web I don't get close to what I want.

My Code:

    const Nightmare = require('nightmare')
const nightmare = Nightmare({ show: true })
var url = '';

nightmare
  .goto('https://duckduckgo.com')
  .type('#search_form_input_homepage', 'github nightmare')
  .click('#search_button_homepage')
  .wait('#r1-0 a.result__a')
  .evaluate(() => document.querySelector('#r1-0 a.result__a').href)
  .end()
  .then(function(result){
    url = result;
  })
  .catch(error => {
    console.error('Search failed:', error)
  })

//this will throw empty
console.log(url);

//basically i need a loop that can check if url has either changed values or isnt empty but only until it is not empty!

url.change(function(){
  console.log(url);
})

So I describe it mostly inside the code.

If you can help I would love that, you dont really need a basic understanding in nightmare other then it is a headless chrome npm, its basically phantom.js simplfied

James
  • 83
  • 6
  • What is the original problem that you are trying to solve? It seems that you are asking about a proposed solution while there may be a better way to do what you really want. (Reference: [XY Problem](https://en.wikipedia.org/wiki/XY_problem)) – Code-Apprentice Apr 04 '18 at 16:40
  • 1
    What you are doing in `nightmare` is asynchronous call, you will have to execute what you are executing in `.then` – Harshal Carpenter Apr 04 '18 at 16:40

2 Answers2

1

Why don't you simply use the .then you already have?

.then(function(result){
  // Instead of this:
  // url = result;
  // Do this:
  console.log(result);
})
Aurel Bílý
  • 7,068
  • 1
  • 21
  • 34
1

Maybe this thread can help you:

Nightmare conditional wait()

Basicall, you have to write an actionlike:

Nightmare.action('deferredWait', function(done) {
  var attempt = 0;
  var self = this;

  function doEval() {
    self.evaluate_now(function(selector) {
      return (document.querySelector(selector) !== null);
    }, function(result) {
      if (result) {
        done(null, true);
      } else {
        attempt++;
        if (attempt < 10) {
          setTimeout(doEval, 2000); //This seems iffy.
        } else {
          done(null, false);
        }
      }
    }, '#elem');
  };
  doEval();
  return this;
});

And now you're able to use it

var nightmare = Nightmare();
nightmare.goto('http://example.com')
  .deferredWait()
  .then(function(result) {
    console.log(result);
  }); 
Benjamin RD
  • 11,516
  • 14
  • 87
  • 157