【问题标题】:Trouble with downloading files下载文件有问题
【发布时间】:2010-07-07 16:34:17
【问题描述】:

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

【问题讨论】:

    标签: perl download www-mechanize


    【解决方案1】:

    很抱歉,但几乎所有事情都错了。

    • 您以错误的方式混合使用了LWP::UserAgentWWW::Mechanize。如果您使用 $browser->get() 混合来自 2 个模块的功能,则不能使用 $mech->follow_link()$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"; ... }
    在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')
    

    【讨论】:

    • 你还在用浏览器吗->get?
    • 但是现在它怎么知道要去哪个页面呢?
    • 不,他正在使用WWW::Mechanizecredentials方法。见http://search.cpan.org/perldoc/WWW::Mechanize#$mech-%3Ecredentials%28_$username,_$password_%29
    • 我看到了,但他说不要使用浏览器->get()。那么我现在应该把 URL 放在哪里呢?
    • 我更正了,当然需要 get 但来自 $mech 而不是 $browser
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    相关资源
    最近更新 更多