在 Perl 中解析 HTML 表

Parsing a HTML table in Perl

提问人:user1675386 提问时间:4/24/2015 最后编辑:Brian Tompsett - 汤莱恩user1675386 更新时间:5/19/2017 访问量:1764

问:

我正在尝试解析以下HTML表:

<table cellspacing="0" border="1" width="100%">
 <tr bgcolor="#d0d0d0">
  <th style="COLOR: #ff6600">number</th>
  <th style="COLOR: #ff6600">id</th>
  <th style="COLOR: #ff6600">result</th>
  <th style="COLOR: #ff6600">reason</th>
 </tr>
 <tr>
  <td>1027</td>
  <td><a href="<url>">21cs_337</a></td>
  <td>0</td>
  <td>catch-all caught </td>
  <td>reason</td>  
 </tr>
 <tr>
  <td>10288</td>
  <td><a href="<url>">21cs_437</a></td>
  <td>0</td>
  <td>badfetch</td>
  <td>reason</td>
 </tr>
</table>

我正在尝试从我的 perl 脚本中读取此 html 文件中的值。我为此使用 HTML::TagParser,并且能够获取每行的值:

$table_old = ($html_old->getElementsByTagName("tr"))[1]->innerText();

但是我想获取每列(每行)的值。我试过了这个:

$table_new = ($html_new->getElementsByTagName("tr"))[1];  
my $temp  = ($table_new->getElementsByTagName("td"))[2]->innerText();

这是行不通的,关于如何有效解析列元素的任何建议。

html perl 表格 html解析

评论

0赞 Kim Ryan 4/24/2015
这个模块可能更合适:search.cpan.org/~djerius/HTML-TableParser-0.40/lib/HTML/...
0赞 user1675386 4/24/2015
谢谢,但我已经在我的脚本中使用标签解析器进行大多数其他解析,所以正在考虑继续使用相同的解析器。也研究表解析器,但任何带有标签解析器的建议都可能更好。
0赞 Sinan Ünür 4/24/2015
HTML::TableExtract 非常非常有用。

答:

0赞 xxfelixxx 4/24/2015 #1

您需要使用 subTree。

#!/usr/bin/env perl
use warnings;
use strict;
use HTML::TagParser;

my $html = HTML::TagParser->new( 'foo.html' ); # Change this to your file

my $nrow = 0;
for my $tr ( $html->getElementsByTagName("tr" ) ) {
    my $ncol = 0;
    for my $td ( $tr->subTree->getElementsByTagName("td") ) {
        print "Row [$nrow], Col [" . $ncol++ . "], Value [" . $td->innerText() . "]\n";
    }
    $nrow++;
}

生成以下输出(请注意,省略了第 1 行):

Row [1], Col [0], Value [1027]
Row [1], Col [1], Value [21cs_337]
Row [1], Col [2], Value [0]
Row [1], Col [3], Value [catch-all caught]
Row [1], Col [4], Value [reason]
Row [2], Col [0], Value [10288]
Row [2], Col [1], Value [21cs_437]
Row [2], Col [2], Value [0]
Row [2], Col [3], Value [badfetch]
Row [2], Col [4], Value [reason]

评论

0赞 user1675386 4/25/2015
谢谢,这有效,但仍然对我没有帮助,因为我使用的是支持 HTML-TagParser-0.16 (search.cpan.org/~kawasaki/HTML-TagParser-0.16/lib/HTML/...) 的 perl v5.6.1,并且此版本不支持 HTML::TagParser::Element(subTree 需要)
1赞 Dave Cross 4/27/2015
最好的建议是停止使用14年前不受支持的Perl版本。是什么阻止您使用更新的版本?