The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Scrappy::Scraper - Scrappy Web Scraper

VERSION

version 0.9111110

SYNOPSIS

Scrappy::Scraper is the meat and potatoes behind Scrappy.

    #!/usr/bin/perl
    use Scrappy;

    my $scraper = Scrappy->new;
    my $queue = $scraper->queue;
    
    $queue->add('http://search.cpan.org/recent'); # starting url
    
    while (my $url = $queue->next) {
        
        $scraper->get($url);
        
        foreach my $link (@{ $scraper->grab('#cpansearch li a') }) {
            $queue->add($link->href);
        }
    }

DESCRIPTION

Scrappy is an easy (and hopefully fun) way of scraping, spidering, and/or harvesting information from web pages, web services, and more. Scrappy is a feature rich, flexible, intelligent web automation tool.

Scrappy (pronounced Scrap+Pee) == 'Scraper Happy' or 'Happy Scraper'; If you like you may call it Scrapy (pronounced Scrape+Pee) although Python has a web scraping framework by that name and this module is not a port of that one.

METHODS

back

The back method is the equivalent of hitting the "back" button in a browser, it returns the previous page (response), it will not backtrack beyond the first request.

cookies

The cookies method is a shortcut to the automatically generated WWW::Mechanize cookie handler. This method returns an HTTP::Cookie object. Setting this as undefined using the _undef keyword will prevent cookies from being stored and subsequently read.

    get $requested_url;
    my $cookies = cookies;
    
    # prevent cookie storage
    cookies _undef;

domain

The domain method returns the URI host of the current page.

download

The download method is passed a URL, a Download Directory Path and a optionally a File Path, then it will follow the link and store the response contents into the specified file without leaving the current page. Basically it downloads the contents of the request (especially when the request pushes a file download). If a File Path is not specified, Scrappy will attempt to name the file automatically resorting to a random 6-charater string only if all else fails, then returns to the originating page.

    my $scaper = Scrappy->new;
    $scraper->download($requested_url, '/tmp');
    
    # supply your own file name
    $scraper->download($requested_url, '/tmp', 'somefile.txt');

form

The form method is used to submit a form.

    my  $scraper = Scrappy->new;
    
    $scraper->form(fields => {
        username => 'mrmagoo',
        password => 'foobarbaz'
    });
    
    # or more specifically, for pages with multiple forms
    
    $scraper->form(form_number => 1, fields => {
        username => 'mrmagoo',
        password => 'foobarbaz'
    });

get

The get method takes a URL or URI and returns an HTTP::Response object.

    my  $scraper = Scrappy->new;
        $scraper->get($new_url);

page

The page method returns the URI of the current page.

page_data

The page_data method returns the content of the current page exactly the same as the html() function does, additionally this method when passed a string with HTML markup, updates the content of the current page with that data and returns the modified content.

page_loaded

The page_loaded method returns true/false based on whether the last request was successful.

    my $scraper = Scrappy->new;
    $scraper->get($requested_url);
    
    if ($scraper->page_loaded) {
        ...
    }

page_content_type

The page_content_type method returns the content_type of the current page.

page_ishtml

The page_ishtml method returns true/false based on whether our content is HTML, according to the HTTP headers.

page_match

The page_match method checks the passed-in URL (or URL of the current page if left empty) against the URL pattern (route) defined. If URL is a match, it will return the parameters of that match much in the same way a modern web application framework processes URL routes.

    my $url = 'http://somesite.com/tags/awesomeness';
    
    ...
    
    my $scraper = Scrappy->new;
    
    # match against the current page
    my $this = $scraper->page_match('/tags/:tag');
    if ($this) {
        print $this->{'tag'};
        # ... prints awesomeness
    }
    
    .. or ..
    
    # match against a passed url
    my $this = $scraper->page_match('/tags/:tag', $url, {
        host => 'somesite.com'
    });
    
    if ($this) {
        print "This is the ", $this->{tag}, " page";
        # ... prints this is the awesomeness page
    }

page_reload

The page_reload method acts like the refresh button in a browser, it simply repeats the current request.

page_status

The page_status method returns the 3-digit HTTP status code of the response.

    my $scraper = Scrappy->new;
    $scraper->get($requested_url);
    
    if ($scraper->page_status == 200) {
        ...
    }

page_text

The page_text method returns a text representation of the last page having all HTML markup stripped.

page_title

The page_title method returns the content of the title tag if the current page is HTML, otherwise returns undef.

post

