views:

103

answers:

1

I am having a problem with HTML::TreeBuilder; it shows mojibake/weird characters in the output. Please help me. Thanks in advance.

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);
}
+1  A: 

You did not get an answer for a whole day because your code's a mess both in shape and content and you didn't even bother to make a reduced test case out of your whole program. MvanGeest also produced a misdiagnosis in the comment attached to the question.

The problem is that the people who wrote Breitbart's CMS are clueless, they insert the NCR &#151; (which is a non-printable character, and perhaps even an invalid character) when they should have simply inserted the character (U+2014 EM DASH); after all, the document encoding is declared UTF-8. (One can clearly see that the encoding was supposed to be Windows-1252, where the codepoint 151 (decimal) is allocated.)

You can work around the incompetence on their part with an explicit decoding/encoding step.

use Encode qw(encode decode);
⋮
my $string_representation = $dom_tree->as_HTML('<>&', ' ', {});
my $octets = encode('UTF-8', decode('Windows-1252', $string_representation);
⋮
# send the correct Content-Type header in your CGI program before printing the HTTP body
print $octets;
daxim