Skip to content

Instantly share code, notes, and snippets.

@memememomo
Created February 5, 2011 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save memememomo/812563 to your computer and use it in GitHub Desktop.
Save memememomo/812563 to your computer and use it in GitHub Desktop.
use strict;
use warnings;
use utf8;
use Mojo::Client;
use Mojo::ByteStream 'b';
my $client = Mojo::Client->new;
# Mojo::Message::Response (http://mojolicio.us/perldoc?Mojo/Message)
my $res = $client->max_redirects(3)->get('http://search.cpan.org/')->res;
# Mojo::DOM (http://mojolicio.us/perldoc?Mojo/DOM)
my $dom = $res->dom;
# Iterate
$dom->find('a')->each(sub {
my $dom = shift;
b($dom->text)->say;
b($dom->attrs->{href})->say;
});
$dom->find('input[name="query"]')->each(sub {
my $dom = shift;
b($dom->attrs->{type})->say;
b($dom->attrs->{size})->say;
});
# Form post
my $tx = $client->post_form('http://search.cpan.org/search' => { q => 'mojo' });
if (my $res = $tx->success) {
b($res->body)->say;
}
else {
my ($message, $code) = $tx->error;
b("Error $code: $message")->say;
}
# Parallel requests
my $callback = sub { b(shift->res->body)->say };
$client->get('http://mojolicio.us' => $callback);
$client->get('http://search.cpan.org' => $callback);
$client->start;
# JSON
use Mojo::URL;
my $url = Mojo::URL->new('http://api.atnd.org/events/');
$url->query->param(keyword => 'perl');
$url->query->param(format => 'json');
my $json = $client->get($url)->res->json;
for my $event (@{$json->{events}}) {
b("title: ", b($event->{title})->encode('UTF-8'))->say;
b("url: ", $event->{event_url})->say;
b("--------")->say;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment