简体   繁体   中英

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?

  • 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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM