下载文件时遇到问题

时间:2010-07-07 16:34:17

标签: perl download www-mechanize

我正在尝试使用perl从网站下载文件。我选择不使用wget,这样我就可以学习如何这样做。我不确定我的页面是否没有连接,或者我的语法是否出错。另外,检查您是否获得与该页面的连接的最佳方法是什么。

#!/usr/bin/perl -w
use strict;
use LWP;
use WWW::Mechanize;

my $mech = WWW::Mechanize->new();
$mech->credentials( '********' , '********'); # if you do need to supply server and realms use credentials like in [LWP doc][2]
$mech->get('http://datawww2.wxc.com/kml/echo/MESH_Max_180min/');
$mech->success();
if (!$mech->success()) {
    print "cannot connect to page\n";
    exit;
}
$mech->follow_link( n => 8);
$mech->save_content('C:/Users/********/Desktop/');

1 个答案:

答案 0 :(得分:3)

我很抱歉,但几乎一切都错了。

  • 您以错误的方式混合使用LWP::UserAgentWWW::Mechanize。如果在混合2个模块的功能时使用$mech->follow_link(),则无法执行$browser->get()$mech不知道您提出了请求。
  • 凭据的参数不佳,请参阅the doc

你可能更想做这样的事情:

use WWW::Mechanize;
my $mech = WWW::Mechanize->new();

$mech->credentials( '************' , '*************'); # if you do need to supply server and realms use credentials like in LWP doc
$mech->get('http://datawww2.wxc.com/kml/echo/MESH_Max_180min/');
$mech->follow_link( n => 8);

您可以通过查看$mech->success()结果来检查get()和follow_link()的结果 if (!$mech->success()) { warn "error"; ... }
在关注>链接后,可以使用$mech->content()获取数据,如果您想将其保存在文件中,请使用$mech->save_content('/path/to/a/file')

完整的代码可以是:

use strict;
use WWW::Mechanize;
my $mech = WWW::Mechanize->new();

$mech->credentials( '************' , '*************'); #
$mech->get('http://datawww2.wxc.com/kml/echo/MESH_Max_180min/');
die "Error: failled to load the web page" if (!$mech->success());
$mech->follow_link( n => 8);
die "Error: failled to download content" if (!$mech->success());
$mech->save_content('/tmp/mydownloadedfile')