我正在尝试解析HTML文档并提取网址,但无法弄清楚如何获取“a”标记的href值。如果有帮助,我正在关注此文档:http://perl.active-venture.com/lib/HTML/TokeParser.html
问题出在第三个'elsif'代码块中。
sub findTokens {
my $htmlFileName = $_[0];
my $pagesDir = $_[1];
my %titles = %{$_[2]};
my %mapping = %{$_[3]};
my @outLinks;
my $p = HTML::TokeParser->new("$pagesDir$htmlFileName")
or die("Can't open $htmlFileName: \n");
my @tokens;
my $url = $mapping{$htmlFileName};
while (my $newChunk = $p->get_token) {
if ($newChunk->[0] eq 'T') {
my @lineArray = split(' ', $newChunk->[1]);
foreach my $i (@lineArray) {
if ( lc($i) =~ /^[a-z]*\-?\'?s?$/) {
push(@tokens, lc($i));
}
}
} elsif ($newChunk->[0] eq 'S') {
if ($newChunk->[1] eq 'title') {
$newChunk = $p->get_token;
$titles{$url} = $newChunk->[1];
#print $url;
#print $titles{$url};
}
} elsif ($newChunk->[0] eq 'S') {
if ($newChunk->[1] eq 'a') {
my %attr = %{$newChunk->[2]};
push(@outLinks, $attr{'href'});
}
}
}
return (\@tokens, \%titles, \@outLinks);
}
答案 0 :(得分:1)
恕我直言,HTML::TokeParser
代表旧学校。
因为我知道HTML::TreeBuilder::XPath
,所以我不能回到过去。
帖子上的示例:
#!/usr/bin/env perl
use strict; use warnings;
use WWW::Mechanize;
use HTML::TreeBuilder::XPath;
my $m = WWW::Mechanize->new( autocheck => 1 );
$m->get("http://stackoverflow.com/q/13790575/465183");
my $tree = HTML::TreeBuilder::XPath->new_from_content( $m->content );
print join "\n", $tree->findvalues( './/a/@href' );