Search code examples
perlmojoliciousmojo-dom

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


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.


Solution

  • 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