【发布时间】:2009-11-10 04:54:48
【问题描述】:
这是我第一次使用 Stack Overflow,所以如果我做错了什么,请告诉我。
我目前正在尝试编写一个“scraper”,因为没有更好的术语,它将提取 html 并将某些内联 CSS 样式替换为 HTML 对应样式。例如,我有这个 HTML:
<p style="text-align:center"><span style="font-weight:bold;font-style:italic;">Some random text here. What's here doesn't matter so much as what needs to happen around it.</span></p>
我希望能够将font-weight:bold 替换为<b>,将font-style:italic 替换为<i>,将text-align:center 替换为<center>。之后,我将使用正则表达式删除所有非基本 HTML 标记和任何属性。 KISS 绝对适用于此。
我已经阅读了这个问题:Convert CSS Style Attributes to HTML Attributes using Perl 和其他一些关于使用 HTML::TreeBuilder 和其他模块(如 HTML::TokeParser)的问题,但到目前为止我自己都被绊倒了。
我是 Perl 的新手,但对一般的编码并不陌生。道理是一样的。
这是我目前所拥有的:
#!/usr/bin/perl
use warnings;
use strict;
use HTML::TreeBuilder;
my $newcont = ""; #Has to be set to something? I've seen other scripts where it doesn't...this is confusing.
my $html = <<HTML;
<p style="text-align:center"><span style="font-weight:bold;font-style:italic;">Some random text here. What's here doesn't matter so much as what needs to happen around it.</span> And sometimes not all the text is styled the same.</p>
HTML
my $tb = HTML::TreeBuilder->new_from_content($html);
my @spans = $tb->look_down(_tag => q{span}) or die qq{look_down for tag failed: $!\n};
for my $span (@spans){
#What next?? A print gives HASH, not really workable. Split doesn't seem to work...I've never felt like such a noobie coder before.
}
print $tb->as_HTML;
希望有人可以帮助我,告诉我我可能做错了什么,等等。我真的很好奇还有其他可能的方法可以做到这一点。或者,如果以前曾经做过。
另外,如果有人可以通过建议我应该使用哪些标签来提供帮助,那就太好了。我唯一知道肯定会使用的是 perl。
【问题讨论】:
-
你为什么不在 perl 中使用简单的搜索和替换
perl -pi -e 's/find/replace/g' file_name -
您可以在命令行上执行 3 次替换 3 次。
-
@John - 因为问题比简单的搜索和替换正则表达式更复杂。
-
那是我的第一直觉,但是您将如何将新的 HTML 标签包裹在内容周围?完成后的 HTML /should/ 如下所示:
<center><p><i><b>Some random text here. What's here doesn't matter so much as what needs to happen around it.</b></i> And sometimes not all the text is styled the same.</p></center> -
你真正需要的是一个好的 DOM 解析器。
HTML::DOM似乎有些不成熟。
标签: perl