我遇到HTML::TreeBuilder
的问题;它在输出中显示mojibake /怪异字符。
use strict;
use WWW::Curl::Easy;
use HTML::TreeBuilder;
my $cookie_file ='/tmp/pcook';
my $curl = new WWW::Curl::Easy;
my $response_body;
my $charset = 'utf-8';
$DocOffline::charset = undef;
$curl->setopt (CURLOPT_URL, 'http://www.breitbart.com/article.php?id=D9G7CR5O0&show_article=1');
$curl->setopt ( CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.9 (KHTML, like Gecko) Chrome/6.0.400.0 Safari/533.9');
$curl->setopt ( CURLOPT_HEADER, 0);
$curl->setopt ( CURLOPT_FOLLOWLOCATION, 1);
$curl->setopt ( CURLOPT_AUTOREFERER, 1);
$curl->setopt ( CURLOPT_SSL_VERIFYPEER, 0);
$curl->setopt ( CURLOPT_COOKIEFILE, $cookie_file);
$curl->setopt ( CURLOPT_COOKIEJAR, $cookie_file);
$curl->setopt ( CURLOPT_HEADERFUNCTION, \&headerCallback );
open (my $fileb, ">", \$response_body);
$curl->setopt(CURLOPT_WRITEDATA,$fileb);
my $retcode = $curl->perform;
if ($retcode == 0) {
my $dom_tree = HTML::TreeBuilder->new();
$dom_tree->ignore_elements(qw(script style));
$dom_tree->utf8_mode(1);
$dom_tree->parse($response_body);
$dom_tree->eof();
print $dom_tree->as_HTML('<>&', ' ', {});
}
sub headerCallback {
my($data, $pointer) = @_;
$data =~ m/Content-Type:\s*.*;\s*charset=(.*)/;
if ($1) {
$charset = $1;
$charset =~ s/[^a-zA-Z0-9_\-]*//g;
}
return length($data);
}
答案 0 :(得分:2)
你整整一天都没有得到答案,因为你的代码在形状和内容方面都很混乱,你甚至都懒得在你的整个程序中减少测试用例。 MvanGeest也在该问题的评论中产生了误诊。
问题是编写Breitbart的CMS的人是无能为力的,他们插入NCR —
(这是一个不可打印的角色,甚至可能是一个无效的角色),他们应该简单地插入角色{ {1}}(—
);毕竟,文档编码声明为UTF-8。 (可以清楚地看到编码应该是Windows-1252,其中分配了代码点151(十进制)。)
你可以通过明确的解码/编码步骤解决他们的无能。
U+2014 EM DASH