噩梦JavaScript文档未定义错误

时间:2018-07-19 11:39:39

标签: javascript nightmare

我有下面的代码,我想转到W3Schools,获取所有链接,检查标题是否与页面相同,但是我需要遍历搜索的所有页面,然后我似乎无法做到这一点。

你能帮我吗?另外,如果代码有任何更改,请告诉我。我收到错误消息:

document not defined

我不明白为什么。

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

let Promise = require('bluebird');

return start();

function itExists() {
  var element = document.querySelector("#pnnext > span:nth-child(2)");
  if (typeof(element) != 'undefined' && element != null) {
    return true;
  } else {
    return false;
  }
}

async function start() {
  await nightmare
    .goto('https://www.google.com')
    .type('#lst-ib', 'w3schools')
    .click('#tsf > div.tsf-p > div.jsb > center > input[type="submit"]:nth-child(1)');
  while (itExists()) {
    const linkuri = await nightmare.evaluate(() => {
        let urls = document.querySelectorAll('div.rc>.r>a');
        let linkuri = [];
        for (let i = 0; i < urls.length; ++i) {
          item = {};
          item["title"] = urls[i].innerHTML;
          item["link"] = urls[i].href;
          linkuri.push(item);
        }
        return linkuri;
      })
      .click("#pnnext > span:nth-child(2)");
  }
  return selectare(linkuri);
}

async function selectare(linkuri) {
  await Promise.each(linkuri, async(link) => {
    await nightmare
      .goto(link.link)
      .wait(1000)
      .evaluate(function() {
        return document.title;
      })
      .then(function(title) {
        if (title === link.title) {
          console.log(title + " = " + link.link + " " + link.title);
        } else {
          console.log(title + " != " + link.link + " " + link.title);
        }
      })
  })
}

0 个答案:

没有答案