下面的代码显示TreeBuilder方法look_down找不到"section"元素。 为什么?
use strict;
use warnings;
use HTML::TreeBuilder;
my $html =<<'END_HTML';
<html>
<head><title></title></head>
<body>
<div attrname="div">
<section attrname="section">
</section>
</div>
</body>
</html>
END_HTML
my $tree = HTML::TreeBuilder->new_from_content($html);
my @divs = $tree->look_down('attrname', 'div');
print "number of div elements found = ", scalar(@divs), "n";
my @sections = $tree->look_down('attrname', 'section');
print "number of section elements found = ", scalar(@sections), "n";
$tree->delete();
输出: 找到的div 元素数 = 1 找到的剖面元素数 = 0
my @divs = $tree->look_down('attrname', 'div');
print "number of div elements found = ", scalar(@divs), "n";
这找到了一个元素,因为它将属性attrname
与恰好位于<div>
标签上的值div
匹配。
my @sections = $tree->look_down('attrname', 'section');
print "number of section elements found = ", scalar(@sections), "n";
这不匹配任何内容,因为没有带有名为attrname
的属性且值为section
的标记。
他们应该是
my @divs = $tree->look_down(_tag => 'div');
...
my @sections = $tree->look_down(_tag => 'section');
这在 HTML::Element#lookdown 文档中都有一些晦涩的解释。 没有明确的解释什么是"标准",您必须阅读整个页面才能找到伪属性_tag
来引用标签名称......但从长远来看,仔细阅读整个页面可能会为您节省数小时的挫败感:-)
这对我有用:
my $tree = HTML::TreeBuilder->new;
$tree->ignore_unknown(0); # <-- Include unknown elements in tree
$tree->parse($html);
my @divs = $tree->look_down('attrname', 'div');
my @sections = $tree->look_down('attrname', 'section');
print "number of div elements found = ", scalar(@divs), "n";
print "number of section elements found = ", scalar(@sections), "n";
输出:
number of div elements found = 1
number of section elements found = 1