我正在尝试使用以下 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
最佳答案
作为 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;
关于PhantomJs:带有外部 CSS 文件的内联 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20950013/