2

I have interest to programmatically take a screenshot of a webpage using perl. I have come across this solution:

use WWW::Mechanize::Firefox;
use Path::Class qw/file/;

my $mech = WWW::Mechanize::Firefox->new(
  bufsize => 10_000_000, # PNGs might become huge
);
$mech->get('http://www.stackoverflow.com/');

my $fh = file( 'test.png' )->open( '> :raw' );
print $fh $mech->content_as_png();

but when I try to run this code I get:

Failed to connect to , problem connecting to "localhost", port 4242: Connection refused at /usr/local/share/perl/5.20.2/MozRepl/Client.pm line 144

It was suggested that this failure is due to a closed port (Debian Jessie, Apache2, Perl 5.20), or MozRepl not installed or not configured correctly.

The Debian server is a command line only, and there is no graphic interface otherwise. When I run cpan WWW::Mechanize::Firefox I get at the end:

CPAN: Storable loaded ok (v2.49_01)
Reading '/root/.cpan/Metadata'
  Database was generated on Fri, 22 Jul 2016 17:53:33 GMT
CPAN: Module::CoreList loaded ok (v5.20150214)
WWW::Mechanize::Firefox is up to date (0.79).

And when I run cpan MozRepl, I get at the end:

CPAN: Storable loaded ok (v2.49_01)
Reading '/root/.cpan/Metadata'
  Database was generated on Fri, 22 Jul 2016 17:53:33 GMT
CPAN: Module::CoreList loaded ok (v5.20150214)
MozRepl is up to date (0.06).

So as the title asks, can the above code work if there is no graphical interface? If yes, what can I do to debug and solve this issue?

Community
  • 1
  • 1
KingsInnerSoul
  • 1,373
  • 4
  • 20
  • 49
  • 1
    You need a headless browser like PhantomJS. I haven't been recommending [WWW::Mechanize::PhantomJS](https://metacpan.org/pod/WWW::Mechanize::PhantomJS) because it wasn't really being maintained, but the author has put out two releases this year after a two year hiatus, so you might give that a shot. When I tried it, there was a bug with rendering screenshots that was a deal-breaker for me; I submitted a patch but after a while with no response, I had to drop Perl and just use plain PhantomJS. (My patch was finally applied a couple weeks ago.) – ThisSuitIsBlackNot Jul 22 '16 at 19:13

1 Answers1

2

2 solutions:

  • I used this link to download and install PhantomJS: https://gist.github.com/julionc/7476620 Once it was successfully installed I installed `WWW::Mechanize::PhantomJS` via cpan. The link that @ThisSuitIsBlackNot provided in his comment has the documentation on how to get the PNG. – KingsInnerSoul Jul 22 '16 at 20:42