Mojo::DOM - How to return more than one attribute

181 views Asked by At

I'm new to Mojolicious, to find the title for a link within a p tag with class Module e.g.

<p class="Module"><a class="story" href="http://intranet/blah" >Link Text is here</a></p>

I use the following code:

my $dom = Mojo::DOM->new( $page );

for my $elm ( $dom->find('p.Module > a.story')->each ){
    print $elm->text ."\n";
}

Pretty crude but it's functional. What I can't figure out as yet (it could be too late at night for me) is how to return the href and the link text. Please put me out of my misery.

2

There are 2 answers

0
Miller On BEST ANSWER

You just need the attr method:

my $dom = Mojo::DOM->new( $page );

for my $elm ( $dom->find('p.Module > a.story')->each ){
    print $elm->text, ' ', $elm->attr('href'), "\n";
}

For a quick tutorial on Mojo::UserAgent and Mojo::DOM, check out Mojocast episode 5

0
brian d foy On

Here's a mojo-y way of doing it by using Mojo::Collection's map:

use v5.10;

use Mojo::DOM;
use Data::Dumper;

my $page =<<'HTML';
<p class="Module"><a class="story" href="http://intranet/blah" >Link Text is here</a></p>
HTML

my $dom = Mojo::DOM->new( $page );

my @links = $dom
    ->find('p.Module > a.story')
    ->map( sub { [ $_->text, $_->attr( 'href' ) ] } );

say Dumper \@links;