The post method takes a URL, a hashref of key/value pairs, and optionally an array of key/value pairs, and posts that data to the specified URL, then returns an HTTP::Response object.

    my $scraper = Scrappy->new;

    $scraper->post($requested_url, {
        input_a => 'value_a',
        input_b => 'value_b'
    });
    
    # w/additional headers
    my %headers = ('Content-Type' => 'multipart/form-data');
    $scraper->post($requested_url, {
        input_a => 'value_a',
        input_b => 'value_b'
    },  %headers);

Note! The most common post headers for content-type are application/x-www-form-urlencoded and multipart/form-data.

proxy

The proxy method is a shortcut to the WWW::Mechanize proxy function. This method set the proxy for the next request to be tunneled through. Setting this as undefined using the _undef keyword will reset the scraper application instance so that all subsequent requests will not use a proxy.

    my $scraper = Scrappy->new;
    
    $scraper->proxy('http', 'http://proxy.example.com:8000/');
    $scraper->get($requested_url);
    
    $scraper->proxy('http', 'ftp', 'http://proxy.example.com:8000/');
    $scraper->get($requested_url);
    
    # best practice when using proxies
    
    use Tiny::Try;
    
    $scraper->proxy('http', 'http://proxy.example.com:8000/');
    
    try {
        $scraper->get($requested_url);
    };

Note! When using a proxy to perform requests, be aware that if they fail your program will die unless you wrap your code in an eval statement or use a try/catch mechanism. In the example above we use Tiny::Try to trap any errors that might occur when using proxy.

request_denied

The request_denied method is a simple shortcut to determine if the page you requested got loaded or redirected. This method is very useful on systems that require authentication and redirect if not authorized. This function return boolean, 1 if the current page doesn't match the requested page.

    my $scraper = Scrappy->new;
    $scraper->get($url_to_dashboard);
    
    if ($scraper->request_denied) {
        # do login, again
    }
    else {
        # resume ...
    }

log

The log method logs an event with the event logger.

    my  $scraper = Scrappy->new;
        $scraper->debug(1);
        
        $scraper->log('error', 'Somthing bad happened');
        
        ...
        
        $scraper->log('info', 'Somthing happened');
        $scraper->log('warn', 'Somthing strange happened');
        $scraper->log('coolness', 'Somthing cool happened');

pause

This method sets breaks between your requests in an attempt to simulate human interaction.

    my  $scraper = Scrappy->new;
        $scraper->pause(20);
    
        $scraper->get($request_1);
        $scraper->get($request_2);
        $scraper->get($request_3);

Given the above example, there will be a 20 sencond break between each request made, get, post, request, etc., You can also specify a range to have the pause method select from at random...

        $scraper->pause(5,20);
    
        $scraper->get($request_1);
        $scraper->get($request_2);
    
        # reset/turn it off
        $scraper->pause(0);
    
        print "I slept for ", ($scraper->pause), " seconds";

Note! The download method is exempt from any automatic pausing.

response

The response method returns the HTTP::Repsonse object of the current page.

stash

The stash method sets a stash (shared) variable or returns a reference to the entire stash object.

    my  $scraper = Scrappy->new;
        $scraper->stash(age => 31);
        
    print 'stash access works'
        if $scraper->stash('age') == $scraper->stash->{age};
    
    my @array = (1..20);
    $scraper->stash(integers => [@array]);

store

The store method stores the contents of the current page into the specified file. If the content-type does not begin with 'text', the content is saved as binary data.

    my  $scraper = Scrappy->new;
    
    $scraper->get($requested_url);
    $scraper->store('/tmp/foo.html');

select

The select method takes XPATH or CSS selectors and returns an arrayref with the matching elements.

    my $scraper = Scrappy->new;
    
    # return a list of links
    my $list = $scraper->select('#profile li a')->data; # see Scrappy::Scraper::Parser
    
    foreach my $link (@{$list}) {
        print $link->{href}, "\n";
    }
    
    # Zoom in on specific chunks of html code using the following ...
    my $list = $scraper
    ->select('#container table tr') # select all rows
    ->focus(4) # focus on the 5th row
    ->select('div div')->data;
    
    # The code above selects the div > div inside of the 5th tr in #container table
    # Access tag html, text and other attributes as follows...
    
    $element = $scraper->select('table')->data->[0];
    $element->{html}; # HTML representation of the table
    $element->{text}; # Table stripped of all HTML
    $element->{cellpadding}; # cellpadding
    $element->{height}; # ...

AUTHOR

Al Newkirk <awncorp@cpan.org>

COPYRIGHT AND LICENSE

This software is copyright (c) 2010 by awncorp.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.