Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw

Comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

Dear Monks,

When I parse a string of html that I conjured up looking for span tags that have the attribute class="value", this code works:

use strict; use warnings; use 5.010; use LWP::Simple; use HTML::TreeBuilder; my $html =<<'END_HTML'; <html> <head><title></title></head> <body> <div><span class="value">Hi</span></div> <p>Thanks</p> <div><span class="value">Hello</span></div> </body> </html> END_HTML my $tree = HTML::TreeBuilder->new_from_content($html); my @spans = $tree->look_down(class => 'value'); for my $span (@spans) { say $span->as_trimmed_text(); } $tree->delete(); --output:-- Hi Hello

But when I unleash my code in the wild, it doesn't find the span tags:

use strict; use warnings; use 5.010; use LWP::Simple; use HTML::TreeBuilder; my $url = ' +9-02'; my $html = get($url); my $tree = HTML::TreeBuilder->new(); $tree->parse_file($html); my $span_tag = $tree->look_down( class => 'value', ); say $span_tag->as_trimmed_text(); $tree->delete(); --output:-- Can't call method "as_trimmed_text" on an undefined value at +line 41.

Can anyone see what the problem is?


In reply to HTM::TreeBuilder, HTML::Element's look_down() method by 7stud

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, 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, 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.
  • Log In?

    What's my password?
    Create A New User
    and all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others making s'mores by the fire in the courtyard of the Monastery: (4)
    As of 2018-06-25 01:15 GMT
    Find Nodes?
      Voting Booth?
      Should cpanminus be part of the standard Perl release?

      Results (126 votes). Check out past polls.