in reply to Finding the DOM element via text search
#!/usr/bin/perl use warnings; use strict; use HTML::TreeBuilder; my $h = HTML::TreeBuilder->new_from_content( do{local $/;<DATA>}, ); $h->objectify_text; my $text = q{text}; walk($h, $text); sub walk{ my $h = shift; my $text = shift; for my $ele ($h->content_list) { my @lineage = $ele->lineage; my @ancestors; for my $ancestor (reverse @lineage){ push @ancestors, $ancestor->tag; } if ( $ele->tag eq q{~text} and $ele->attr(q{text}) and $ele->attr(q{text}) eq $text ) { printf( qq{%s\t}, $_ ) for @ancestors; printf( qq{found *%s* at depth %s\n}, $ele->attr(q{text}), scalar @ancestors ); } walk($ele, $text); } } __DATA__ <html><head><title>search</title></head> <body> <p>text</p> <div> <p>text</p> </div> </body></html>
html body p found *text* at depth 3 html body div p found *text* at depth 4
|
|---|