【问题标题】:Perl HTML::Parser - search a for a specific string in a parsed filePerl HTML::Parser - 在已解析文件中搜索特定字符串
【发布时间】:2014-05-22 17:31:03
【问题描述】:

我是 HTML::Parser 的 Perl 新手。

我正在尝试解析网页,然后搜索特定字符串,例如 passfail。我该怎么办呢。

由于框架问题,我必须使用 HTML::Parser 基础库而不是其他模块。

代码片段

#!/usr/bin/perl
use strict;

# define the subclass
package IdentityParse;

package HTMLStrip;
use base "HTML::Parser";

sub text {
  my ($self, $text) = @_;

  # just print out the original text
  print $text;
}

sub comment {
  my ($self, $comment) = @_;

  # print out original text with comment marker
  #print "hey hey";
}

sub end {
  my ($self, $tag, $origtext) = @_;

  # print out original text
  #print $origtext;
}

#my $p = new IdentityParse;
my $p    = new HTMLStrip;
my @file = $p->parse_file("testcase1.html");

if ($p->parse_file("testcase1.html") =~ "PASS") {
  print " The test passed \n";
}
else {
  print "\nthe test failed \n";
}

【问题讨论】:

    标签: perl html-parsing


    【解决方案1】:

    如果您只想从 XML 中去除标签,只留下文本内容,那么您自己做的事情就太难了。您所需要的只是一个文本处理程序子例程,它将每个文本节点连接到一个全局标量。

    看起来像这样。我编辑了最后一个字符串,将所有空格和换行符更改为一个空格;否则从布局缩进那里会有 很多 的空间。

    use strict;
    use warnings;
    
    use HTML::Parser;
    
    my $parser = HTML::Parser->new( text_h => [\&text, 'dtext'] );
    
    my $text_content;
    
    sub text {
      $text_content .= shift;
    }
    
    $parser->parse_file(*DATA);
    $text_content =~ s/\s+/ /g;
    print $text_content;
    
    __DATA__
    <root>
      <item>
        Item 1
        status failed
      </item>
      <item>
        Item 2
        status passed
      </item>
      <item>
        Item 3
        status failed
      </item>
    </root>
    

    输出

     Item 1 status failed Item 2 status passed Item 3 status failed  
    

    【讨论】:

    • 深入挖掘问题并提供帮助的方法。我已经完成了我的 HTML::Parser 日子,只是不想再回去了 :)
    猜你喜欢
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多