Reputation: 21
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);
Upvotes: 1
Views: 1163
Reputation: 20280
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"
});
Upvotes: 1
Reputation: 185126
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);
Upvotes: 0
Reputation: 385789
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;
Upvotes: 1