If you're a tad familiar with XPath (or if you want to become familiar with it), you can try HTML::TreeBuilder::XPath, which adds XPath support to HTML::TreeBuilder.

The code looks like this:

use warnings; use strict; use HTML::TreeBuilder::XPath; my $str = q{<a href ='some\\where'><img src='apple.gif'></img></a> <a href ='some\\where'>not an img</img></a> <a href ='some\\where'><img src='apple.gif'></img> and tex +t</a> }; my $root = HTML::TreeBuilder->new_from_content($str); foreach my $tag ($root->findnodes( '//a[./img]')) { print "link: ", $tag->as_HTML; }

If you want to capture the links that have only an image in the content, you can replace the condition by //a[./img and string()=""] (that doesn't exactly garantee that there's nothing else in the link, but getting the query 100% right is left as an exercise for the reader).

Of course if all you're interested in is the value of the src attribute, you can get it directly:

foreach my $url ($root->findnodes( '//a/img/@src')) { print "link: ", $url->getValue, "\n"; }

Note that in that case the attribute are returned as HTML::TreeBuilder::XPath::Attribute objects, hence you need to use getValue to get the value. Hummm.... I wonder if that's in the docs, if not I'll add it.


In reply to Re: Extracting full links from HTML by mirod
in thread Extracting full links from HTML by wojtyk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.