1
#!/usr/bin/perl
use strict;
use warnings;
my $html = q|
    <html>
    <head>
    <style>
    .classname{
        color: red;
    }
    </style>
    </head>
    <body>
    classname will have a color property.
    </body>
    </html>
|;
$html=~s/classname/NEW/g;
print $html;

classname这在两个地方都替换了。如何将替换仅限于内容<body>?我希望看到它使用HTML::Parseror完成HTML::TreeBuilder

4

1 回答 1

3

我相信这可以满足您的要求,使用 HTML::TreeBuilder 在 body 元素的所有子元素上用您的正则表达式替换类名。

我在输入中添加了另一个虚拟 div,以确保它被正确处理。

#!/usr/bin/perl
use strict;
use warnings;

use HTML::TreeBuilder;

my $html = q|
    <html>
    <head>
    <style>
    .classname{
        color: red;
    }
    </style>
    </head>
    <body>
    classname will have a color property.
    <div>more text with classname in it</div>
    </body>
    </html>
|;

my $tree = HTML::TreeBuilder->new_from_content($html);

replace_text( $tree->find_by_tag_name("body") );

print $tree->as_HTML."\n";

sub replace_text {

    my $html_element = shift;

    for my $el ( $html_element->content_refs_list ){

    if ( ref( $$el ) ){
        replace_text( $$el );
        next;
    }

    $$el =~ s /classname/NEW/g;

    }

    return $html_element;

}
于 2014-11-26T00:28:31.577 回答