我读了很多问题和许多答案,但我找不到我的问题的直接答案。所有答案要么非常笼统,要么与我想做的不同。到目前为止,我需要使用HTML :: TableExtract或HTML :: TreeBuilder :: XPath,但我无法真正使用它们来存储值。我可以以某种方式获取表行值并使用Dumper显示它们。
这样的事情:
foreach my $ts ($tree->table_states) {
foreach my $row ($ts->rows) {
push (@fir , (Dumper $row));
} }
print @sec;
但这并不是我正在寻找的东西。我将添加我想要存储值的HTML表的结构:
<table><caption><b>Table 1 </b>bla bla bla</caption>
<tbody>
<tr>
<th ><p>Foo</p>
</th>
<td ><p>Bar</p>
</td>
</tr>
<tr>
<th ><p>Foo-1</p>
</th>
<td ><p>Bar-1</p>
</td>
</tr>
<tr>
<th ><p>Formula</p>
</th>
<td><p>Formula1-1</p>
<p>Formula1-2</p>
<p>Formula1-3</p>
<p>Formula1-4</p>
<p>Formula1-5</p>
</td>
</tr>
<tr>
<th><p>Foo-2</p>
</th>
<td ><p>Bar-2</p>
</td>
</tr>
<tr>
<th ><p>Foo-3</p>
</th>
<td ><p>Bar-3</p>
<p>Bar-3-1</p>
</td>
</tr>
</tbody>
</table>
如果我可以将行值一起存储在一起会很方便。
预期输出类似于数组,其值为: (Foo,Bar,Foo-1,Bar-1,Formula,Formula-1 Formula-2 Formula-3 Formula-4 Formula-5,....) 对我来说重要的是学习如何存储每个标签的值以及如何在标签树中移动。
答案 0 :(得分:3)
学习XPath和DOM操作。
use strictures;
use HTML::TreeBuilder::XPath qw();
my $dom = HTML::TreeBuilder::XPath->new;
$dom->parse_file('10280979.html');
my %extract;
@extract{$dom->findnodes_as_strings('//th')} =
map {[$_->findvalues('p')]} $dom->findnodes('//td');
__END__
# %extract = (
# Foo => [qw(Bar)],
# 'Foo-1' => [qw(Bar-1)],
# 'Foo-2' => [qw(Bar-2)],
# 'Foo-3' => [qw(Bar-3 Bar-3-1)],
# Formula => [qw(Formula1-1 Formula1-2 Formula1-3 Formula1-4 Formula1-5)],
# )