HTML::Treebuilder - Parse between parents
Folks,
There is so much info out there on HTML::Treebuilder that I'm surprised I can't find the answer, hopefully I'm not just missing it.
What I'm trying to do is simply parse between parent nodes, so given a html doc like this
<html>
<body>
<a id="111" name="111"></a>
<p>something</p>
<p>something</p>
<p>something</p>
<a href=xxx">something</a>
<a id="222" name="222"></a>
<p>something</p>
<p>something</p>
<p>something</p>
....
</body>
</html>
I want to be able to get the info about that 1st anchor tag (111), then process the 3 p tags and then get the next anchor tag (222) and then process those p tags etc etc.
Its easy to get to each anchor tag
use HTML::TreeBuilder;
my $tree = HTML::TreeBuilder->new();
$tree->parse_file("index-01.htm");
foreach my $atag ( $tree->look_down( '_tag', 'a' ) ) {
if ($atag->attr('id')) {
# Found 'a' tag, now process the p tags until the next 'a'
}
}
But once I find that tag how do I then get 开发者_如何学编程all the p tags until the next anchor?
TIA!!
HTML::TreeBuilder version
#!/usr/bin/perl
use strict; use warnings;
use HTML::TreeBuilder;
my $tree = HTML::TreeBuilder->new;
$tree->parse_file(\*DATA);
$tree->elementify;
$tree->objectify_text;
foreach my $atag ( $tree->look_down( '_tag', 'a' ) ) {
if ($atag->attr('id')) {
printf "Found %s\n", $atag->as_XML;
process_p( $atag );
}
}
sub process_p {
my ($tag) = @_;
while ( defined( $tag ) and defined( my $next = $tag->right ) ) {
last if lc $next->tag eq 'a';
if ( lc $next->tag eq 'p') {
$next->deobjectify_text;
print $next->as_text, "\n";
}
$tag = $next;
}
}
__DATA__
<html>
<body>
<a id="111" name="111"></a>
<p>something</p>
<p>something</p>
<p>something</p>sometext
<a href=xxx">something</a>
<a id="222" name="222"></a>
<p>something</p>
<p>something</p>
<p>something</p>
</body>
</html>
Output:
Found <a id="111" name="111"></a>
something
something
something
Found <a id="222" name="222"></a>
something
something
something
HTML::TokeParser::Simple version
#!/usr/bin/perl
use strict; use warnings;
use HTML::TokeParser::Simple;
my $parser = HTML::TokeParser::Simple->new(\*DATA);
while ( my $tag = $parser->get_tag('a') ) {
next unless $tag->get_attr('id');
printf "Found %s\n", $tag->as_is;
process_p($parser);
}
sub process_p {
my ($parser) = @_;
while ( my $next = $parser->get_token ) {
if ( $next->is_start_tag('a') ) {
$parser->unget_token($next);
return;
}
elsif ( $next->is_start_tag('p') ) {
print $parser->get_text('/p'), "\n";
}
}
return;
}
Output:
Found <a id="111" name="111">
something
something
something
Found <a id="222" name="222">
something
something
something
精彩评论