Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PhantomJS: setContent not working when HTML has assets

Tags:

html

phantomjs

This script works:

var page = require('webpage').create(); 

var html = '<h1>Test</h1><img>'; //works with page.setContent and page.content
//var html = '<h1>Test</h1><img src=".">'; //only works with page.content

page.setContent(html, 'http://github.com');
//page.content = html;

page.render('test.png');
phantom.exit();

but adding a src attribute to the img makes it fail silently (page.render returns false and no image is generated).

Setting page.content directly works in both cases but then relative URLs don't. The same thing happens with other tags that load a resource such as link. It doesn't matter whether the linked resource exists or not. Tested in 1.8.1 and 1.9.2.

Is this a bug or have I misunderstood the API?

like image 851
Tamlyn Avatar asked Oct 02 '22 19:10

Tamlyn


1 Answers

You can not render webpage if it is not fully loaded.

When you are setting link or src to <img>, It will try to load image asynchronously. So, it requires to wait for loading finished.

Try following code.

page.onLoadFinished = function(status) {
    page.render('test.png');
    phantom.exit();
};
page.setContent(html, 'http://github.com');
like image 84
Kashyap Prajapati Avatar answered Oct 07 '22 18:10

Kashyap Prajapati