4

可能重复:
您会推荐哪个 CPAN 模块将 HTML 转换为纯文本?

问题:

  • 是否有一个渲染 HTML的模块,专门用于收集文本,同时遵守字体样式标签,例如<tt><b><i>等和break-line <br>,类似于Lynx

例如

# cat test.html

<body>  
<div id="foo" class="blah">  
<tt>test<br>
<b>test</b><br>
whatever<br>
test</tt>
</div>
</body>

# lynx.exe --dump test.html

test
test
whatever
test

注意:第二行应该是粗体。

4

3 回答 3

11

Lynx 是一个大程序,它的 html 渲染将非常重要。

这个怎么样:

my $lynx = '/path/to/lynx';
my $html = [ html here ];
my $txt = `$lynx --dump --width 9999 -stdin <<EOF\n$html\nEOF\n`;
于 2009-12-22T10:12:10.147 回答
6

转到search.cpan.org并搜索HTML 文本,这将为您提供许多选项以满足您的特定需求。 HTML::FormatText是一个很好的基线,然后扩展到它的特定变体,例如HTML::FormatText::WithLinks如果您想将链接保留为脚注。

于 2009-12-22T12:02:28.963 回答
2

我在 Windows 上,所以我无法完全测试它,但您可以调整HTML::Parser附带的htext

#!/usr/bin/perl

use strict; use warnings;

use HTML::Parser;
use Term::ANSIColor;

use HTML::Parser 3.00 ();

my %inside;

sub tag {
   my($tag, $num) = @_;
   $inside{$tag} += $num;
   print " ";  # not for all tags
}

sub text {
    return if $inside{script} || $inside{style};
    my $esc = 1;
    if ( $inside{b} or $inside{strong} ) {
        print color 'blue';
    }
    elsif ( $inside{i} or $inside{em} ) {
        print color 'yellow';
    }
    else {
        $esc = 0;
    }
    print $_[0];
    print color 'reset' if $esc;
}

HTML::Parser->new(api_version => 3,
    handlers => [
        start => [\&tag, "tagname, '+1'"],
        end   => [\&tag, "tagname, '-1'"],
        text  => [\&text, "dtext"],
    ],
    marked_sections => 1,
)->parse_file(shift) || die "Can't open file: $!\n";;
于 2009-12-22T14:04:58.173 回答