我正在尝试自动完成我的任务之一,我必须下载一些软件的最新5个版本,让我们来自http://www.filehippo.com/download_google_talk/的Google谈话。
我从来没有做过这种类型的编程,我想通过perl与Web进行交互。我刚刚阅读并了解到通过CGI模块我们可以实现这个东西所以我尝试了这个模块。
如果某个机构可以给我更好的建议那么请欢迎你:)
我的代码:
#!/usr/bin/perl
use strict;
use warnings;
use CGI;
use CGI::Carp qw/fatalsToBrowser/;
my $path_to_files = 'http://www.filehippo.com/download_google_talk/download/298ba15362f425c3ac48ffbda96a6156';
my $q = CGI->new;
my $file = $q->param('file') or error('Error: No file selected.');
print "$file\n";
if ($file =~ /^(\w+[\w.-]+\.\w+)$/) {
$file = $1;
}
else {
error('Error: Unexpected characters in filename.');
}
if ($file) {
download($file) or error('Error: an unknown error has occured. Try again.');
}
sub download
{
open(DLFILE, '<', "$path_to_files/$file") or return(0);
print $q->header(-type => 'application/x-download',
-attachment => $file,
'Content-length' => -s "$path_to_files/$file",
);
binmode DLFILE;
print while <DLFILE>;
close (DLFILE);
return(1);
}
sub error {
print $q->header(),
$q->start_html(-title=>'Error'),
$q->h1($_[0]),
$q->end_html;
exit(0);
}
在上面的代码我试图打印我要下载的文件名,但它显示错误信息。我无法弄清楚为什么这个错误“错误:没有选择文件。”快来了。
答案 0 :(得分:2)
抱歉,你走错了路。最好的选择是这个模块:http://metacpan.org/pod/WWW::Mechanize
此页面包含许多开头示例:http://metacpan.org/pod/WWW::Mechanize::Examples
它可能更优雅,但我认为这段代码更容易理解。
use strict;
use warnings;
my $path_to_files = 'http://www.filehippo.com/download_google_talk/download/298ba15362f425c3ac48ffbda96a6156';
my $mech = WWW::Mechanize->new();
$mech->get( $path_to_files );
$mech->save_content( "download_google_talk.html" );#save the base to see how it looks like
foreach my $link ( $mech->links() ){ #walk all links
print "link: $link\n";
if ($link =~ m!what_you_want!i){ #if it match
my $fname = $link;
$fname =~ s!\A.*/!! if $link =~ m!/!;
$fname .= ".zip"; #add extension
print "Download $link to $fname\n";
$mech->get($link,":content_file" => "$fname" );#download the file and stoore it in a fname.
}
}