PhantomJs:内联HTML与外部CSS文件 [英] PhantomJs: inline HTML with external CSS file

查看:122
本文介绍了PhantomJs:内联HTML与外部CSS文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下PhantomJs脚本呈现一些内联HTML,这些HTML链接到外部CSS文件:

I'm attempting to render some inline HTML which links to an external css file using the following PhantomJs script:

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();
};

可以使用wget

但这是phantomjs的输出:

But here's the output of 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

Any ideas on how to ensure external CSS resources get fully loaded before rendering? It seems to work okay when I request the same html with page.open

推荐答案

正如 benweet 所述,您需要设置page.content一次,因为每次都会触发重新加载.

As benweet mentioned, you need to set page.content just once, as it will trigger a reload each time.

因此,此外,您需要在实际设置页面内容之前定义回调.

Because of that, in addition you will need to define your callbacks before actually setting the 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:内联HTML与外部CSS文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