我正在编写一个Perl脚本,从许多不同的网站获取各种HTML文档,并试图从中提取数据。我在解码那些文件时遇到了问题。
我知道如何从元标记中读取charset
(如果有的话),以及如何从HTTP标头中读取此信息(如果可用)。
结果可以是:
- utf - 8
- iso - 8859 - 1
- Shift_JIS windows - 1252
和更多
有了这些知识,我想在我的Perl脚本中解码文档#!/usr/bin/perl -w
use strict;
use LWP::UserAgent;
use Encode;
use Encode::JP;
# Maybe also use other extensions for Encode
my $ua = LWP::UserAgent->new;
my $response = $ua->get($url); #$url is the documents URL
if ( $response->is_success ) {
my $charset = getcharset($response);
# getcharset is a self-written subroutine that reads the charset
# from a meta tag or from the HTTP header (not shown in this example)
# Now I know the documents charset and want to find its encoding:
my $encoding = 'utf-8'; # default
if ($charset eq 'utf-8') {
$encoding = 'utf-8'; # Here $encoding and $charset are equal
}
elsif ( $charset eq 'Shift_JIS' ) {
$encoding = 'shiftjis'; #here $encoding and $charset are not equal
}
elsif ( $charset eq 'windows-1252' ) {
# Here I have no idea what $encoding should be, since there is no
# encoding in the documentation that contains the string "windows"
}
elsif ( $charset eq 'any other character set' ) {
$encoding = ???
}
my $content = decode($encoding, $result->content);
# Extract data from $content
}
但是我没有找到一些存在于野外的字符集的正确编码。
对于HTML文档,您所需要的只是
my $content = $response->decoded_content();
它将同时使用HTTP头中字符集属性的值,并根据需要使用META元素。
但是我找不到一些字符集的正确编码
Encode并不支持所有已经存在的编码,但是我很惊讶你遇到了一个它无法解码的HTML页面。这可能只是一个创建别名的案例,但您没有提供任何细节让我们帮助您。
参见Encode::Supported。基本上,大多数编码都可以工作™
binmode STDIN, ':encoding(Shift_JIS)';
binmode STDIN, ':encoding(windows-1252)';