清除大多数HTML标记,但格式化ASCII表格

时间:2013-06-04 13:55:57

标签: html perl html-table sanitize

我将下载的HTML传递给STDIN,然后擦除除了表标记之外的所有标签。我想基于table,tr和td的剩余实例渲染表,以便表格以“\ t”或“|”结尾分隔。 ASCII格式的表也可以工作。以下是我到目前为止所做的,但它没有完成任务:

#!/usr/bin/perl -ws
use HTML::Scrubber;
use HTML::Entities qw(decode_entities);
use Text::Unidecode qw(unidecode);

my $HTMLinput = do {local $/; <STDIN>};

my $scrubber = HTML::Scrubber->new( allow => [ qw[ table tr td ] ] );

#this prints the text from the page, but without formatting tables in ASCII:
#print $scrubber->scrub($HTMLinput);

my $scrubber2 = $scrubber->scrub($HTMLinput);

#was hoping this would remove transform table, tr, and td-tagged content
#into ASCII-formatted tables, but it doesn't work:
print unidecode(decode_entities($scrubber2)), "\n";

#test page: http://www.w3schools.com/html/html_tables.asp
#curl http://www.w3schools.com/html/html_tables.asp | html.table.parser.pl 

2 个答案:

答案 0 :(得分:1)

这是我到达的解决方案,部分归功于用户名tjd:

#!/usr/bin/perl -ws
use HTML::Scrubber;

my $HTMLinput = do {local $/; <STDIN>};
my $scrubber = HTML::Scrubber->new( allow => [ qw[ table tr td ] ] );
print $scrubber->scrub($HTMLinput);

#test page: http://www.w3schools.com/html/html_tables.asp
#links -dump http://www.w3schools.com/html/html_tables.asp | html.table.parser.pl 

#needed: "links" program for bash (sudo yum install links)
#http://www.jikos.cz/~mikulas/links/

答案 1 :(得分:0)

我不想重新发明在文本中创建表格的轮子。我要么将linksw3m之类的文本浏览器的输出传输到文件/标准输出,要么使用像Text::Table这样的模块来完成繁重的工作。