Problem after linking to image from WWW :: Mechanization

I am working on a Perl script to get the "astronomical image of the day" and set it as wallpaper. Then I would put a kronob to do this every day for me. But it’s not easy for me to make the script follow the link to the image, which leads to a full-sized image, and only then load it. I tried something like this code below (keep in mind that I'm just a beginner of Perl who knows little about Perl regex):

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

Any help would be greatly appreciated!

+4
source share
1 answer

Your script is almost correct. NASA page structure:

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

So, if $mech->follow_link successful, you already have the image data in $mech->content .

Try the following:

 $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"; 
+3
source

Source: https://habr.com/ru/post/1444000/


All Articles