【问题标题】:HTML parser by perl scriptperl 脚本的 HTML 解析器
【发布时间】:2012-10-25 09:58:54
【问题描述】:
#!/usr/bin/perl

use HTML::TreeBuilder;

my $tree = HTML::TreeBuilder->new; 

$tree->parse_file("sample.html");

foreach my $anchor ($tree->find("p")) {

  print $anchor->as_text, "\n";

}

我的代码没有打印任何输出。 $tree->find("p") 正在返回 NULL。

【问题讨论】:

  • 请确保该文件与脚本存在于同一目录中,并且包含 p 个元素。您的脚本运行良好,可以输出我的 sample.html 所具有的 4 p 标签
  • 文件与 sample.html 位于同一目录中,并且具有

    标签。但它仍然没有返回任何东西。

  • $tree->dump 打印什么?

标签: html perl parsing html-parsing html-tree


【解决方案1】:

您没有打开文件,或者它完全无法解析。

尝试类似:

my $file = shift(@ARGV) or die "No filename given";
$tree->parse_file($file) or die "Unable to open $file";

这样你可以检查它是什么。

当我为 sample.html 提供以下内容时,您的脚本运行良好

<html>
<head><title>test file</title></head>
<body>
    <h1>Title</h1>
    <p>First para</p>
    <p>Second para</p>
    <div>
        <P>Third para</P>
    </div>
</body>
</html>

【讨论】:

    猜你喜欢
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 2011-06-03
    • 2016-05-06
    相关资源
    最近更新 更多