HTML :: TokeParser - 在标签之间和之后查找文本

时间:2014-02-17 09:44:57

标签: html perl tags

我正在尝试使用以下代码从HTML页面中提取以下文本,但我的代码失败了..

预算 - $ 25,000,00

总收入(全球) - $ 58,500,00

#!/usr/bin/perl
use HTML::TokeParser;

my $content = <<HTML;
<h5>Budget</h5>
$25,000,000 (estimated)<br/>
<br/>

<h5>Opening Weekend</h5>
$727,327 (USA) (<a href="/date/09-25/">25 September</a> <a href="/year/1994/">1994</a>) (33 Screens)<br/>
<br/>

<h5>Gross</h5>
$28,341,469 (USA) (<a href="/date/08-05/">5 August</a> <a href="/year/2012/">2012</a>)<br/>&#163;2,344,349 (UK) (<a href="/date/05-18/">18 May</a> <a href="/year/1995/">1995</a>)<br/>&#163;1,732,123 (UK) (<a href="/date/04-16/">16 April</a> <a href="/year/1995/">1995</a>)<br/>$58,500,000 (Worldwide)<br/>$555,480 (Belgium)<br/>ESP 637,291,985 (Spain)<br/>
<br/>

<h5>Admissions</h5>
82,890 (Belgium)<br/>163,594 (France) (<a href="/date/03-28/">28 March</a> <a href="/year/1995/">1995</a>)<br/>410,811 (Germany) (<a href="/date/12-31/">31 December</a> <a href="/year/1995/">1995</a>)<br/>1,245,604 (Spain)<br/>
<br/>

<h5>Filming Dates</h5>
<a href="/date/06-16/">16 June</a> <a href="/year/1993/">1993</a>&nbsp;-&nbsp;<a href="/date/09-10/">10 September</a> <a href="/year/1993/">1993</a><br/>
<br/>
HTML

my $description = "";
my $tp = HTML::TokeParser->new(\$content) || die "Can't open: $!";

while (my $token = $tp->get_tag("h5")) {
    my $text = $parser->get_text();
    last if $text =~ /budget/i;
}

2 个答案:

答案 0 :(得分:0)

也可以使用正则表达式。

while ( $content =~ s!<h5[^>]*>\s*(.+?)\s*</h5>\s*(\S+)(.*?)<br[^>]*>!!is ){
  my $h5text = $1;
  my $amount = $2;
  my $rest   = $3;
  if ($h5text =~ m!(Budget|Gross)!is){
     print "$h5text\t$amount\n";
  }
}

答案 1 :(得分:0)

这可能不是最优雅的解决方案,但它确实有效。

while (my $token = $tp->get_tag("h5")) {
    my $heading = $tp->get_text();
    $tp->get_tag("/h5");
    my $amount = $tp->get_trimmed_text =~ s/[^\d,\$]//gr;
    next unless $amount =~ m/\d/;
    say qq{$heading - $amount};
}

根据HTML::TokeParser docs,您可以使用get_tag获取开始和结束标记。在开始<h5>之后,我们可以抓住标题,然后转到结束</h5>。那个背后有一个文本节点,它包含货币价值。