1

I am trying to extract table content from a html file using HTML::TableExtract. My problem is my html file is structured in the following way:

<!DOCTYPE html>
<html>
<body>

    <h4>One row and three columns:</h4>

    <table border="1">
      <tr>
        <td>
        <p> 100 </p></td>
        <td>
        <p> 200 </p></td>
        <td>
        <p> 300 </p></td>
        </tr>
      <tr>
        <td>
        <p> 100 </p></td>
        <td>
        <p> 200 </p></td>
        <td>
        <p> 300 </p></td>
        </tr>
    </table>
</body>
</html>

Because of this structure, my output looks like:

   100|

   200|

   300|

   400|

   500|

   600|

Instead of what I want:

   100|200|300|
   400|500|600|

Can you please help? Here is my perl code

use strict;
use warnings;
use HTML::TableExtract;

my $te = HTML::TableExtract->new();
$te->parse_file('Table_One.html');

open (DATA2, ">TableOutput.txt")
    or die "Can't open file";

foreach my $ts ($te->tables()) {

    foreach my $row ($ts->rows()) {

        my $Final = join('|', @$row );
    print DATA2 "$Final";
    }
}
close (DATA2);
BoltClock
  • 630,065
  • 150
  • 1,295
  • 1,284

3 Answers3

1
sub trim(_) { my ($s) = @_; $s =~ s/^\s+//; $s =~ s/\s+\z//; $s }

Or in Perl 5.14+,

sub trim(_) { $_[0] =~ s/^\s+//r =~ s/\s+\z//r }

Then use:

my $Final = join '|', map trim, @$row;
ikegami
  • 322,729
  • 15
  • 228
  • 466
1

Using Mojo::DOM

#!/usr/bin/env perl

use strict;
use warnings;

use Mojo::DOM;
my $dom = Mojo::DOM->new(<<'END');
<!DOCTYPE html>
<html>
<body>

    <h4>One row and three columns:</h4>

    <table border="1">
      <tr>
        <td>
        <p> 100 </p></td>
        <td>
        <p> 200 </p></td>
        <td>
        <p> 300 </p></td>
        </tr>
      <tr>
        <td>
        <p> 100 </p></td>
        <td>
        <p> 200 </p></td>
        <td>
        <p> 300 </p></td>
        </tr>
    </table>
</body>
END

my $rows = $dom->find('table tr');
$rows->each(sub{ 
  print $_->find('td p')
          ->pluck('text')
          ->join('|') . "|\n"
});
Joel Berger
  • 19,816
  • 5
  • 47
  • 101
0

Try doing this :

use strict;
use warnings;
use HTML::TableExtract;

my $te = HTML::TableExtract->new();
$te->parse_file('Table_One.html');

open (DATA2, ">TableOutput.txt") or die "Can't open file";
foreach my $ts ($te->tables() )
{
    foreach my $row ($ts->rows() )
    {
        s/(\n|\s)//g for @$row;
        my $Final = join('|', @$row );
        print DATA2 "$Final"; 
    }
}
close (DATA2);
Gilles Quenot
  • 143,367
  • 32
  • 199
  • 195