osullic has asked for the wisdom of the Perl Monks concerning the following question:
I'm trying to use HTML::TreeBuilder to parse and extract certain text from a group of HTML files. The HTML files are encoded as UTF-8. I want my output (printed to a text file) to be encoded as windows-1252.
Testing with a simple Perl script and just one input file, my output is not as I expect. Here is my code:
use HTML::TreeBuilder; $infile = "test.html"; $outfile = "test-treebuilder-output.txt"; open($fh, "<:utf8", $infile); open(OUT, ">$outfile"); binmode OUT, ':cp1252'; $tree = HTML::TreeBuilder->new(); $tree->parse_file($fh); $h1Element = $tree->look_down("_tag", "h1"); $h1TrimmedText = $h1Element->as_trimmed_text(); print OUT "$h1TrimmedText\n"; $tree->delete(); close(OUT); close($fh);
The test.html file I'm using only contains:
<html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf +-8"> <title>test</title> </head> <body> <h1>Décembre</h1> </body> </html>
My output text file contains just the word Décembre, but the file appears to be encoded as UTF-8. (Force-reading the file as ISO-8859-1 causes the accented character to display as LATIN CAPITAL LETTER A WITH TILDE followed by COPYRIGHT SIGN.)
However, I have another short test script, which doesn't use HTML::TreeBuilder, but just reads all lines from the input file and prints them to the output file. The two scripts are not materially different in how they handle the character encodings, but the output text file from this second script seems to be correctly encoded as windows-1252. Here is the second script:
$infile = "test.html"; $outfile = "test-print-output.txt"; open($fh, "<:utf8", $infile); open(OUT, ">$outfile"); binmode OUT, ':cp1252'; @infile = <$fh>; foreach $line (@infile) { print OUT $line; } close(OUT); close($fh);
I'd appreciate if someone could explain why I'm not getting the text output from my HTML::TreeBuilder script correctly encoded as windows-1252.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: HTML::TreeBuilder, UTF-8 input, windows-1252 output
by Eliya (Vicar) on Jan 05, 2012 at 17:14 UTC | |
|
Re: HTML::TreeBuilder, UTF-8 input, windows-1252 output
by ikegami (Patriarch) on Jan 05, 2012 at 19:18 UTC |