如何从Perl中的HTML表中提取数据?

时间:2009-10-30 17:36:35

标签: html perl parsing

可能重复:
Can you provide an example of parsing HTML with your favorite parser?
How can I extract content from HTML files using Perl?


我正在尝试在Perl中使用正则表达式来解析具有以下结构的表。第一行如下:

<tr class="Highlight"><td>Time Played</a></td><td></td><td>Artist</td><td width="1%"></td><td>Title</td><td>Label</td></tr>

在这里,我希望取出“Time Played”,“Artist”,“Title”和“Label”,并将它们打印到输出文件中。

任何帮助都会有很大帮助!

好的抱歉...我尝试了许多正则表达式,例如:

$lines =~ / (<td>) /
       OR
$lines =~ / <td>(.*)< /
       OR
$lines =~ / >(.*)< /

我目前的计划如下:

#!perl -w

open INPUT_FILE, "<", "FIRST_LINE_OF_OUTPUT.txt" or die $!;

open OUTPUT_FILE, ">>", "PLAYLIST_TABLE.txt" or die $!;

my $lines = join '', <INPUT_FILE>;

print "Hello 2\n";

if ($lines =~ / (\S.*\S) /) {
print "this is 1: \n";
print $1;
    if ($lines =~ / <td>(.*)< / ) {
    print "this is the 2nd 1: \n";
    print $1;
    print "the word was: $1.\n";
    $Time = $1;
    print $Time;
    print OUTPUT_FILE $Time;
    } else {
    print "2ND IF FAILED\n";
    }
} else { 
print "THIS FAILED\n";
}

close(INPUT_FILE);
close(OUTPUT_FILE);

3 个答案:

答案 0 :(得分:16)

答案 1 :(得分:11)

使用HTML::TableExtract。真。

#!/usr/bin/perl

use strict;
use warnings;

use HTML::TableExtract;
use LWP::Simple;

my $file = 'Table3.htm';
unless ( -e $file ) {
    my $rc = getstore(
        'http://www.ntsb.gov/aviation/Table3.htm',
        $file);
    die "Failed to download document\n" unless $rc == 200;
}

my @headers = qw( Year Fatalities );

my $te = HTML::TableExtract->new(
    headers => \@headers,
    attribs => { id => 'myTable' },
);

$te->parse_file($file);

my ($table) = $te->tables;

print join("\t", @headers), "\n";

for my $row ($te->rows ) {
    print join("\t", @$row), "\n";
}

这就是我在“特定任务”HTML解析器的另一篇文章中的意思。

你可以节省大量的时间,将精力放在阅读一些文档上,而不是将正则表达式放在墙上,看看是否有任何问题。

答案 2 :(得分:0)

这很简单:

my $html = '<tr class="Highlight"><td>Time Played</a></td><td></td><td>Artist</td><td width="1%"></td><td>Title</td><td>Label</td></tr>';
my @stuff = $html =~ />([^<]+)</g;
print join (", ", @stuff), "\n";

如果您想尝试运行,请参阅http://codepad.org/qz9d5Bro