node.js - Nightmare、PhantomJS 和提取页面数据

标签 node.js phantomjs nightmare

我是 Nightmare/PhantomJS 的新手,正在努力获取给定页面上所有标签的简单 list 。在从源代码构建 PhantomJS 并手动安装 NodeJS、Nightmare 等之后,我在 Ubuntu 14.04 上运行,其他功能似乎按我预期的那样工作。

这是我使用的代码:

var Nightmare = require('nightmare');
new Nightmare()
  .goto("http://www.google.com")
  .wait()
  .evaluate(function () 
   {
     var a = document.getElementsByTagName("*");
     return(a);
   }, 
   function(i) 
   {
     for (var index = 0; index < i.length; index++)
     if (i[index])
        console.log("Element " + index + ": " + i[index].nodeName);
    })
  .run(function(err, nightmare) 
  {
     if (err) 
        console.log(err);
  }); 

当我在“真正的”浏览器中运行它时,我得到了页面上所有标记类型的列表(HTML、HEAD、BODY,...)。当我使用 node GetTags.js 运行它时,我只得到一行输出:

Element 0: HTML

我确定这是一个新手问题,但我在这里做错了什么?

最佳答案

PhantomJS 有两个上下文。提供对 DOM 访问的页面上下文只能通过 evaluate() 访问。因此,变量必须显式传入和传出页面上下文。但是有一个限制(docs):

Note: The arguments and the return value to the evaluate function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.

Closures, functions, DOM nodes, etc. will not work!

Nightmare 的 evaluate() 函数只是同名 PhantomJS 函数的包装器。这意味着您将需要使用页面上下文中的元素,并且只向外部传递一个表示。例如:

.evaluate(function () 
{
    var a = document.getElementsByTagName("div");
    return a.length;
}, 
function(i) 
{
    console.log(i + " divs available");
})

关于node.js - Nightmare、PhantomJS 和提取页面数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30876927/

相关文章:

javascript - "npm-run-all"未被识别为内部或外部命令

node.js - 我的 socket.io 应用程序的服务器未在 Heroku 上启动

javascript - 从文件加载 html 到 nightmare.js

javascript - 与开发工具交互,同时使用 .evaluate 抓取 dreamer.js

node.js - EC2 托管的 Node.js 应用程序 - 无法远程连接到端口

jquery - 使用 jQuery 作为开发工具

javascript - PhantomCSS/CasperJS - 广告图像变灰

javascript - 是否可以将函数传递给 casper.evaluate()?

javascript - child_process.execFile 不适用于 phantomjs 和 highcharts-convert.js

javascript - Nightmare - 文件来自哪里?