【发布时间】:2013-06-23 20:35:05
【问题描述】:
我需要扫描 html 片段以查找文本中的某些字符串(不在元素属性中)并用 <span></span> 包装这些匹配的字符串。这是一个带有输出的示例尝试:
use v5.10;
use Mojo::DOM;
my $body = qq|
<div>
<p>Boring Text:</p>
<p>
Highlight Cool whenever we see it.
but not <a href="/Cool.html">here</a>.
<code>
sub Cool {
print "Foo\n";
}
</code>
And here is more Cool.
</p>
</div>
|;
my $dom = Mojo::DOM->new($body);
foreach my $e ($dom->find('*')->each) {
my $text = $e->text;
say "e text is: $text ";
if ($text =~ /Cool/) {
(my $newtext = $text ) =~ s/Cool/<span class="fun">Cool<\/span>/g;
$e->replace_content($newtext);
}
}
say $dom->root;
输出:
e text is:
e text is: Boring Text:
e text is: Highlight Cool whenever we see it. but not. And here is more Cool.
e text is: here
e text is: sub Cool { print "Foo "; }
<div>
<p>Boring Text:</p>
<p>Highlight <span class="fun">Cool</span> whenever we see it. but not. And here is more <span class="fun">Cool</span>.</p>
</div>
关闭,但我真正想看到的是以下内容:
<div>
<p>Boring Text:</p>
<p>Highlight <span class="fun">Cool</span> whenever we see it. but not <a href="/Cool.html">here</a>.
<code>
sub <span class="fun">Cool<span> {
print "Foo\n";
}
</code>
And here is more <span class="fun">Cool</span>.</p>
</div>
任何帮助/指针将不胜感激。 谢谢, 托德
【问题讨论】:
-
由于
Mojo::DOM对 CSS 选择器的限制,很难做到这一点。您是否仅限于使用此模块,还是可以转到XML::Twig或其他允许 XPath 访问数据的模块? -
没有限制,我将开始研究 XML::Twig。谢谢。
标签: perl mojolicious