memwaster has asked for the wisdom of the Perl Monks concerning the following question:
This is my first attempt at a perl program that does anything vaguely useful - it is a web crawler that currently just prints out the urls that it visits, but may later look for some specific content. Some of the code I pinched from an example program. The problem is that it uses up 2Gb of memory in about 10 minutes and I cannot figure out why this is. I have probably done something fundamentally wrong. Can anyone spot an obvious problem, or offer ideas of how to troubleshoot this? Thanks.
Oh, the usage is basically "./crawler.pl www.mysite.com mysite.com" where the second argument restricts the links it follows to avoid crawling sites other than the target.
#!/usr/bin/perl use strict; use warnings; use LWP::UserAgent; use HTML::LinkExtor; use URI::URL; my $site = shift @ARGV; my $domain = shift @ARGV; my $firsturl = "http://$site"; my $ua = LWP::UserAgent->new; my @links = (); my @newlinks = (); my @visited = (); my $newlink = ""; my $link = ""; push (@links, $firsturl); # Set up a callback that collects links sub callback { my($tag, %attr) = @_; return if $tag ne 'a'; # we only look closer at <a ...> push(@newlinks, values %attr); } # Make the parser my $p = HTML::LinkExtor->new(\&callback); # The main loop MAIN: foreach my $url (@links) { # Skip if we have been here before foreach my $inside (@visited) { #print "skipping $url\n" if $url eq $inside; next MAIN if $url eq $inside; } # Request document and parse it as it arrives print "visiting $url\n"; my $res = $ua->request(HTTP::Request->new(GET => $url), sub {$p->parse($_[0])}); # Remember that we have visited this url push (@visited, $url); # Expand all URLs to absolute ones my $base = $res->base; @newlinks = map { $_ = url($_, $base)->abs; } @newlinks; # Reduce the links to only ones in our domain foreach $newlink (@newlinks) { if ($newlink =~ /$domain/) { push (@links, $newlink); } } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Newbie memory leak
by ikegami (Patriarch) on Jul 25, 2007 at 16:35 UTC | |
by ikegami (Patriarch) on Jul 25, 2007 at 17:05 UTC | |
by memwaster (Initiate) on Jul 26, 2007 at 09:59 UTC |