简体   繁体   English

无法从 nightmare.evalute function 返回 DOM 元素数组

[英]Unable to return an array of DOM elements from nightmare.evalute function

This is the DOM structure of a page I am accessing with Nightmare:这是我使用 Nightmare 访问的页面的 DOM 结构:

<h1 class='entry-title'>
  <a>Link</a>
</h1>

<h1 class='entry-title'>
  <a>Link</a>
</h1>

<h1 class='entry-title'>
  <a>Link</a>
</h1>

I am trying to iterate over the links on the page.我正在尝试遍历页面上的链接。 Here's my code for that:这是我的代码:

await nightmare.goto(URL);
await nightmare.wait('h1.entry-title a');

const titles = await nightmare.evaluate(() => Array.from(document.querySelectorAll('h1.entry-title a')));
console.log(titles) // result - [ {}, {}, {}, {}, {} ]

When I log the array of DOM elements inside the Nightmare headless browser, I get the expected result.当我在 Nightmare 无头浏览器中记录 DOM 元素数组时,我得到了预期的结果。 However, when I log out the "titles" constant in my Node.js code, it's just an array of several empty objects.但是,当我在 Node.js 代码中注销“titles”常量时,它只是几个空对象的数组。

What am I doing wrong?我究竟做错了什么?

You need to understand that nightmareJS instance is triggered from nodeJS.您需要了解 nightmareJS 实例是从 nodeJS 触发的。 when you are inside the nightmare evaluate function, you have full access to the page DOM and you are within the context of the page which is loaded in electron.当您在噩梦中评估 function 时,您可以完全访问页面 DOM,并且您处于 electron 中加载的页面的上下文中。

when you are outside of evaluate function like nightmare.then() or any other nodeJs function, you outside the context of the Page and hence the difference.当您不在评估 function 之类的 nightmare.then() 或任何其他 nodeJs function 之外时,您在页面的上下文之外,因此存在差异。

if you have extract Details from Page, then in nightmareJS it can be done only with in the nightmare.evaluate() function.如果您从 Page 中提取了详细信息,那么在 nightmareJS 中只能在 nightmare.evaluate() function 中完成。

nightmare
   .goto(www.google.com) //navigate to given url
   .wait(10000) // wait for 10s for the page to load
   .inject('js', 'node_modules/jquery/dist/jquery.min.js') //manually inject jQuery at runtime to the page
   .evaluate(() => {
       //You are inside the context of page loaded in electron.
       //since the jQuery has been loaded in the previous step, you 
       // can use jquery functions to scrape data or manipulate DOM at run 
       //time

      return element;
   })
   .then((element) => {
      //the returned element from the previous step (evaluate) is recieved as 
      //the input for the the function.
      //inside th then function you are with in the context of the nodeJs 
      
     //as you mentioned, if you want to print the titles object, it needs to 
     //be returned from the evaluate function and can be printed in then()
     //function.

    //when you returning something from evaluate function, you are basically 
    //returning the data from page context to nodeJS context.
   })
   .end();

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

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