繁体   English   中英

无法跟踪与WWW :: Mechanize的图像链接

[英]Trouble following an image link with WWW::Mechanize

我正在研究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);

任何帮助将非常感激!

你的脚本几乎是正确的。 NASA页面的结构是:

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

因此,如果$mech->follow_link成功,则您已经在$mech->content $mech->follow_link拥有了图像数据。

尝试这个:

$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";

暂无
暂无

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

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