简体   繁体   English

如何使用 Perl 下载文件?

[英]How do I download a file using Perl?

I'm running Perl on Windows XP, and I need to download a file from the URL http://marinetraffic2.aegean.gr/ais/getkml.aspx .我在 Windows XP 上运行 Perl,我需要从 URL http://marinetraffic2.aegean.gr/ais/getkml.aspx下载一个文件。

How should I do this?我该怎么做? I have attempted using WWW::Mechanize, but I can't get my head around it.我曾尝试使用 WWW::Mechanize,但我无法理解它。

This is the code I used:这是我使用的代码:

my $url = 'marinetraffic2.aegean.gr/ais/getkml.aspx';
my $mech = WWW::Mechanize->new;
$mech->get($url);

I'd use LWP::Simple for this.为此,我会使用LWP::Simple

#!/usr/bin/perl

use strict;
use warnings;

use LWP::Simple;

my $url = 'http://marinetraffic2.aegean.gr/ais/getkml.aspx';
my $file = 'data.kml';

getstore($url, $file);

I used File::Fetch as this is a core Perl module (I didn't need to install any additional packages) and will try a number of different ways to download a file depending on what's installed on the system.我使用了File::Fetch,因为这是一个核心 Perl 模块(我不需要安装任何额外的包),并且会根据系统上安装的内容尝试多种不同的方式来下载文件。

use File::Fetch;
my $url = 'http://www.example.com/file.txt';
my $ff = File::Fetch->new(uri => $url);
my $file = $ff->fetch() or die $ff->error;

Note that this module will in fact try to use LWP first if it is installed...请注意,如果安装了该模块,实际上它会首先尝试使用 LWP...

If downloading that file is all you actually do, you'd better go with @davorg's answer.如果您实际上只需要下载该文件,那么您最好使用@davorg 的答案。

If this is part of a bigger process, you access the ressource you downloaded as a string using method content on your $mech object.如果这是更大进程的一部分,您可以使用$mech对象上的方法content访问作为字符串下载的资源。

use WWW::Mechanize;

my $url = 'marinetraffic2.aegean.gr/ais/getkml.aspx';
my $local_file_name = 'getkml.aspx';

my $mech = WWW::Mechanize->new;

$mech->get( $url, ":content_file" => $local_file_name );

This in fact wraps around the LWP::UserAgent->get .这实际上围绕着LWP::UserAgent->get

More details can be found at WWW::Mechanize docs page .更多细节可以在WWW::Mechanize 文档页面找到

Just in case someone needs an oneliner ;)以防万一有人需要oneliner ;)

perl -e 'use File::Fetch;my $url = "http://192.168.1.10/myFile.sh";my $ff = File::Fetch->new(uri => $url);my $file = $ff->fetch() or die $ff->error;'

Just change the content of $url只需更改$url的内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM