javascript - 如何将函数从 Node Horseman 传递给 `evaluate` 函数?

标签 javascript node.js web-scraping web-crawler

借助 Node Horseman,我们可以在 Node.js 中使用 PhantomJS。如果我们想在页面的上下文中执行一段 JS 代码,我们可以这样做:

var Horseman = require('node-horseman');
var horseman = new Horseman();

horseman.open(pageUrl)
        .status()
        .evaluate(function () {
            // Js Code goes here
        })
        .close();

现在,假设我们想“从外部”将一些东西传递给求值函数。例如,如果我执行以下操作

var Horseman = require('node-horseman');
var horseman = new Horseman();

function someFunction() {}

horseman.open(pageUrl)
        .status()
        .evaluate(function () {
            someFunction();
        })
        .close();

当我在评估中调用 someFunction 时,找不到它。

另一个例子,假设我做了以下

var Horseman = require('node-horseman');
var url = require('url');
var horseman = new Horseman();

horseman.open(pageUrl)
        .status()
        .evaluate(function () {
            // try to use url somehow here
        })
        .close();

它也无法识别那里的 url 对象。我确实理解这个问题,该代码是在页面的上下文中运行的。但是有没有办法从外部传递这些东西,以便我们可以在评估内部使用它们?

最佳答案

关于在页面上下文中运行的代码,您是正确的。您可以将其想象成打开浏览器的控制台并将 evalute 函数中的所有内容粘贴到那里。

如果将 someFunction() 粘贴到控制台,JS 运行时将抛出错误:someFunction 未定义。那是因为它从未在页面的上下文中定义。

实际上有一种从外部传递函数的变通方法,但只有当该函数不依赖于 Node 上下文中的其他函数和全局对象时,它才会起作用。

这是一个例子:

function someFunction() {
    return document.title;
}

horseman.open('http://google.com')
    .evaluate(function (someFunction) {
        eval('var sf = ' + someFunction);
        return sf();
    }, someFunction.toString())
    .log() //Will print out "Google"
    .close();

url 实际上是一个 node.js 模块。您可以尝试用任何类似的客户端 JS 库替换它,然后使用以下命令之一注入(inject)它:

horseman
    .injectJs(file)

horseman
    .includeJs(url)

关于javascript - 如何将函数从 Node Horseman 传递给 `evaluate` 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37911330/

相关文章:

node.js - 无法在 Facebook 中获取访问 token

javascript - 在类方法中使用 Promise

javascript - 我无法安装 puppeteer

python - 在Scrapy中养CloseSpider有什么影响?

python - 为什么我在抓取网站时会得到一个空列表?

python - BeautifulSoup 在 Amazon EC2 机器上表现不同

javascript - 如何使用提交上传文件而不重新加载页面

javascript - 自动化批处理脚本 - 在 Photoshop 中将文件名转换为文本

javascript - 如何根据angularJS中的数据将 'selected'放入html选项中?

javascript - 在 Matlab 生产服务器上启用 CORS 时出错