0
#!/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";

}

my code is not printing any output. $tree->find("p") is returning NULL.

cjm
  • 61,471
  • 9
  • 126
  • 175
dreamer
  • 478
  • 1
  • 11
  • 24
  • 1
    Please ensure that the file exists in the same directory as the script and that it has p elements. Your script ran fine for me outputting the 4 p tags that my sample.html had – Himanshu Nov 05 '12 at 14:51
  • file is in the same directory as the sample.html and it has

    tags. But still it does not return anything.

    – dreamer Nov 05 '12 at 15:49
  • What does `$tree->dump` print? – cjm Nov 05 '12 at 17:44

1 Answers1

0

You're not opening the file, or it's completely unparseable.

Try something like:

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

That way you can check which it is.

Your script worked fine when I had the following for 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>
Richard Huxton
  • 21,516
  • 3
  • 39
  • 51