创建一个 perl 脚本(W10 上的 Strawberry Perl v5.32.0)来下载我的 Google 日历。 Google 为“basic.ics”文件提供了“私有(private)”(无需登录)网址。
在我的浏览器 (firefox) 中打开这个 url 时,会弹出一个窗口来下载这个“basic.ics”文件。保存时,文件采用 UTF-8 编码。
在我的脚本中,我使用 WWW::Mechanize get ":content_file"
下载文件:
#!/usr/bin/perl -w
use WWW::Mechanize;
# URL modified for obvious reasons ...
my $url = 'https://calendar.google.com/path-to-private-calendar-file/basic.ics';
my $local_file_name = 'Calendar.ics';
my $mech = WWW::Mechanize->new();
$mech->get( $url, ":content_file" => $local_file_name );
收到的文件 $mech->get
但是,它是用 ANSI 编码编写的,并且包含“gibberich”(我想不是“翻译”的 UTF-8 数据)。我该如何制作
get :content_file
创建本地文件 UTF-8 编码?还是我只是按原样下载文件,然后再将其转换为 UTF-8?
如果是这样,请指出我正确的方向,因为将 ANSI 编码的文件读取为 UTF-8 并不能解决问题......
最佳答案
这与 UTF-8 或字符编码无关。您将收到 gzip 压缩的响应。
如果 Compress::Zlib 可用,则 WWW::Mechanize 默认提供以下 header :
Accept-Encoding: gzip
这允许远程端压缩响应。如果是,远程端将在响应中提供以下 header :Content-Encoding: gzip
这在这里发生,您正在保存压缩的响应。您可以使用
:content_cb
而不是 :content_file
提供一个回调来解压数据并存储它。或者,您可以通过提供以下 header 来简单地请求未压缩版本:Accept-Encoding: identity
这是使用$mech->get($url,
Accept_Encoding => 'identity',
":content_file" => $local_file_name,
);
如果你不需要 WWW::Mechanize 的开销,为什么不使用它的基类 LWP::UserAgent .它不提供 Accept-Encoding
默认情况下,因此服务器不太可能对响应进行 gzipmy $ua = LWP::UserAgent->new();
# Will work 99.999% of the time.
$ua->get($url, ":content_file" => $local_file_name);
# Definitely works.
$ua->get($url,
Accept_Encoding => 'identity',
":content_file" => $local_file_name,
);
关于file - Perl:使用 Mechanize content_file 获取 UTF-8 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63957793/