我正在尝试使用HTML :: TableExtract从html文件中提取表内容。我的问题是我的html文件是按以下方式构建的:
<!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>
由于这种结构,我的输出如下:
100|
200|
300|
400|
500|
600|
而不是我想要的:
100|200|300|
400|500|600|
你能帮帮忙吗?这是我的perl代码
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);
答案 0 :(得分:1)
sub trim(_) { my ($s) = @_; $s =~ s/^\s+//; $s =~ s/\s+\z//; $s }
或者在Perl 5.14 +中,
sub trim(_) { $_[0] =~ s/^\s+//r =~ s/\s+\z//r }
然后使用:
my $Final = join '|', map trim, @$row;
答案 1 :(得分:1)
使用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"
});
答案 2 :(得分:0)
尝试这样做:
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);