2012-11-04 33 views
4

我正在研究Perl腳本以獲得「天文學圖像」並將其設置爲我的壁紙。然後我會設置一個cronjob爲我每天做這件事。但是我很難讓腳本沿着圖像鏈接進入全尺寸圖像,只有這樣,才能下載它。 我是想這樣的事情代碼波紋管(有記住,我只是一個Perl的初學者誰不知道很多關於Perl的正則表達式):與WWW的圖像鏈接後的麻煩::機械化

#!/usr/bin/perl -w 
use strict; 
use warnings; 
use WWW::Mechanize; 

my $url = "http://apod.nasa.gov/apod/astropix.html"; 

my $mech = WWW::Mechanize->new(); 
$mech->get($url); 
    #debugging 
if ($mech->follow_link(url_regex=>qr/\.(?:jpg|png)$/)){ 
    print "Following the image link..."; 
}else{ 
    print "Couldn't find the link..."; 
} 

my @img = $mech->find_image(alt_regex => qr/image/i); 

    foreach my $img(@img){ 
    $mech->get($img->url, ':content_file'=>'astro.jpg'); 
    } 

    print "\n"; 

    exit(0); 

任何幫助,將不勝感激!

+0

參見http://perlmonks.org/?node_id=978153 –

回答

3

你的腳本幾乎是正確的。美國航空航天局網頁的結構是:

<html> 
<body> 
    ... 
    <a href="http://.../blah.jpg"><img src="http://.../blah-lowres.jpg"></a> 
    ... 
</body> 
</html> 

所以,如果$mech->follow_link成功,你已經在$mech->content的圖像數據。

試試這個:

$mech->get($url) or die "unable to get $url"; 
$mech->follow_link(url_regex => qr/\.(jpg|png)\z/) or die "unable to follow image link"; 
open(my $fh, ">astro.jpg"); 
print {$fh} $mech->content; 
close($fh); 
print "saved image as astro.jpg\n"; 
+0

非常感謝您!它像一個魅力! – XVirtusX