2011-04-26 33 views
0

我想寫一個Perl腳本來獲取網頁的html內容,然後刮掉表格的內容。確切的頁面是:Perl屏幕上的數據擦除

http://djbpmstudio.com/Default.aspx?Page=album&id=1

到目前爲止,我可以使用下面的代碼以正則表達式的藝術家,專輯,流派等,以及在表中的第一項:

use LWP::Simple; 

$url = "http://djbpmstudio.com/Default.aspx?Page=album&id=1"; 
my $mystring = get($url) or die "Error fetching source page."; 
$mystring =~ s/[\r\n]/ /g;  #remove line breaks from HTML 
$mystring =~ s/(>)\s+(<)/$1$2/g; #Remove white space between html tags 
#print $mystring; 

if($mystring =~ m{</table><h1>(.*?) - (.*?) - (.*?)</h1>}) { 
    #Get Artist name and print 
    print "Artist: $1\n"; 
    print "Album: $2\n"; 
    print "Genre: $3\n\n"; 

    if($mystring =~ m{</tr><tr class="row-(.*?)"><td>(.*?)</td><td align="right">(.*?)</td></tr>}) { 
     #Get Songname and BPM and print 
     #print "$1\t"; 
     print "$2\t"; 
     print "$3\n"; 
    } 
} 

在嵌套IF,類在「row-a」和「row-b」之間交替。

我不知道如何下單,並獲得所有的歌曲名稱和每個BPM。我還想將歌名和BPM放入一個數組中供以後處理。

謝謝。

+0

[除XHTML自包含標籤的正則表達式匹配開放標籤]的可能重複(http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – outis 2011-04-26 01:15:15

回答

4

使用regular expressions to process HTML幾乎總是一個壞主意。

不要壞。

使用理解HTML數據的模塊來處理HTML數據。

#!/usr/bin/perl 
use warnings; 
use strict; 
use LWP::Simple; 
use HTML::TableExtract; 

my $html = get 'http://djbpmstudio.com/Default.aspx?Page=album&id=1'; 

my $te = new HTML::TableExtract(headers => ['Track Name', 'BPM']); 
$te->parse($html); 
foreach my $ts ($te->table_states) { 
    foreach my $row ($ts->rows) { 
     next unless $row->[0] =~ /\w/; # skip garbage rows 
     printf "%-20s ==> %.2f\n", $row->[0], $row->[1]; 
    } 
} 
+0

完善!謝謝。 – CrzySheeit 2011-04-26 23:06:26