4

「今日の天文画像」を取得して壁紙として設定する Perl スクリプトを作成しています。それから、毎日それを行うように cronjob を設定しました。しかし、スクリプトがフルサイズの画像につながる画像リンクをたどってから、それをダウンロードするのに苦労しています。私は次のようなコードを試していました(私はPerl正規表現についてあまり知らないPerl初心者にすぎないことに注意してください):

#!/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);

どんな助けでも大歓迎です!

4

1 に答える 1

3

あなたのスクリプトはほぼ正しいです。NASA ページの構造は次のとおりです。

<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";
于 2012-11-04T22:17:30.403 に答える