1 package HTML::TreeBuilder;
4 use integer; # vroom vroom!
6 use vars qw(@ISA $VERSION $DEBUG);
9 #---------------------------------------------------------------------------
10 # Make a 'DEBUG' constant...
13 # We used to have things like
14 # print $indent, "lalala" if $Debug;
15 # But there were an awful lot of having to evaluate $Debug's value.
16 # If we make that depend on a constant, like so:
17 # sub DEBUG () { 1 } # or whatever value.
19 # print $indent, "lalala" if DEBUG;
20 # Which at compile-time (thru the miracle of constant folding) turns into:
21 # print $indent, "lalala";
22 # or, if DEBUG is a constant with a true value, then that print statement
23 # is simply optimized away, and doesn't appear in the target code at all.
24 # If you don't believe me, run:
25 # perl -MO=Deparse,-uHTML::TreeBuilder -e 'BEGIN { \
26 # $HTML::TreeBuilder::DEBUG = 4} use HTML::TreeBuilder'
27 # and see for yourself (substituting whatever value you want for $DEBUG
31 # Already been defined! Do nothing.
32 } elsif($] < 5.00404) {
33 # Grudgingly accomodate ancient (pre-constant) versions.
34 eval 'sub DEBUG { $Debug } ';
36 eval 'sub DEBUG () {0}'; # Make it a constant.
37 } elsif($DEBUG =~ m<^\d+$>s) {
38 eval 'sub DEBUG () { ' . $DEBUG . ' }'; # Make THAT a constant.
40 warn "Non-numeric value \"$DEBUG\" in \$HTML::Element::DEBUG";
41 eval 'sub DEBUG () { $DEBUG }'; # I guess.
45 #---------------------------------------------------------------------------
47 use HTML::Entities ();
48 use HTML::Tagset 3.02 ();
52 @ISA = qw(HTML::Element HTML::Parser);
53 # This looks schizoid, I know.
54 # It's not that we ARE an element AND a parser.
55 # We ARE an element, but one that knows how to handle signals
56 # (method calls) from Parser in order to elaborate its subtree.
59 *HTML::TreeBuilder::isKnown = \%HTML::Tagset::isKnown;
60 *HTML::TreeBuilder::canTighten = \%HTML::Tagset::canTighten;
61 *HTML::TreeBuilder::isHeadElement = \%HTML::Tagset::isHeadElement;
62 *HTML::TreeBuilder::isBodyElement = \%HTML::Tagset::isBodyElement;
63 *HTML::TreeBuilder::isPhraseMarkup = \%HTML::Tagset::isPhraseMarkup;
64 *HTML::TreeBuilder::isHeadOrBodyElement = \%HTML::Tagset::isHeadOrBodyElement;
65 *HTML::TreeBuilder::isList = \%HTML::Tagset::isList;
66 *HTML::TreeBuilder::isTableElement = \%HTML::Tagset::isTableElement;
67 *HTML::TreeBuilder::isFormElement = \%HTML::Tagset::isFormElement;
68 *HTML::TreeBuilder::p_closure_barriers = \@HTML::Tagset::p_closure_barriers;
70 #==========================================================================
71 # Two little shortcut constructors:
73 sub new_from_file { # or from a FH
75 Carp::croak("new_from_file takes only one argument")
77 Carp::croak("new_from_file is a class method only")
79 my $new = $class->new();
80 $new->parse_file($_[0]);
84 sub new_from_content { # from any number of scalars
86 Carp::croak("new_from_content is a class method only")
88 my $new = $class->new();
89 foreach my $whunk (@_) {
90 if(ref($whunk) eq 'SCALAR') {
95 last if $new->{'_stunted'}; # might as well check that.
101 # TODO: document more fully?
102 sub parse_content { # from any number of scalars
105 foreach my $whunk (@_) {
106 if(ref($whunk) eq 'SCALAR') {
107 $retval = $tree->parse($$whunk);
109 $retval = $tree->parse($whunk);
111 last if $tree->{'_stunted'}; # might as well check that.
118 #---------------------------------------------------------------------------
120 sub new { # constructor!
122 $class = ref($class) || $class;
124 my $self = HTML::Element->new('html'); # Initialize HTML::Element part
126 # A hack for certain strange versions of Parser:
127 my $other_self = HTML::Parser->new();
128 %$self = (%$self, %$other_self); # copy fields
129 # Yes, multiple inheritance is messy. Kids, don't try this at home.
130 bless $other_self, "HTML::TreeBuilder::_hideyhole";
131 # whack it out of the HTML::Parser class, to avoid the destructor
134 # The root of the tree is special, as it has these funny attributes,
135 # and gets reblessed into this class.
137 # Initialize parser settings
138 $self->{'_implicit_tags'} = 1;
139 $self->{'_implicit_body_p_tag'} = 0;
140 # If true, trying to insert text, or any of %isPhraseMarkup right
141 # under 'body' will implicate a 'p'. If false, will just go there.
143 $self->{'_tighten'} = 1;
144 # whether ignorable WS in this tree should be deleted
146 $self->{'_implicit'} = 1; # to delete, once we find a real open-"html" tag
148 $self->{'_element_class'} = 'HTML::Element';
149 $self->{'_ignore_unknown'} = 1;
150 $self->{'_ignore_text'} = 0;
151 $self->{'_warn'} = 0;
152 $self->{'_no_space_compacting'}= 0;
153 $self->{'_store_comments'} = 0;
154 $self->{'_store_declarations'} = 1;
155 $self->{'_store_pis'} = 0;
156 $self->{'_p_strict'} = 0;
158 # Parse attributes passed in as arguments
162 $self->{"_$_"} = $attr{$_};
166 # rebless to our class
169 $self->{'_element_count'} = 1;
170 # undocumented, informal, and maybe not exactly correct
172 $self->{'_head'} = $self->insert_element('head',1);
173 $self->{'_pos'} = undef; # pull it back up
174 $self->{'_body'} = $self->insert_element('body',1);
175 $self->{'_pos'} = undef; # pull it back up again
180 #==========================================================================
182 sub _elem # universal accessor...
184 my($self, $elem, $val) = @_;
185 my $old = $self->{$elem};
186 $self->{$elem} = $val if defined $val;
191 sub implicit_tags { shift->_elem('_implicit_tags', @_); }
192 sub implicit_body_p_tag { shift->_elem('_implicit_body_p_tag', @_); }
193 sub p_strict { shift->_elem('_p_strict', @_); }
194 sub no_space_compacting { shift->_elem('_no_space_compacting', @_); }
195 sub ignore_unknown { shift->_elem('_ignore_unknown', @_); }
196 sub ignore_text { shift->_elem('_ignore_text', @_); }
197 sub ignore_ignorable_whitespace { shift->_elem('_tighten', @_); }
198 sub store_comments { shift->_elem('_store_comments', @_); }
199 sub store_declarations { shift->_elem('_store_declarations', @_); }
200 sub store_pis { shift->_elem('_store_pis', @_); }
201 sub warn { shift->_elem('_warn', @_); }
204 #==========================================================================
208 CORE::warn("HTML::Parse: $_[0]\n") if $self->{'_warn'};
209 # should maybe say HTML::TreeBuilder instead
212 #==========================================================================
215 # To avoid having to rebuild these lists constantly...
216 my $_Closed_by_structurals = [qw(p h1 h2 h3 h4 h5 h6 pre textarea)];
220 return if $_[0]{'_stunted'};
222 # Accept a signal from HTML::Parser for start-tags.
223 my($self, $tag, $attr) = @_;
224 # Parser passes more, actually:
225 # $self->start($tag, $attr, $attrseq, $origtext)
226 # But we can merrily ignore $attrseq and $origtext.
228 if($tag eq 'x-html') {
229 print "Ignoring open-x-html tag.\n" if DEBUG;
230 # inserted by some lame code-generators.
231 return; # bypass tweaking.
234 $tag =~ s{/$}{}s; # So <b/> turns into <b>. Silently forgive.
236 unless($tag =~ m/^[-_a-zA-Z0-9:%]+$/s) {
237 DEBUG and print "Start-tag name $tag is no good. Skipping.\n";
239 # This avoids having Element's new() throw an exception.
243 my $pos = $self->{'_pos'} || $self
245 my $already_inserted;
248 # optimization -- don't figure out indenting unless we're in debug mode
249 my @lineage = $pos->lineage;
250 $indent = ' ' x (1 + @lineage);
252 $indent, "Proposing a new \U$tag\E under ",
253 join('/', map $_->{'_tag'}, reverse($pos, @lineage)) || 'Root',
259 #print $indent, "POS: $pos ($ptag)\n" if DEBUG > 2;
262 foreach my $k (keys %$attr) {
263 # Make sure some stooge doesn't have "<span _content='pie'>".
264 # That happens every few million Web pages.
265 $attr->{' ' . $k} = delete $attr->{$k}
266 if length $k and substr($k,0,1) eq '_';
267 # Looks bad, but is fine for round-tripping.
271 ($self->{'_element_class'} || 'HTML::Element')->new($tag, %$attr);
272 # Make a new element object.
273 # (Only rarely do we end up just throwing it away later in this call.)
275 # Some prep -- custom messiness for those damned tables, and strict P's.
276 if($self->{'_implicit_tags'}) { # wallawallawalla!
278 unless($HTML::TreeBuilder::isTableElement{$tag}) {
279 if ($ptag eq 'table') {
281 " * Phrasal \U$tag\E right under TABLE makes implicit TR and TD\n"
283 $self->insert_element('tr', 1);
284 $pos = $self->insert_element('td', 1); # yes, needs updating
285 } elsif ($ptag eq 'tr') {
287 " * Phrasal \U$tag\E right under TR makes an implicit TD\n"
289 $pos = $self->insert_element('td', 1); # yes, needs updating
291 $ptag = $pos->{'_tag'}; # yes, needs updating
293 # end of table-implication block.
296 # Now maybe do a little dance to enforce P-strictness.
297 # This seems like it should be integrated with the big
298 # "ALL HOPE..." block, further below, but that doesn't
302 and $HTML::TreeBuilder::isKnown{$tag}
303 and not $HTML::Tagset::is_Possible_Strict_P_Content{$tag}
306 my $here_tag = $ptag;
308 if($here_tag eq 'p') {
310 " * Inserting $tag closes strict P.\n" if DEBUG > 1;
312 # NB: same as \'q', but less confusing to emacs cperl-mode
316 #print("Lasting from $here_tag\n"),
318 $HTML::TreeBuilder::isKnown{$here_tag}
319 and not $HTML::Tagset::is_Possible_Strict_P_Content{$here_tag};
320 # Don't keep looking up the tree if we see something that can't
321 # be strict-P content.
323 $here_tag = ($here = $here->{'_parent'} || last)->{'_tag'};
325 $ptag = ($pos = $self->{'_pos'} || $self)->{'_tag'}; # better update!
327 # end of strict-p block.
330 # And now, get busy...
331 #----------------------------------------------------------------------
332 if (!$self->{'_implicit_tags'}) { # bimskalabim
334 print $indent, " * _implicit_tags is off. doing nothing\n"
337 #----------------------------------------------------------------------
338 } elsif ($HTML::TreeBuilder::isHeadOrBodyElement{$tag}) {
339 if ($pos->is_inside('body')) { # all is well
341 " * ambilocal element \U$tag\E is fine under BODY.\n"
343 } elsif ($pos->is_inside('head')) {
345 " * ambilocal element \U$tag\E is fine under HEAD.\n"
348 # In neither head nor body! mmmmm... put under head?
350 if ($ptag eq 'html') { # expected case
351 # TODO?? : would there ever be a case where _head would be
352 # absent from a tree that would ever be accessed at this
354 die "Where'd my head go?" unless ref $self->{'_head'};
355 if ($self->{'_head'}{'_implicit'}) {
357 " * ambilocal element \U$tag\E makes an implicit HEAD.\n"
359 # or rather, points us at it.
360 $self->{'_pos'} = $self->{'_head'}; # to insert under...
363 "Ambilocal element <$tag> not under HEAD or BODY!?");
364 # Put it under HEAD by default, I guess
365 $self->{'_pos'} = $self->{'_head'}; # to insert under...
369 # Neither under head nor body, nor right under html... pass thru?
371 "Ambilocal element <$tag> neither under head nor body, nor right under html!?");
375 #----------------------------------------------------------------------
376 } elsif ($HTML::TreeBuilder::isBodyElement{$tag}) {
378 # Ensure that we are within <body>
379 if($ptag eq 'body') {
381 } elsif($HTML::TreeBuilder::isBodyElement{$ptag} # glarg
382 and not $HTML::TreeBuilder::isHeadOrBodyElement{$ptag}
384 # Special case: Save ourselves a call to is_inside further down.
385 # If our $ptag is an isBodyElement element (but not an
386 # isHeadOrBodyElement element), then we must be under body!
387 print $indent, " * Inferring that $ptag is under BODY.\n",
389 # I think this and the test for 'body' trap everything
390 # bodyworthy, except the case where the parent element is
391 # under an unknown element that's a descendant of body.
392 } elsif ($pos->is_inside('head')) {
394 " * body-element \U$tag\E minimizes HEAD, makes implicit BODY.\n"
397 $pos = $self->{'_pos'} = $self->{'_body'} # yes, needs updating
398 || die "Where'd my body go?"
399 )->{'_tag'}; # yes, needs updating
400 } elsif (! $pos->is_inside('body')) {
402 " * body-element \U$tag\E makes implicit BODY.\n"
405 $pos = $self->{'_pos'} = $self->{'_body'} # yes, needs updating
406 || die "Where'd my body go?"
407 )->{'_tag'}; # yes, needs updating
409 # else we ARE under body, so okay.
412 # Handle implicit endings and insert based on <tag> and position
413 # ... ALL HOPE ABANDON ALL YE WHO ENTER HERE ...
415 $tag eq 'h1' or $tag eq 'h2' or $tag eq 'h3' or
416 $tag eq 'h4' or $tag eq 'h5' or $tag eq 'h6' or
418 # Hm, should <form> really be here?!
420 # Can't have <p>, <h#> or <form> inside these
421 $self->end($_Closed_by_structurals,
422 @HTML::TreeBuilder::p_closure_barriers
423 # used to be just li!
426 } elsif ($tag eq 'ol' or $tag eq 'ul' or $tag eq 'dl') {
427 # Can't have lists inside <h#> -- in the unlikely
428 # event anyone tries to put them there!
430 $ptag eq 'h1' or $ptag eq 'h2' or $ptag eq 'h3' or
431 $ptag eq 'h4' or $ptag eq 'h5' or $ptag eq 'h6'
435 # TODO: Maybe keep closing up the tree until
436 # the ptag isn't any of the above?
437 # But anyone that says <h1><h2><ul>...
438 # deserves what they get anyway.
440 } elsif ($tag eq 'li') { # list item
441 # Get under a list tag, one way or another
443 exists $HTML::TreeBuilder::isList{$ptag} or
444 $self->end(\q{*}, keys %HTML::TreeBuilder::isList) #'
447 " * inserting implicit UL for lack of containing ",
448 join('|', keys %HTML::TreeBuilder::isList), ".\n"
450 $self->insert_element('ul', 1);
453 } elsif ($tag eq 'dt' or $tag eq 'dd') {
454 # Get under a DL, one way or another
455 unless($ptag eq 'dl' or $self->end(\q{*}, 'dl')) { #'
457 " * inserting implicit DL for lack of containing DL.\n"
459 $self->insert_element('dl', 1);
462 } elsif ($HTML::TreeBuilder::isFormElement{$tag}) {
463 if($self->{'_ignore_formies_outside_form'} # TODO: document this
464 and not $pos->is_inside('form')
467 " * ignoring \U$tag\E because not in a FORM.\n"
469 return; # bypass tweaking.
471 if($tag eq 'option') {
472 # return unless $ptag eq 'select';
473 $self->end(\q{option});
474 $ptag = ($self->{'_pos'} || $self)->{'_tag'};
475 unless($ptag eq 'select' or $ptag eq 'optgroup') {
476 print $indent, " * \U$tag\E makes an implicit SELECT.\n"
478 $pos = $self->insert_element('select', 1);
479 # but not a very useful select -- has no 'name' attribute!
480 # is $pos's value used after this?
483 } elsif ($HTML::TreeBuilder::isTableElement{$tag}) {
484 if(!$pos->is_inside('table')) {
485 print $indent, " * \U$tag\E makes an implicit TABLE\n"
487 $self->insert_element('table', 1);
490 if($tag eq 'td' or $tag eq 'th') {
491 # Get under a tr one way or another
493 $ptag eq 'tr' # either under a tr
494 or $self->end(\q{*}, 'tr', 'table') #or we can get under one
497 " * \U$tag\E under \U$ptag\E makes an implicit TR\n"
499 $self->insert_element('tr', 1);
500 # presumably pos's value isn't used after this.
503 $self->end(\$tag, 'table'); #'
505 # Hmm, I guess this is right. To work it out:
506 # tr closes any open tr (limited at a table)
507 # thead closes any open thead (limited at a table)
508 # tbody closes any open tbody (limited at a table)
509 # tfoot closes any open tfoot (limited at a table)
510 # colgroup closes any open colgroup (limited at a table)
511 # col can try, but will always fail, at the enclosing table,
512 # as col is empty, and therefore never open!
514 # td closes any open td OR th (limited at a table)
515 # th closes any open th OR td (limited at a table)
516 # ...implementable as "close to a tr, or make a tr"
518 } elsif ($HTML::TreeBuilder::isPhraseMarkup{$tag}) {
519 if($ptag eq 'body' and $self->{'_implicit_body_p_tag'}) {
521 " * Phrasal \U$tag\E right under BODY makes an implicit P\n"
523 $pos = $self->insert_element('p', 1);
524 # is $pos's value used after this?
527 # End of implicit endings logic
529 # End of "elsif ($HTML::TreeBuilder::isBodyElement{$tag}"
530 #----------------------------------------------------------------------
532 } elsif ($HTML::TreeBuilder::isHeadElement{$tag}) {
533 if ($pos->is_inside('body')) {
534 print $indent, " * head element \U$tag\E found inside BODY!\n"
536 $self->warning("Header element <$tag> in body"); # [sic]
537 } elsif (!$pos->is_inside('head')) {
538 print $indent, " * head element \U$tag\E makes an implicit HEAD.\n"
542 " * head element \U$tag\E goes inside existing HEAD.\n"
545 $self->{'_pos'} = $self->{'_head'} || die "Where'd my head go?";
547 #----------------------------------------------------------------------
548 } elsif ($tag eq 'html') {
549 if(delete $self->{'_implicit'}) { # first time here
550 print $indent, " * good! found the real HTML element!\n"
553 print $indent, " * Found a second HTML element\n"
555 $self->warning("Found a nested <html> element");
558 # in either case, migrate attributes to the real element
560 $self->attr($_, $attr->{$_});
562 $self->{'_pos'} = undef;
563 return $self; # bypass tweaking.
565 #----------------------------------------------------------------------
566 } elsif ($tag eq 'head') {
567 my $head = $self->{'_head'} || die "Where'd my head go?";
568 if(delete $head->{'_implicit'}) { # first time here
569 print $indent, " * good! found the real HEAD element!\n"
571 } else { # been here before
572 print $indent, " * Found a second HEAD element\n"
574 $self->warning("Found a second <head> element");
577 # in either case, migrate attributes to the real element
579 $head->attr($_, $attr->{$_});
581 return $self->{'_pos'} = $head; # bypass tweaking.
583 #----------------------------------------------------------------------
584 } elsif ($tag eq 'body') {
585 my $body = $self->{'_body'} || die "Where'd my body go?";
586 if(delete $body->{'_implicit'}) { # first time here
587 print $indent, " * good! found the real BODY element!\n"
589 } else { # been here before
590 print $indent, " * Found a second BODY element\n"
592 $self->warning("Found a second <body> element");
595 # in either case, migrate attributes to the real element
597 $body->attr($_, $attr->{$_});
599 return $self->{'_pos'} = $body; # bypass tweaking.
601 #----------------------------------------------------------------------
602 } elsif ($tag eq 'frameset') {
604 !($self->{'_frameset_seen'}++) # first frameset seen
605 and !$self->{'_noframes_seen'}
606 # otherwise it'll be under the noframes already
607 and !$self->is_inside('body')
609 # The following is a bit of a hack. We don't use the normal
610 # insert_element because 1) we don't want it as _pos, but instead
611 # right under $self, and 2), more importantly, that we don't want
612 # this inserted at the /end/ of $self's content_list, but instead
613 # in the middle of it, specifiaclly right before the body element.
615 my $c = $self->{'_content'} || die "Contentless root?";
616 my $body = $self->{'_body'} || die "Where'd my BODY go?";
617 for(my $i = 0; $i < @$c; ++$i) {
618 if($c->[$i] eq $body) {
619 splice(@$c, $i, 0, $self->{'_pos'} = $pos = $e);
620 $e->{'_parent'} = $self;
621 $already_inserted = 1;
622 print $indent, " * inserting 'frameset' right before BODY.\n"
627 die "BODY not found in children of root?" unless $already_inserted;
630 } elsif ($tag eq 'frame') {
631 # Okay, fine, pass thru.
632 # Should probably enforce that these should be under a frameset.
633 # But hey. Ditto for enforcing that 'noframes' should be under
634 # a 'frameset', as the DTDs say.
636 } elsif ($tag eq 'noframes') {
637 # This basically assumes there'll be exactly one 'noframes' element
638 # per document. At least, only the first one gets to have the
639 # body under it. And if there are no noframes elements, then
640 # the body pretty much stays where it is. Is that ever a problem?
641 if($self->{'_noframes_seen'}++) {
642 print $indent, " * ANOTHER noframes element?\n" if DEBUG;
644 if($pos->is_inside('body')) {
645 print $indent, " * 'noframes' inside 'body'. Odd!\n" if DEBUG;
646 # In that odd case, we /can't/ make body a child of 'noframes',
647 # because it's an ancestor of the 'noframes'!
649 $e->push_content( $self->{'_body'} || die "Where'd my body go?" );
650 print $indent, " * Moving body to be under noframes.\n" if DEBUG;
654 #----------------------------------------------------------------------
657 if ($self->{'_ignore_unknown'}) {
658 print $indent, " * Ignoring unknown tag \U$tag\E\n" if DEBUG;
659 $self->warning("Skipping unknown tag $tag");
662 print $indent, " * Accepting unknown tag \U$tag\E\n"
666 #----------------------------------------------------------------------
671 $indent, "(Attaching ", $e->{'_tag'}, " under ",
672 ($self->{'_pos'} || $self)->{'_tag'}, ")\n"
673 # because if _pos isn't defined, it goes under self
677 # The following if-clause is to delete /some/ ignorable whitespace
678 # nodes, as we're making the tree.
679 # This'd be a node we'd catch later anyway, but we might as well
680 # nip it in the bud now.
681 # This doesn't catch /all/ deletable WS-nodes, so we do have to call
682 # the tightener later to catch the rest.
684 if($self->{'_tighten'} and !$self->{'_ignore_text'}) { # if tightenable
687 ($sibs = ( $par = $self->{'_pos'} || $self )->{'_content'})
688 and @$sibs # parent already has content
689 and !ref($sibs->[-1]) # and the last one there is a text node
690 and $sibs->[-1] !~ m<[^\n\r\f\t ]>s # and it's all whitespace
692 and ( # one of these has to be eligible...
693 $HTML::TreeBuilder::canTighten{$tag}
697 ? # WS is leftmost -- so parent matters
698 $HTML::TreeBuilder::canTighten{$par->{'_tag'}}
699 : # WS is after another node -- it matters
701 and $HTML::TreeBuilder::canTighten{$sibs->[-2]{'_tag'}}
706 and !$par->is_inside('pre', 'xmp', 'textarea', 'plaintext')
710 print $indent, "Popping a preceding all-WS node\n" if DEBUG;
714 $self->insert_element($e) unless $already_inserted;
717 if($self->{'_pos'}) {
719 $indent, "(Current lineage of pos: \U$tag\E under ",
722 # $self->{'_pos'}{'_tag'}, # don't list myself!
723 $self->{'_pos'}->lineage_tag_names
728 print $indent, "(Pos points nowhere!?)\n";
732 unless(($self->{'_pos'} || '') eq $e) {
733 # if it's an empty element -- i.e., if it didn't change the _pos
734 &{ $self->{"_tweak_$tag"}
735 || $self->{'_tweak_*'}
737 }(map $_, $e, $tag, $self); # make a list so the user can't clobber
744 #==========================================================================
750 return if $_[0]{'_stunted'};
752 # Either: Acccept an end-tag signal from HTML::Parser
753 # Or: Method for closing currently open elements in some fairly complex
754 # way, as used by other methods in this class.
755 my($self, $tag, @stop) = @_;
756 if($tag eq 'x-html') {
757 print "Ignoring close-x-html tag.\n" if DEBUG;
758 # inserted by some lame code-generators.
762 unless(ref($tag) or $tag =~ m/^[-_a-zA-Z0-9:%]+$/s) {
763 DEBUG and print "End-tag name $tag is no good. Skipping.\n";
765 # This avoids having Element's new() throw an exception.
768 # This method accepts two calling formats:
769 # 1) from Parser: $self->end('tag_name', 'origtext')
770 # in which case we shouldn't mistake origtext as a blocker tag
771 # 2) from myself: $self->end(\q{tagname1}, 'blk1', ... )
772 # from myself: $self->end(['tagname1', 'tagname2'], 'blk1', ... )
774 # End the specified tag, but don't move above any of the blocker tags.
775 # The tag can also be a reference to an array. Terminate the first
778 my $ptag = ( my $p = $self->{'_pos'} || $self )->{'_tag'};
779 # $p and $ptag are sort-of stratch
782 # First param is a ref of one sort or another --
783 # THE CALL IS COMING FROM INSIDE THE HOUSE!
784 $tag = $$tag if ref($tag) eq 'SCALAR';
785 # otherwise it's an arrayref.
787 # the call came from Parser -- just ignore origtext
793 # optimization -- don't figure out depth unless we're in debug mode
794 my @lineage_tags = $p->lineage_tag_names;
795 $indent = ' ' x (1 + @lineage_tags);
797 # now announce ourselves
798 print $indent, "Ending ",
799 ref($tag) ? ('[', join(' ', @$tag ), ']') : "\U$tag\E",
800 scalar(@stop) ? (" no higher than [", join(' ', @stop), "]" )
804 print $indent, " (Current lineage: ", join('/', @lineage_tags), ".)\n"
809 # $package, $filename, $line, $subroutine,
810 # $hasargs, $wantarray, $evaltext, $is_require) = caller;
812 " (Called from ", (caller(1))[3], ' line ', (caller(1))[2],
824 # Special -- close everything up to (but not including) the first
825 # limiting tag, or return if none found. Somewhat of a special case.
828 $ptag = $p->{'_tag'};
829 print $indent, " (Looking at $ptag.)\n" if DEBUG > 2;
832 print $indent, " (Hit a $_; closing everything up to here.)\n"
838 $p = $p->{'_parent'}; # no match so far? keep moving up
841 " (Moving on up to ", $p ? $p->{'_tag'} : 'nil', ")\n"
845 unless(defined $p) { # We never found what we were looking for.
846 print $indent, " (We never found a limit.)\n" if DEBUG > 1;
851 # " (To close: ", join('/', map $_->tag, @to_close), ".)\n"
854 # Otherwise update pos and fall thru.
855 $self->{'_pos'} = $p;
857 # Close the first of any of the matching tags, giving up if you hit
858 # any of the stop-tags.
861 $ptag = $p->{'_tag'};
862 print $indent, " (Looking at $ptag.)\n" if DEBUG > 2;
865 print $indent, " (Closing $_.)\n" if DEBUG > 2;
871 print $indent, " (Hit a limiting $_ -- bailing out.)\n"
873 return; # so it was all for naught
877 $p = $p->{'_parent'};
879 return unless defined $p; # We went off the top of the tree.
880 # Otherwise specified element was found; set pos to its parent.
882 $self->{'_pos'} = $p->{'_parent'};
884 # Close the first of the specified tag, giving up if you hit
885 # any of the stop-tags.
887 $ptag = $p->{'_tag'};
888 print $indent, " (Looking at $ptag.)\n" if DEBUG > 2;
890 print $indent, " (Closing $tag.)\n" if DEBUG > 2;
895 print $indent, " (Hit a limiting $_ -- bailing out.)\n"
897 return; # so it was all for naught
901 $p = $p->{'_parent'};
903 return unless defined $p; # We went off the top of the tree.
904 # Otherwise specified element was found; set pos to its parent.
906 $self->{'_pos'} = $p->{'_parent'};
909 $self->{'_pos'} = undef if $self eq ($self->{'_pos'} || '');
910 print $indent, "(Pos now points to ",
911 $self->{'_pos'} ? $self->{'_pos'}{'_tag'} : '???', ".)\n"
914 ### EXPENSIVE, because has to check that it's not under a pre
915 ### or a CDATA-parent. That's one more method call per end()!
916 ### Might as well just do this at the end of the tree-parse, I guess,
917 ### at which point we'd be parsing top-down, and just not traversing
918 ### under pre's or CDATA-parents.
920 ## Take this opportunity to nix any terminal whitespace nodes.
921 ## TODO: consider whether this (plus the logic in start(), above)
922 ## would ever leave any WS nodes in the tree.
923 ## If not, then there's no reason to have eof() call
924 ## delete_ignorable_whitespace on the tree, is there?
926 #if(@to_close and $self->{'_tighten'} and !$self->{'_ignore_text'} and
927 # ! $to_close[-1]->is_inside('pre', keys %HTML::Tagset::isCDATA_Parent)
928 #) { # if tightenable
929 # my($children, $e_tag);
930 # foreach my $e (reverse @to_close) { # going top-down
931 # last if 'pre' eq ($e_tag = $e->{'_tag'}) or
932 # $HTML::Tagset::isCDATA_Parent{$e_tag};
935 # $children = $e->{'_content'}
936 # and @$children # has children
937 # and !ref($children->[-1])
938 # and $children->[-1] =~ m<^\s+$>s # last node is all-WS
941 # # has a tightable parent:
942 # $HTML::TreeBuilder::canTighten{ $e_tag }
944 # ( # has a tightenable left sibling:
946 # ref($children->[-2])
947 # and $HTML::TreeBuilder::canTighten{ $children->[-2]{'_tag'} }
952 # #print $indent, "Popping a terminal WS node from ", $e->{'_tag'},
953 # # " (", $e->address, ") while exiting.\n" if DEBUG;
959 foreach my $e (@to_close) {
960 # Call the applicable callback, if any
961 $ptag = $e->{'_tag'};
962 &{ $self->{"_tweak_$ptag"}
963 || $self->{'_tweak_*'}
965 }(map $_, $e, $ptag, $self);
966 print $indent, "Back from tweaking.\n" if DEBUG;
967 last if $self->{'_stunted'}; # in case one of the handlers called stunt
973 #==========================================================================
975 my($indent, $nugget);
978 return if $_[0]{'_stunted'};
980 # Accept a "here's a text token" signal from HTML::Parser.
981 my($self, $text, $is_cdata) = @_;
982 # the >3.0 versions of Parser may pass a cdata node.
983 # Thanks to Gisle Aas for pointing this out.
985 return unless length $text; # I guess that's always right
987 my $ignore_text = $self->{'_ignore_text'};
988 my $no_space_compacting = $self->{'_no_space_compacting'};
990 my $pos = $self->{'_pos'} || $self;
992 HTML::Entities::decode($text)
993 unless $ignore_text || $is_cdata
994 || $HTML::Tagset::isCDATA_Parent{$pos->{'_tag'}};
996 #my($indent, $nugget);
998 # optimization -- don't figure out depth unless we're in debug mode
999 my @lineage_tags = $pos->lineage_tag_names;
1000 $indent = ' ' x (1 + @lineage_tags);
1002 $nugget = (length($text) <= 25) ? $text : (substr($text,0,25) . '...');
1003 $nugget =~ s<([\x00-\x1F])>
1004 <'\\x'.(unpack("H2",$1))>eg;
1006 $indent, "Proposing a new text node ($nugget) under ",
1007 join('/', reverse($pos->{'_tag'}, @lineage_tags)) || 'Root',
1016 if ($HTML::Tagset::isCDATA_Parent{$ptag = $pos->{'_tag'}}
1017 #or $pos->is_inside('pre')
1018 or $pos->is_inside('pre', 'textarea')
1020 return if $ignore_text;
1021 $pos->push_content($text);
1023 # return unless $text =~ /\S/; # This is sometimes wrong
1025 if (!$self->{'_implicit_tags'} || $text !~ /[^\n\r\f\t ]/) {
1026 # don't change anything
1027 } elsif ($ptag eq 'head' or $ptag eq 'noframes') {
1028 if($self->{'_implicit_body_p_tag'}) {
1030 " * Text node under \U$ptag\E closes \U$ptag\E, implicates BODY and P.\n"
1035 ? ($self->{'_pos'} = $self->{'_body'}) # expected case
1036 : $self->insert_element('body', 1);
1037 $pos = $self->insert_element('p', 1);
1040 " * Text node under \U$ptag\E closes, implicates BODY.\n"
1045 ? ($self->{'_pos'} = $self->{'_body'}) # expected case
1046 : $self->insert_element('body', 1);
1048 } elsif ($ptag eq 'html') {
1049 if($self->{'_implicit_body_p_tag'}) {
1051 " * Text node under HTML implicates BODY and P.\n"
1055 ? ($self->{'_pos'} = $self->{'_body'}) # expected case
1056 : $self->insert_element('body', 1);
1057 $pos = $self->insert_element('p', 1);
1060 " * Text node under HTML implicates BODY.\n"
1064 ? ($self->{'_pos'} = $self->{'_body'}) # expected case
1065 : $self->insert_element('body', 1);
1066 #print "POS is $pos, ", $pos->{'_tag'}, "\n";
1068 } elsif ($ptag eq 'body') {
1069 if($self->{'_implicit_body_p_tag'}) {
1071 " * Text node under BODY implicates P.\n"
1073 $pos = $self->insert_element('p', 1);
1075 } elsif ($ptag eq 'table') {
1077 " * Text node under TABLE implicates TR and TD.\n"
1079 $self->insert_element('tr', 1);
1080 $pos = $self->insert_element('td', 1);
1082 } elsif ($ptag eq 'tr') {
1084 " * Text node under TR implicates TD.\n"
1086 $pos = $self->insert_element('td', 1);
1089 # # $ptag eq 'li' ||
1090 # # $ptag eq 'dd' ||
1091 # $ptag eq 'form') {
1092 # $pos = $self->insert_element('p', 1);
1096 # Whatever we've done above should have had the side
1097 # effect of updating $self->{'_pos'}
1100 #print "POS is now $pos, ", $pos->{'_tag'}, "\n";
1102 return if $ignore_text;
1103 $text =~ s/[\n\r\f\t ]+/ /g # canonical space
1104 unless $no_space_compacting ;
1107 $indent, " (Attaching text node ($nugget) under ",
1108 # was: $self->{'_pos'} ? $self->{'_pos'}{'_tag'} : $self->{'_tag'},
1113 $pos->push_content($text);
1116 &{ $self->{'_tweak_~text'} || return }($text, $pos, $pos->{'_tag'} . '');
1117 # Note that this is very exceptional -- it doesn't fall back to
1118 # _tweak_*, and it gives its tweak different arguments.
1123 #==========================================================================
1125 # TODO: test whether comment(), declaration(), and process(), do the right
1126 # thing as far as tightening and whatnot.
1127 # Also, currently, doctypes and comments that appear before head or body
1128 # show up in the tree in the wrong place. Something should be done about
1129 # this. Tricky. Maybe this whole business of pre-making the body and
1133 return if $_[0]{'_stunted'};
1134 # Accept a "here's a comment" signal from HTML::Parser.
1136 my($self, $text) = @_;
1137 my $pos = $self->{'_pos'} || $self;
1138 return unless $self->{'_store_comments'}
1139 || $HTML::Tagset::isCDATA_Parent{ $pos->{'_tag'} };
1142 my @lineage_tags = $pos->lineage_tag_names;
1143 my $indent = ' ' x (1 + @lineage_tags);
1145 my $nugget = (length($text) <= 25) ? $text : (substr($text,0,25) . '...');
1146 $nugget =~ s<([\x00-\x1F])>
1147 <'\\x'.(unpack("H2",$1))>eg;
1149 $indent, "Proposing a Comment ($nugget) under ",
1150 join('/', reverse($pos->{'_tag'}, @lineage_tags)) || 'Root',
1155 $self->{'_element_class'} || 'HTML::Element'
1156 )->new('~comment'))->{'text'} = $text;
1157 $pos->push_content($e);
1158 ++($self->{'_element_count'});
1160 &{ $self->{'_tweak_~comment'}
1161 || $self->{'_tweak_*'}
1163 }(map $_, $e, '~comment', $self);
1169 return if $_[0]{'_stunted'};
1170 # Accept a "here's a markup declaration" signal from HTML::Parser.
1172 my($self, $text) = @_;
1173 my $pos = $self->{'_pos'} || $self;
1176 my @lineage_tags = $pos->lineage_tag_names;
1177 my $indent = ' ' x (1 + @lineage_tags);
1179 my $nugget = (length($text) <= 25) ? $text : (substr($text,0,25) . '...');
1180 $nugget =~ s<([\x00-\x1F])>
1181 <'\\x'.(unpack("H2",$1))>eg;
1183 $indent, "Proposing a Declaration ($nugget) under ",
1184 join('/', reverse($pos->{'_tag'}, @lineage_tags)) || 'Root',
1188 $self->{'_element_class'} || 'HTML::Element'
1189 )->new('~declaration'))->{'text'} = $text;
1191 $self->{_decl} = $e;
1195 #==========================================================================
1198 return if $_[0]{'_stunted'};
1199 # Accept a "here's a PI" signal from HTML::Parser.
1201 return unless $_[0]->{'_store_pis'};
1202 my($self, $text) = @_;
1203 my $pos = $self->{'_pos'} || $self;
1206 my @lineage_tags = $pos->lineage_tag_names;
1207 my $indent = ' ' x (1 + @lineage_tags);
1209 my $nugget = (length($text) <= 25) ? $text : (substr($text,0,25) . '...');
1210 $nugget =~ s<([\x00-\x1F])>
1211 <'\\x'.(unpack("H2",$1))>eg;
1213 $indent, "Proposing a PI ($nugget) under ",
1214 join('/', reverse($pos->{'_tag'}, @lineage_tags)) || 'Root',
1218 $self->{'_element_class'} || 'HTML::Element'
1219 )->new('~pi'))->{'text'} = $text;
1220 $pos->push_content($e);
1221 ++($self->{'_element_count'});
1223 &{ $self->{'_tweak_~pi'}
1224 || $self->{'_tweak_*'}
1226 }(map $_, $e, '~pi', $self);
1232 #==========================================================================
1234 #When you call $tree->parse_file($filename), and the
1235 #tree's ignore_ignorable_whitespace attribute is on (as it is
1236 #by default), HTML::TreeBuilder's logic will manage to avoid
1237 #creating some, but not all, nodes that represent ignorable
1238 #whitespace. However, at the end of its parse, it traverses the
1239 #tree and deletes any that it missed. (It does this with an
1240 #around-method around HTML::Parser's eof method.)
1242 #However, with $tree->parse($content), the cleanup-traversal step
1243 #doesn't happen automatically -- so when you're done parsing all
1244 #content for a document (regardless of whether $content is the only
1245 #bit, or whether it's just another chunk of content you're parsing into
1246 #the tree), call $tree->eof() to signal that you're at the end of the
1247 #text you're inputting to the tree. Besides properly cleaning any bits
1248 #of ignorable whitespace from the tree, this will also ensure that
1249 #HTML::Parser's internal buffer is flushed.
1252 # Accept an "end-of-file" signal from HTML::Parser, or thrown by the user.
1254 return if $_[0]->{'_done'}; # we've already been here
1256 return $_[0]->SUPER::eof() if $_[0]->{'_stunted'};
1259 print "EOF received.\n" if DEBUG;
1262 # I don't think this makes any difference for this particular
1263 # method, but let's be scrupulous, for once.
1264 @rv = $x->SUPER::eof();
1266 $rv[0] = $x->SUPER::eof();
1269 $x->end('html') unless $x eq ($x->{'_pos'} || $x);
1270 # That SHOULD close everything, and will run the appropriate tweaks.
1271 # We /could/ be running under some insane mode such that there's more
1272 # than one HTML element, but really, that's just insane to do anyhow.
1274 unless($x->{'_implicit_tags'}) {
1275 # delete those silly implicit head and body in case we put
1276 # them there in implicit tags mode
1277 foreach my $node ($x->{'_head'}, $x->{'_body'}) {
1278 $node->replace_with_content
1279 if defined $node and ref $node
1280 and $node->{'_implicit'} and $node->{'_parent'};
1281 # I think they should be empty anyhow, since the only
1282 # logic that'd insert under them can apply only, I think,
1283 # in the case where _implicit_tags is on
1285 # this may still leave an implicit 'html' at the top, but there's
1286 # nothing we can do about that, is there?
1289 $x->delete_ignorable_whitespace()
1290 # this's why we trap this -- an after-method
1291 if $x->{'_tighten'} and ! $x->{'_ignore_text'};
1294 return @rv if wantarray;
1298 #==========================================================================
1304 print "Stunting the tree.\n" if DEBUG;
1305 $self->{'_done'} = 1;
1307 if($HTML::Parser::VERSION < 3) {
1308 #This is a MEAN MEAN HACK. And it works most of the time!
1309 $self->{'_buf'} = '';
1310 my $fh = *HTML::Parser::F{IO};
1311 # the local'd FH used by parse_file loop
1313 print "Closing Parser's filehandle $fh\n" if DEBUG;
1317 # But if they called $tree->parse_file($filehandle)
1318 # or $tree->parse_file(*IO), then there will be no *HTML::Parser::F{IO}
1319 # to close. Ahwell. Not a problem for most users these days.
1322 $self->SUPER::eof();
1323 # Under 3+ versions, calling eof from inside a parse will abort the
1324 # parse / parse_file
1327 # In the off chance that the above didn't work, we'll throw
1328 # this flag to make any future events be no-ops.
1334 sub stunted { shift->_elem('_stunted', @_); }
1335 sub done { shift->_elem('_done', @_); }
1337 #==========================================================================
1340 # Override Element's delete method.
1341 # This does most, if not all, of what Element's delete does anyway.
1342 # Deletes content, including content in some special attributes.
1343 # But doesn't empty out the hash.
1345 $_[0]->{'_element_count'} = 1; # never hurts to be scrupulously correct
1347 delete @{$_[0]}{'_body', '_head', '_pos'};
1348 for (@{ delete($_[0]->{'_content'})
1350 }, # all/any content
1351 # delete @{$_[0]}{'_body', '_head', '_pos'}
1352 # ...and these, in case these elements don't appear in the
1353 # content, which is possible. If they did appear (as they
1354 # usually do), then calling $_->delete on them again is harmless.
1355 # I don't think that's such a hot idea now. Thru creative reattachment,
1356 # those could actually now point to elements in OTHER trees (which we do
1357 # NOT want to delete!).
1359 # If these point to elements not in the content list of any element in this
1360 # tree, but not in the content list of any element in any OTHER tree, then
1361 # just deleting these will make their refcounts hit zero.
1362 # If these point to elements in the content lists of elements in THIS tree,
1363 # then we'll get to deleting them when we delete from the top.
1364 # If these point to elements in the content lists of elements in SOME OTHER
1365 # tree, then they're not to be deleted.
1369 if defined $_ and ref $_ # Make sure it's an object.
1370 and $_ ne $_[0]; # And avoid hitting myself, just in case!
1373 $_[0]->detach if $_[0]->{'_parent'} and $_[0]->{'_parent'}{'_content'};
1374 # An 'html' element having a parent is quite unlikely.
1379 sub tighten_up { # legacy
1380 shift->delete_ignorable_whitespace(@_);
1384 # Rebless this object down into the normal element class.
1386 my $to_class = ($self->{'_element_class'} || 'HTML::Element');
1387 delete @{$self}{ grep {;
1388 length $_ and substr($_,0,1) eq '_'
1389 # The private attributes that we'll retain:
1390 and $_ ne '_tag' and $_ ne '_parent' and $_ ne '_content'
1391 and $_ ne '_implicit' and $_ ne '_pos'
1392 and $_ ne '_element_class'
1394 bless $self, $to_class; # Returns the same object we were fed
1397 #--------------------------------------------------------------------------
1401 my @stack = ($_[0]);
1402 my $destructive = $_[1];
1405 $this = shift @stack;
1407 push @out, $this; # yes, it can include text nodes
1408 } elsif(! $this->{'_implicit'}) {
1410 delete $this->{'_parent'} if $destructive;
1412 # it's an implicit node. Delete it and recurse
1413 delete $this->{'_parent'} if $destructive;
1416 delete($this->{'_content'})
1417 : $this->{'_content'}
1423 # Doesn't call a real $root->delete on the (when implicit) root,
1424 # but I don't think it needs to.
1426 return @out if wantarray; # one simple normal case.
1427 return undef unless @out;
1428 return $out[0] if @out == 1 and ref($out[0]);
1429 my $x = HTML::Element->new('div', '_implicit' => 1);
1430 $x->push_content(@out);
1434 sub disembowel { $_[0]->guts(1) }
1436 #--------------------------------------------------------------------------
1443 HTML::TreeBuilder - Parser that builds a HTML syntax tree
1447 foreach my $file_name (@ARGV) {
1448 my $tree = HTML::TreeBuilder->new; # empty tree
1449 $tree->parse_file($file_name);
1450 print "Hey, here's a dump of the parse tree of $file_name:\n";
1451 $tree->dump; # a method we inherit from HTML::Element
1452 print "And here it is, bizarrely rerendered as HTML:\n",
1453 $tree->as_HTML, "\n";
1455 # Now that we're done with it, we must destroy it.
1456 $tree = $tree->delete;
1461 (This class is part of the L<HTML::Tree|HTML::Tree> dist.)
1463 This class is for HTML syntax trees that get built out of HTML
1464 source. The way to use it is to:
1466 1. start a new (empty) HTML::TreeBuilder object,
1468 2. then use one of the methods from HTML::Parser (presumably with
1469 $tree->parse_file($filename) for files, or with
1470 $tree->parse($document_content) and $tree->eof if you've got
1471 the content in a string) to parse the HTML
1472 document into the tree $tree.
1474 (You can combine steps 1 and 2 with the "new_from_file" or
1475 "new_from_content" methods.)
1477 2b. call $root-E<gt>elementify() if you want.
1479 3. do whatever you need to do with the syntax tree, presumably
1480 involving traversing it looking for some bit of information in it,
1482 4. and finally, when you're done with the tree, call $tree->delete() to
1483 erase the contents of the tree from memory. This kind of thing
1484 usually isn't necessary with most Perl objects, but it's necessary for
1485 TreeBuilder objects. See L<HTML::Element|HTML::Element> for a more verbose
1486 explanation of why this is the case.
1488 =head1 METHODS AND ATTRIBUTES
1490 Objects of this class inherit the methods of both HTML::Parser and
1491 HTML::Element. The methods inherited from HTML::Parser are used for
1492 building the HTML tree, and the methods inherited from HTML::Element
1493 are what you use to scrutinize the tree. Besides this
1494 (HTML::TreeBuilder) documentation, you must also carefully read the
1495 HTML::Element documentation, and also skim the HTML::Parser
1496 documentation -- probably only its parse and parse_file methods are of
1499 Most of the following methods native to HTML::TreeBuilder control how
1500 parsing takes place; they should be set I<before> you try parsing into
1501 the given object. You can set the attributes by passing a TRUE or
1502 FALSE value as argument. E.g., $root->implicit_tags returns the current
1503 setting for the implicit_tags option, $root->implicit_tags(1) turns that
1504 option on, and $root->implicit_tags(0) turns it off.
1508 =item $root = HTML::TreeBuilder->new_from_file(...)
1510 This "shortcut" constructor merely combines constructing a new object
1511 (with the "new" method, below), and calling $new->parse_file(...) on
1512 it. Returns the new object. Note that this provides no way of
1513 setting any parse options like store_comments (for that, call new, and
1514 then set options, before calling parse_file). See the notes (below)
1515 on parameters to parse_file.
1517 =item $root = HTML::TreeBuilder->new_from_content(...)
1519 This "shortcut" constructor merely combines constructing a new object
1520 (with the "new" method, below), and calling for(...){$new->parse($_)}
1521 and $new->eof on it. Returns the new object. Note that this provides
1522 no way of setting any parse options like store_comments (for that,
1523 call new, and then set options, before calling parse_file). Example
1524 usages: HTML::TreeBuilder->new_from_content(@lines), or
1525 HTML::TreeBuilder->new_from_content($content)
1527 =item $root = HTML::TreeBuilder->new()
1529 This creates a new HTML::TreeBuilder object. This method takes no
1532 =item $root->parse_file(...)
1534 [An important method inherited from L<HTML::Parser|HTML::Parser>, which
1535 see. Current versions of HTML::Parser can take a filespec, or a
1536 filehandle object, like *FOO, or some object from class IO::Handle,
1537 IO::File, IO::Socket) or the like.
1538 I think you should check that a given file exists I<before> calling
1539 $root->parse_file($filespec).]
1541 =item $root->parse(...)
1543 [A important method inherited from L<HTML::Parser|HTML::Parser>, which
1544 see. See the note below for $root->eof().]
1548 This signals that you're finished parsing content into this tree; this
1549 runs various kinds of crucial cleanup on the tree. This is called
1550 I<for you> when you call $root->parse_file(...), but not when
1551 you call $root->parse(...). So if you call
1552 $root->parse(...), then you I<must> call $root->eof()
1553 once you've finished feeding all the chunks to parse(...), and
1554 before you actually start doing anything else with the tree in C<$root>.
1556 =item C<< $root->parse_content(...) >>
1558 Basically a happly alias for C<< $root->parse(...); $root->eof >>.
1559 Takes the exact same arguments as C<< $root->parse() >>.
1561 =item $root->delete()
1563 [An important method inherited from L<HTML::Element|HTML::Element>, which
1566 =item $root->elementify()
1568 This changes the class of the object in $root from
1569 HTML::TreeBuilder to the class used for all the rest of the elements
1570 in that tree (generally HTML::Element). Returns $root.
1572 For most purposes, this is unnecessary, but if you call this after
1574 you've finished building a tree, then it keeps you from accidentally
1575 trying to call anything but HTML::Element methods on it. (I.e., if
1576 you accidentally call C<$root-E<gt>parse_file(...)> on the
1577 already-complete and elementified tree, then instead of charging ahead
1578 and I<wreaking havoc>, it'll throw a fatal error -- since C<$root> is
1579 now an object just of class HTML::Element which has no C<parse_file>
1582 Note that elementify currently deletes all the private attributes of
1583 $root except for "_tag", "_parent", "_content", "_pos", and
1584 "_implicit". If anyone requests that I change this to leave in yet
1585 more private attributes, I might do so, in future versions.
1587 =item @nodes = $root->guts()
1589 =item $parent_for_nodes = $root->guts()
1591 In list context (as in the first case), this method returns the topmost
1592 non-implicit nodes in a tree. This is useful when you're parsing HTML
1593 code that you know doesn't expect an HTML document, but instead just
1594 a fragment of an HTML document. For example, if you wanted the parse
1595 tree for a file consisting of just this:
1599 Then you would get that with C<< @nodes = $root->guts(); >>.
1600 It so happens that in this case, C<@nodes> will contain just one
1601 element object, representing the "li" node (with "I like pie!" being
1602 its text child node). However, consider if you were parsing this:
1606 In that case, C<< $root->guts() >> would return three items:
1607 an element object for the first "hr", a text string "Hooboy!", and
1608 another "hr" element object.
1610 For cases where you want definitely one element (so you can treat it as
1611 a "document fragment", roughly speaking), call C<guts()> in scalar
1612 context, as in C<< $parent_for_nodes = $root->guts() >>. That works like
1613 C<guts()> in list context; in fact, C<guts()> in list context would
1614 have returned exactly one value, and if it would have been an object (as
1615 opposed to a text string), then that's what C<guts> in scalar context
1616 will return. Otherwise, if C<guts()> in list context would have returned
1617 no values at all, then C<guts()> in scalar context returns undef. In
1618 all other cases, C<guts()> in scalar context returns an implicit 'div'
1619 element node, with children consisting of whatever nodes C<guts()>
1620 in list context would have returned. Note that that may detach those
1621 nodes from C<$root>'s tree.
1623 =item @nodes = $root->disembowel()
1625 =item $parent_for_nodes = $root->disembowel()
1627 The C<disembowel()> method works just like the C<guts()> method, except
1628 that disembowel definitively destroys the tree above the nodes that
1629 are returned. Usually when you want the guts from a tree, you're just
1630 going to toss out the rest of the tree anyway, so this saves you the
1631 bother. (Remember, "disembowel" means "remove the guts from".)
1633 =item $root->implicit_tags(value)
1635 Setting this attribute to true will instruct the parser to try to
1636 deduce implicit elements and implicit end tags. If it is false you
1637 get a parse tree that just reflects the text as it stands, which is
1638 unlikely to be useful for anything but quick and dirty parsing.
1639 (In fact, I'd be curious to hear from anyone who finds it useful to
1640 have implicit_tags set to false.)
1643 Implicit elements have the implicit() attribute set.
1645 =item $root->implicit_body_p_tag(value)
1647 This controls an aspect of implicit element behavior, if implicit_tags
1648 is on: If a text element (PCDATA) or a phrasal element (such as
1649 "E<lt>emE<gt>") is to be inserted under "E<lt>bodyE<gt>", two things
1650 can happen: if implicit_body_p_tag is true, it's placed under a new,
1651 implicit "E<lt>pE<gt>" tag. (Past DTDs suggested this was the only
1652 correct behavior, and this is how past versions of this module
1653 behaved.) But if implicit_body_p_tag is false, nothing is implicated
1654 -- the PCDATA or phrasal element is simply placed under
1655 "E<lt>bodyE<gt>". Default is false.
1657 =item $root->ignore_unknown(value)
1659 This attribute controls whether unknown tags should be represented as
1660 elements in the parse tree, or whether they should be ignored.
1661 Default is true (to ignore unknown tags.)
1663 =item $root->ignore_text(value)
1665 Do not represent the text content of elements. This saves space if
1666 all you want is to examine the structure of the document. Default is
1669 =item $root->ignore_ignorable_whitespace(value)
1671 If set to true, TreeBuilder will try to avoid
1672 creating ignorable whitespace text nodes in the tree. Default is
1673 true. (In fact, I'd be interested in hearing if there's ever a case
1674 where you need this off, or where leaving it on leads to incorrect
1677 =item $root->no_space_compacting(value)
1679 This determines whether TreeBuilder compacts all whitespace strings
1680 in the document (well, outside of PRE or TEXTAREA elements), or
1681 leaves them alone. Normally (default, value of 0), each string of
1682 contiguous whitespace in the document is turned into a single space.
1683 But that's not done if no_space_compacting is set to 1.
1685 Setting no_space_compacting to 1 might be useful if you want
1686 to read in a tree just to make some minor changes to it before
1687 writing it back out.
1689 This method is experimental. If you use it, be sure to report
1690 any problems you might have with it.
1692 =item $root->p_strict(value)
1694 If set to true (and it defaults to false), TreeBuilder will take a
1695 narrower than normal view of what can be under a "p" element; if it sees
1696 a non-phrasal element about to be inserted under a "p", it will close that
1697 "p". Otherwise it will close p elements only for other "p"'s, headings,
1698 and "form" (altho the latter may be removed in future versions).
1700 For example, when going thru this snippet of code,
1705 TreeBuilder will normally (with C<p_strict> false) put the "ul" element
1706 under the "p" element. However, with C<p_strict> set to true, it will
1707 close the "p" first.
1709 In theory, there should be strictness options like this for other/all
1710 elements besides just "p"; but I treat this as a specal case simply
1711 because of the fact that "p" occurs so frequently and its end-tag is
1712 omitted so often; and also because application of strictness rules
1713 at parse-time across all elements often makes tiny errors in HTML
1714 coding produce drastically bad parse-trees, in my experience.
1716 If you find that you wish you had an option like this to enforce
1717 content-models on all elements, then I suggest that what you want is
1718 content-model checking as a stage after TreeBuilder has finished
1721 =item $root->store_comments(value)
1723 This determines whether TreeBuilder will normally store comments found
1724 while parsing content into C<$root>. Currently, this is off by default.
1726 =item $root->store_declarations(value)
1728 This determines whether TreeBuilder will normally store markup
1729 declarations found while parsing content into C<$root>. This is on
1732 =item $root->store_pis(value)
1734 This determines whether TreeBuilder will normally store processing
1735 instructions found while parsing content into C<$root> -- assuming a
1736 recent version of HTML::Parser (old versions won't parse PIs
1737 correctly). Currently, this is off (false) by default.
1739 It is somewhat of a known bug (to be fixed one of these days, if
1740 anyone needs it?) that PIs in the preamble (before the "html"
1741 start-tag) end up actually I<under> the "html" element.
1743 =item $root->warn(value)
1745 This determines whether syntax errors during parsing should generate
1746 warnings, emitted via Perl's C<warn> function.
1748 This is off (false) by default.
1752 =head1 HTML AND ITS DISCONTENTS
1754 HTML is rather harder to parse than people who write it generally
1757 Here's the problem: HTML is a kind of SGML that permits "minimization"
1758 and "implication". In short, this means that you don't have to close
1759 every tag you open (because the opening of a subsequent tag may
1760 implicitly close it), and if you use a tag that can't occur in the
1761 context you seem to using it in, under certain conditions the parser
1762 will be able to realize you mean to leave the current context and
1763 enter the new one, that being the only one that your code could
1764 correctly be interpreted in.
1766 Now, this would all work flawlessly and unproblematically if: 1) all
1767 the rules that both prescribe and describe HTML were (and had been)
1768 clearly set out, and 2) everyone was aware of these rules and wrote
1769 their code in compliance to them.
1771 However, it didn't happen that way, and so most HTML pages are
1772 difficult if not impossible to correctly parse with nearly any set of
1773 straightforward SGML rules. That's why the internals of
1774 HTML::TreeBuilder consist of lots and lots of special cases -- instead
1775 of being just a generic SGML parser with HTML DTD rules plugged in.
1777 =head1 TRANSLATIONS?
1779 The techniques that HTML::TreeBuilder uses to perform what I consider
1780 very robust parses on everyday code are not things that can work only
1781 in Perl. To date, the algorithms at the center of HTML::TreeBuilder
1782 have been implemented only in Perl, as far as I know; and I don't
1783 foresee getting around to implementing them in any other language any
1786 If, however, anyone is looking for a semester project for an applied
1787 programming class (or if they merely enjoy I<extra-curricular>
1788 masochism), they might do well to see about choosing as a topic the
1789 implementation/adaptation of these routines to any other interesting
1790 programming language that you feel currently suffers from a lack of
1791 robust HTML-parsing. I welcome correspondence on this subject, and
1792 point out that one can learn a great deal about languages by trying to
1793 translate between them, and then comparing the result.
1795 The HTML::TreeBuilder source may seem long and complex, but it is
1796 rather well commented, and symbol names are generally
1797 self-explanatory. (You are encouraged to read the Mozilla HTML parser
1798 source for comparison.) Some of the complexity comes from little-used
1799 features, and some of it comes from having the HTML tokenizer
1800 (HTML::Parser) being a separate module, requiring somewhat of a
1801 different interface than you'd find in a combined tokenizer and
1802 tree-builder. But most of the length of the source comes from the fact
1803 that it's essentially a long list of special cases, with lots and lots
1804 of sanity-checking, and sanity-recovery -- because, as Roseanne
1805 Rosannadanna once said, "it's always I<something>".
1807 Users looking to compare several HTML parsers should look at the
1808 source for Raggett's Tidy
1809 (C<E<lt>http://www.w3.org/People/Raggett/tidy/E<gt>>),
1811 (C<E<lt>http://www.mozilla.org/E<gt>>),
1812 and possibly root around the browsers section of Yahoo
1813 to find the various open-source ones
1814 (C<E<lt>http://dir.yahoo.com/Computers_and_Internet/Software/Internet/World_Wide_Web/Browsers/E<gt>>).
1818 * Framesets seem to work correctly now. Email me if you get a strange
1819 parse from a document with framesets.
1821 * Really bad HTML code will, often as not, make for a somewhat
1822 objectionable parse tree. Regrettable, but unavoidably true.
1824 * If you're running with implicit_tags off (God help you!), consider
1825 that $tree->content_list probably contains the tree or grove from the
1826 parse, and not $tree itself (which will, oddly enough, be an implicit
1827 'html' element). This seems counter-intuitive and problematic; but
1828 seeing as how almost no HTML ever parses correctly with implicit_tags
1829 off, this interface oddity seems the least of your problems.
1833 When a document parses in a way different from how you think it
1834 should, I ask that you report this to me as a bug. The first thing
1835 you should do is copy the document, trim out as much of it as you can
1836 while still producing the bug in question, and I<then> email me that
1837 mini-document I<and> the code you're using to parse it, to the HTML::Tree
1838 bug queue at C<bug-html-tree at rt.cpan.org>.
1840 Include a note as to how it
1841 parses (presumably including its $tree->dump output), and then a
1842 I<careful and clear> explanation of where you think the parser is
1843 going astray, and how you would prefer that it work instead.
1847 L<HTML::Tree>; L<HTML::Parser>, L<HTML::Element>, L<HTML::Tagset>
1853 Copyright 1995-1998 Gisle Aas, 1999-2004 Sean M. Burke, 2005 Andy Lester,
1856 This library is free software; you can redistribute it and/or
1857 modify it under the same terms as Perl itself.
1859 This program is distributed in the hope that it will be useful, but
1860 without any warranty; without even the implied warranty of
1861 merchantability or fitness for a particular purpose.
1865 Currently maintained by Pete Krawczyk C<< <petek@cpan.org> >>
1867 Original authors: Gisle Aas, Sean Burke and Andy Lester.