1

我正在尝试使用 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/');
4

1 回答 1

3

我很抱歉,但几乎所有事情都是错误的。

  • 您以错误的方式混合使用LWP::UserAgentWWW::Mechanize$mech->follow_link()如果您使用$browser->get()来自 2 个模块的混合功能,您将无法做到这一点。$mech不知道你做了一个请求。
  • 凭据的参数不好,请参阅文档

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

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);

您可以通过检查结果来检查get()和follow_link()的$mech->success()结果 if (!$mech->success()) { warn "error"; ... }
在follow->link之后$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')
于 2010-07-07T16:44:38.047 回答