PhantomJs:带有外部 CSS 文件的内联 HTML

标签 phantomjs

我正在尝试使用以下 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

请求相同的 html 时,它似乎工作正常

最佳答案

作为 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/

相关文章:

ruby - Watir-Webdriver、PhantomJS 和重定向到 https 的 URL

jquery - 如何在 phantomJS 中执行 jQuery promise ?

windows - 在 Windows : How to do it correctly? 上安装 CasperJS

installation - CentOS 6.2 上 NPM 安装 PhantomJS 错误

node.js - PhantomJS 错误

javascript - 找不到变量

javascript - 如何使用 PhantomJS 和 node.js 进行抓取?

javascript - 显示单元测试的图表

python - 如何使用 Selenium 在 PhantomJS 中设置浏览器首选项

automation - 将 Restful /修昔底德与史波克相结合