Search code examples
htmlperlmojolicious

How to print the text in a paragraph element using Mojolicious


 use strict;
 use warnings;
 use feature 'say';

 use Mojo;

 my $ua = Mojo::UserAgent->new;

 my $array = $ua->get('http://blogs.perl.org/')->res->dom->find('div > p ')->map('text')->join("\n");

 my @arr = split("\n",$array);
 print "\n$arr[0]\n";

When I run this code I get the following output

lets you write your Perl 6 code using Roman numerals:

But I want output as:

perl6-slang-roman lets you write your Perl 6 code using Roman numerals:

Can anyone help me?


Solution

    • The text method will fetch only the text nodes immediately within a node. To fetch all descendant text nodes you need to use all_text

    • It is also rather ugly to use join and then split again to separate the elements into a list. The find method returns a Mojo::Collection object which can be indexed directly

    • And it's as well to confine the selected div to one with the required class

    Like this

    use strict;
    use warnings;
    use feature 'say';
    
    use Mojo;
    
    my $ua = Mojo::UserAgent->new;
    
    my $collection = $ua->get('http://blogs.perl.org/')->res->dom->find('div.entry-body > p ');
    
    say $collection->[0]->all_text;
    

    output

    perl6-slang-roman lets you write your Perl 6 code using Roman numerals: