噩梦/电子,如何进行不同的操作取决于一个元素是否存在?

我想使用Nightmare进入一个页面,并根据指定的元素是否存在做不同的操作。 我知道有一个exists函数来testing一个元素是否存在于页面上,但我不知道如何使用它或是否可以在这里使用。 有人可以给我一个如何做这个任务的例子吗? 谢谢!

梦魇是可以接受的,所以如果你想用exists()函数的返回值作为逻辑,你可以使用.then()来进行方法链接。 这也适用于visible()evaluate()或返回值的任何函数。

我提供的例子searchStackoverflow,如果search框select器存在,去Google,返回标题,然后有条件地logging结果。 您可以根据需要继续链接逻辑。

 var Nightmare = require('nightmare'); var nightmare = Nightmare({ show: true }); nightmare .goto("http://stackoverflow.com") .exists("#search input[type=text]") .then(function (result) { if (result) { return nightmare.type("#search input[type=text]", "javascript\u000d") } else { console.log("Could not find selector") } }) .then(function() { return nightmare .goto("http://www.google.com") .wait(1000) .title() }) .then(function (title) { if (title == "Google") { console.log("title is Google") } else { console.log("title is not Google") } return nightmare.end() }) .catch(function (error) { console.log(error) })