【问题标题】:How can I render HTML as text using Perl as Lynx does? [duplicate]如何像 Lynx 那样使用 Perl 将 HTML 呈现为文本? [复制]
【发布时间】:2009-12-27 06:46:58
【问题描述】:

可能重复:
Which CPAN module would you recommend for turning HTML into plain text?

问题:

  • 是否有一个模块可以渲染 HTML,专门用于收集文本,同时遵守 字体样式标签,例如<tt><b>、@ 987654326@ 等和 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

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

【问题讨论】:

标签: html perl render


【解决方案1】:

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

这个怎么样:

my $lynx = '/path/to/lynx';
my $html = [ html here ];
my $txt = `$lynx --dump --width 9999 -stdin <<EOF\n$html\nEOF\n`;

【讨论】:

  • +1。想提出相同的答案。
  • 不幸的是,这可能只是不得不做的事情。
  • 第 3 行不应该包含 $lynx 而不是 lynx 吗?否则,/path/to/lynx 将被忽略。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    #!/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";;
    

    【讨论】:

      猜你喜欢
      • 2012-04-08
      • 1970-01-01
      • 2011-01-07
      • 1970-01-01
      • 2023-02-03
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多