我正在尝试使用以下PhantomJs脚本呈现一些链接到外部css文件的内联HTML:
var page = require('webpage').create();
page.content = '';
page.content += '<html><head>';
page.content += '<link rel="stylesheet" href="http://example.com/css/layout.css" type="text/css" media="Screen">';
page.content += '</head><body>';
page.content += '<h1>test</h1>';
page.content += '</body></html>';
page.onResourceRequested = function(requestData, request) {
console.log('::loading', requestData['url']); // this doesn't get logged
};
page.onLoadFinished = function() {
console.log('::rendering');
page.render('output.png');
phantom.exit();
};
使用layout.css
wget
文件
但这是phantomjs的输出:
$ ./phantomjs --debug=true render_demo.js
... snip ...
2014-01-06T12:17:53 [DEBUG] WebPage - updateLoadingProgress: 10
2014-01-06T12:17:53 [DEBUG] WebPage - updateLoadingProgress: 10
2014-01-06T12:17:53 [DEBUG] WebPage - updateLoadingProgress: 100
2014-01-06T12:17:53 [DEBUG] Network - Resource request error: 5 ( "Operation canceled" ) URL: "http://example.com/css/layout.css"
::rendering
没有创建输出.png
文件。
有关如何确保外部CSS资源在渲染之前完全加载的任何想法?
当我使用page.open
答案 0 :(得分:6)
如上所述benweet,您只需设置page.content
一次,因为每次都会触发重新加载。
因此,您需要在实际设置网页内容之前定义回调。
请尝试这样:
var page = require('webpage').create();
page.onResourceRequested = function(requestData, request) {
console.log('::loading', requestData['url']); // this does get logged now
};
page.onLoadFinished = function() {
console.log('::rendering');
page.render('output.png');
phantom.exit();
};
var content = '';
content += '<html><head>';
content += '<link rel="stylesheet" href="http://example.com/css/layout.css" type="text/css" media="screen">';
content += '</head><body>';
content += '<h1>test</h1>';
content += '</body></html>';
page.content = content;
答案 1 :(得分:2)
您有一个名为localToRemoteUrlAccessEnabled
的设置,控制本地页面是否可以访问远程资源。它似乎默认为false
,因此您应该尝试更改它。
PhantomJS设置已记录here,因此更改此设置将像您的代码中那样进行:
page.settings.localToRemoteUrlAccessEnabled = true;
在页面创建之后。由于您的页面内容是通过脚本生成的,因此我不知道它是真的被认为是本地还是远程。如果此设置无效,您可以尝试将webSecurityEnabled
设置为false
。
答案 2 :(得分:0)
您必须设置page.content
一次。多次调用setter将多次加载页面并取消任何以前未完成的异步资源加载。
var page = require('webpage').create();
var content = '';
content += '<html><head>';
content += '<link rel="stylesheet" href="http://example.com/css/layout.css" type="text/css" media="Screen">';
content += '</head><body>';
content += '<h1>test</h1>';
content += '</body></html>';
page.content = content;