PhantomJS如何在html字符串中呈现javascript

PhantomJS how to render javascript in html string

本文关键字:javascript 字符串 html PhantomJS      更新时间:2023-09-26

我正试图让PhantomJS获取一个html字符串,然后让它像浏览器一样呈现整个页面(包括执行页面源中的任何javascript)。我需要结果html结果作为字符串。我看到了page.open的例子,它没有用,因为我的数据库中已经有了页面源。

我需要使用page.open来触发PhantomJS中的javascript渲染引擎吗?是否有任何方法可以在内存中完成这一切(即,不分页。打开请求或从磁盘读取/写入html源?

我在这里看到了类似的问题和答案,但它并不能完全解决我的问题。在运行了下面的代码之后,我似乎没有做任何事情来呈现html源字符串中的javascript。

var page = require('webpage').create();
page.setContent('raw html and javascript in this string', 'http://whatever.com');
//everything i've tried from here on doesn't execute the javascript in the string

--------------更新---------------

根据以下建议尝试了以下操作,但仍然不起作用。只是返回我提供的原始源代码,而没有呈现javascript。

var page = require('webpage').create();
page.settings.localToRemoteUrlAccessEnabled = true;
page.settings.webSecurityEnabled = false;
page.onLoadFinished = function(){
    var resultingHtml = page.evaluate(function() {
        return document.documentElement.innerHTML;
    });
    console.log(resultingHtml);
    //console.log(page.content); // this didn't work either
    phantom.exit();
};
page.url = input.Url;
page.content = input.RawHtml;
//page.setContent(input.RawHtml, input.Url); //this didn't work either

以下作品

page.onLoadFinished = function(){
    console.log(page.content); // rendered content
};
page.content = "your source html string";

但你必须记住,如果你从一个字符串中设置页面,域将大约为:空白。因此,如果html从其他域加载资源,那么您应该使用--web-security=false --local-to-remote-url-access=true命令行选项运行PhantomJS:

phantomjs--网络安全=false--本地到远程url访问=true script.js

此外,您可能需要等待JavaScript执行的完成,当PhantomJS认为它已经完成时,JavaScript执行可能还没有完成。使用setTimeout()等待静态时间,或使用waitFor()等待页面上的特定条件。在这个问题中给出了等待完整页面的更稳健的方法:phantomjs不等待"完整"页面加载

setTimeout使它能够工作,尽管我对每个页面等待一段时间并不感到兴奋。这里讨论的waitFor方法不起作用,因为我不知道每个页面可能有什么元素。

var system = require('system');
var page = require('webpage').create();
page.setContent(input.RawHtml, input.Url);
window.setTimeout(function () {
    console.log(page.content);
    phantom.exit();
}, input.WaitToRenderTimeInMilliseconds);

也许不是你想要的答案,但使用PhantomJsCloud.com你可以轻松完成,下面是一个例子:http://api.phantomjscloud.com/api/browser/v2/a-demo-key-with-low-quota-per-ip-address/?request={url:%22http://example.com%22,内容:%22%3Ch1%3New%20Content!%3C/h1%3E%22,renderType:%22png%22,脚本:{domReady:[%22var%20hiDiv=document.createElement%28%27div%27%29;hiDiv.inerHTML=%27Hello%20World!%27;document.body.appendChild%28hiDiv%29;window_pjscMeta.scriptOutput={Goodbye:%27World%27};%22]},outputAsJson:false}"新内容!"是替换原始内容的内容,"Hello World!"由脚本放置在页面中。

如果你想通过普通的PhantomJ来实现这一点,那么在加载页面内容之后,你需要使用injectJs或includeJs函数。