下载文件时遇到问题

问题描述:

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

对不起,但几乎一切都是错误的。

  • 您以错误的方式混合使用LWP::UserAgentWWW::Mechanize。如果您使用$browser->get()作为混合2模块的功能,则不能执行$mech->follow_link()$mech不知道你做了一个请求。
  • 参数传递给凭证都不好,看到the doc

你更有可能想要做这样的事情:通过检查$mech->success()

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

您可以检查)获取的结果(和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') 
+0

的arent你仍然在使用浏览器的>得到什么? – shinjuo 2010-07-07 16:48:01

+0

但现在它怎么知道要去哪个页面? – shinjuo 2010-07-07 16:52:19

+0

不,他正在使用'WWW :: Mechanize'的'credentials'方法。请参阅'http://search.cpan.org/perldoc/WWW :: Mechanize#$ mech-%3Ecredentials%28_ $ username,_ $ password_%29' – 2010-07-07 16:59:38