代码之家  ›  专栏  ›  技术社区  ›  Victor Sanchez

如何根据Perl中的类替换一些HTML标记?

  •  1
  • Victor Sanchez  · 技术社区  · 16 年前

    我需要用Perl替换HTML中的一些标记:

    我有这个:

    <span class="a">text</span><span class="a">text</span><span id="b">text</span>
    

    我需要这个,在哪里 span 带标签 class=a 改为 b 标签代替:

    <b>text</b><b>text</b><span id="b">text</span>
    

    我试着用 HTML::Manipulator 但没有成功。

    3 回复  |  直到 16 年前
        1
  •  7
  •   daotoad    16 年前

    以下是如何使用html::treebuilder:

    use strict;
    use warnings;
    use HTML::TreeBuilder;
    
    my $html_string = '<span class="a">text</span><span class="a">text</span><span id="b">text</span>';    
    
    my $root = HTML::TreeBuilder->new_from_content($html_string);
    $root->elementify;  # Make $root into an HTML::Element object;
    
    
    for my $e ( $root->look_down( _tag => 'span', class => 'a' ) ) {
        $e->tag( 'b' );
        $e->attr( class => undef );
    } 
    
    print $root->as_HTML;
    
        2
  •  2
  •   Greg Bacon    16 年前

    使用的示例 HTML::Parser :

    #! /usr/bin/perl
    
    use warnings;
    use strict;
    use HTML::Parser;
    my $p = HTML::Parser->new( api_version => 3,
      start_h => [\&start, "tagname, attr, text, skipped_text"],
      end_h   => [\&end,   "tagname,       text, skipped_text"],
    );
    $p->parse_file(\*DATA);
    
    my @switch_span_end;
    sub start {
      my($tag,$attr,$text,$skipped) = @_;
      print $skipped;
      unless ($tag eq 'span' && ($attr->{class}||"") eq "a") {
        print $text;
        return;
      }
      push @switch_span_end => 1;
      print "<b>";
    }
    
    sub end {
      my($tag,$text,$skipped) = @_;
      print $skipped;
      if (@switch_span_end && $tag eq "span") {
        print "</b>";
        pop @switch_span_end;
      }
      else {
        print $text;
      }
    }
    __DATA__
    <span class="a">text</span><span class="a">text</span><span id="b">text</span>
    

    输出:

    <b>text</b><b>text</b><span id="b">text</span>
        3
  •  -1
  •   David M    16 年前

    我会用 HTML::Tree 要解析HTML,然后找到具有您想要的属性的节点,更改它们,然后输出新的树,这将具有您想要的更改。