【问题标题】:Unable to return an array of DOM elements from nightmare.evalute function无法从 nightmare.evalute 函数返回 DOM 元素数组
【发布时间】:2020-05-29 18:16:33
【问题描述】:

这是我使用 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>

我正在尝试遍历页面上的链接。 这是我的代码:

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 - [ {}, {}, {}, {}, {} ]

当我在 Nightmare 无头浏览器中记录 DOM 元素数组时,我得到了预期的结果。但是,当我在 Node.js 代码中注销“titles”常量时,它只是一个由几个空对象组成的数组。

我做错了什么?

【问题讨论】:

    标签: javascript node.js web-scraping nightmare


    【解决方案1】:

    您需要了解 nightmareJS 实例是从 nodeJS 触发的。当您在噩梦评估功能中时,您可以完全访问页面 DOM,并且您处于电子加载的页面的上下文中。

    当您在评估函数(如 nightmare.then() 或任何其他 nodeJs 函数之外)时,您在页面的上下文之外,因此存在差异。

    如果你已经从页面中提取详细信息,那么在 nightmareJS 中只能在 nightmare.evaluate() 函数中完成。

    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();
    

    【讨论】:

      猜你喜欢
      • 2018-05-17
      • 2012-07-19
      • 2021-07-07
      • 1970-01-01
      • 1970-01-01
      • 2011-04-08
      • 2017-10-09
      • 2017-01-19
      相关资源
      最近更新 更多