Search code examples
perlwww-mechanize

What is the preferred method of accessing WWW::Mechanize responses?


Are both of these versions OK or is one of them to prefer?

#!/usr/bin/env perl
use strict;
use warnings;
use WWW::Mechanize;

my $mech = WWW::Mechanize->new();
my $content;

# 1
$mech->get( 'http://www.kernel.org' );
$content = $mech->content;
print $content;

# 2
my $res = $mech->get( 'http://www.kernel.org' );
$content = $res->content;
print $content;

Solution

  • The content() method is sometimes more convenient:

    $mech->content(...)
    

    Returns the content that the mech uses internally for the last page fetched. Ordinarily this is the same as $mech->response()->content(), but this may differ for HTML documents if "update_html" is overloaded, and/or extra named arguments are passed to content():

    $mech->content( format => 'text' )
    

    Returns a text-only version of the page, with all HTML markup stripped. This feature requires HTML::TreeBuilder to be installed, or a fatal error will be thrown.

    $mech->content( base_href => [$base_href|undef] )
    

    Returns the HTML document, modified to contain a mark-up in the header. $base_href is $mech->base() if not specified. This is handy to pass the HTML to e.g. HTML::Display.