代码之家  ›  专栏  ›  技术社区  ›  shinjuo

下载文件有问题

  •  1
  • shinjuo  · 技术社区  · 14 年前

    我正在尝试使用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 回复  |  直到 14 年前
        1
  •  3
  •   radius    14 年前

    对不起,几乎所有的事情都错了。

    • 你用的是 LWP::UserAgent WWW::Mechanize $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);
    

    您可以检查get()的结果,并通过检查 $mech->success() 结果 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')