in reply to fork / threads script

The Mojolicious project has one of the most actively developed User Agents to support event-loop style requests. This makes it trivial to make a bunch of requests in parallel, and then just wait for them to all come in. They are all executed immediately, and then the IO loop executes a callback that collects the responses. Here's an example using Mojo::UserAgent and Mojo::IOLoop, which are both part of Mojolicious.

use Mojo::UserAgent; use Mojo::IOLoop; my @url = qw{ http://example.com http://perlmonks.org }; my $ua = Mojo::UserAgent->new; Mojo::IOLoop->delay( sub { my $delay = shift; $ua->get($_ => $delay->begin) foreach @url }, sub { my ($delay, @tx) = @_; print "'", $_->req->url, "' => '", $_->res->text, "'\n" foreach @tx; } )->wait;

The output will be something like this:

'http://perlmonks.org' => '<!DOCTYPE HTML PUBLIC .......', 'http://example.com' => '<!doctype html> .......',

So in the example above, the first sub implements all the get requests. The requests are fired off in rapid succession. The second sub collects the responses in whatever order they emerge. Querying the response object is an easy way to keep track of which is which. Notice how in my example output I'm hitting example.com first, but perlmonks.org is the first to return. The order in which they return is simply based on what comes in first. But it's not hard to sort out what is what. It's amazing to see when you place dozens if not hundreds of URL's in the list and watch them all come in.

This is but one of several ways to implement parallel web scraping using Mojolicious. Others are outlined in its documentation.

I gave another (probably easier to follow) example here: Re: use LWP::Simple slows script down., and here: Re: Most memory efficient way to parallel http request. And a there's a screencast from tempire that demonstrates a non-blocking technique, here: http://mojocasts.com/e5.

Update: Here's another example based on the snippet from Re: use LWP::Simple slows script down.:

use Mojo::UserAgent; use Mojo::IOLoop; my @url = qw( http://perlmonks.org http://example.com ); my $ua = Mojo::UserAgent->new; $ua->get( $_ => sub { my( $ua, $tx ) = @_; print "'", $tx->req->url, "' => '", $tx->res->text, "'\n"; } ) foreach @url; Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

Though the latter seems simpler, the former stops its event loop as soon as the last request comes in, instead of waiting a few moments to realize that it is done listening.


Dave