Pliant AllianceSoftware development notes & tools

Building a Simple Web Scraper with Perl

A web scraper is a small program that retrieves pages, finds the information that matters, and saves it in a form another tool can use. Perl remains well suited to this work because its text-processing facilities are mature, its networking modules are widely available, and a useful script can fit on a single screen without requiring a large framework.

The aim here is a practical scraper rather than a full crawler. It will request a page, parse selected elements, and write clean records to a CSV file. The examples use a product listing, but the same approach applies to software documentation, public notices, job advertisements, event calendars, and other pages whose structure is reasonably consistent.

Choosing a sensible target

Begin with a page that is public, stable, and narrow in scope. A search-results page or a category page is usually easier than a site-wide search form, because the HTML structure is more predictable and the number of requests can be controlled. Inspect the page in a browser and identify the elements that contain the title, price, link, date, or other fields you need.

Australian sites often reveal small details that affect the output. A local retailer may display prices in Australian dollars, include GST in the advertised amount, or show delivery conditions by postcode. If the scraper is recording prices, preserve the currency explicitly rather than assuming that a dollar sign always means the same thing. A record such as AUD,49.95 is safer than a bare 49.95, especially if pages from New Zealand or the United States might later be included.

It is also worth reading the site’s terms of use and checking its robots.txt file before making requests. A scraper should collect only what is necessary, identify itself honestly, and pause between requests. For background on the kind of careful, tool-focused writing that suits this project, Mike Meredith’s notes provide a useful example of concise technical reference material.

Perl’s CPAN ecosystem offers several ways to download and parse HTML. LWP::UserAgent and HTML::TreeBuilder are straightforward choices for a small script. Install them with your operating system’s Perl package manager or with CPAN:

cpan LWP::UserAgent HTML::TreeBuilder

On a modern Linux system, package names may differ. Ubuntu users may find packaged versions through apt, while macOS users often have Perl available through a package manager. Windows users can use a Perl distribution such as Strawberry Perl. The important point is to confirm that the modules are installed before debugging the scraper itself.

Fetching a page politely

The first stage is an HTTP request. A user agent should have a descriptive name, a contact address where appropriate, a timeout, and a clear response check. The following example retrieves one page and stops if the server returns an error:

#!/usr/bin/env perl

use strict;
use warnings;
use LWP::UserAgent;

my $url = 'https://example.com/products';

my $ua = LWP::UserAgent->new(
    agent   => 'PliantExampleScraper/1.0',
    timeout => 15,
);

my $response = $ua->get($url);

die "Request failed: " . $response->status_line . "\n"
    unless $response->is_success;

my $html = $response->decoded_content;
print length($html), " bytes received\n";

decoded_content is preferable to reading the raw response body because it takes the declared character encoding into account. Some older pages provide incomplete encoding information, so unusual characters may still require testing. Australian place names and business titles can contain accented characters, and curly apostrophes or en dashes commonly appear in editorial content.

Do not place a tight loop around get. A short delay, such as two seconds, makes a substantial difference to a small site and reduces the chance that the script will be mistaken for abusive traffic. If several pages must be collected, cache each response locally while developing. This avoids repeatedly contacting the same server when changing a selector or cleaning a field.

use Time::HiRes qw(sleep);

for my $page (1 .. 5) {
    my $page_url = "https://example.com/products?page=$page";
    my $res = $ua->get($page_url);

    if ($res->is_success) {
        open my $cache, '>:encoding(UTF-8)', "page-$page.html"
            or die "Cannot write cache: $!";
        print {$cache} $res->decoded_content;
        close $cache;
    } else {
        warn "Could not fetch page $page: "
           . $res->status_line . "\n";
    }

    sleep 2;
}

A cache is useful for more than politeness. It makes development repeatable: the parser can be tested against the same input while the network is disconnected or the live page changes. When a website blocks automated clients, the correct response is to stop and investigate its published access policy rather than attempting to disguise the program.

Selecting data from HTML

Once the document has been downloaded, parse it as HTML instead of using regular expressions to match tags. HTML permits optional elements, nested markup, entities, and line breaks in places that make regular expressions brittle. HTML::TreeBuilder creates a tree that can be searched by tag name, class, or other attributes.

Suppose each product is contained in a div with the class product, the name is in an h2, the price is in a span with the class price, and the link is on an a element. A parser could look like this:

use HTML::TreeBuilder;

my $tree = HTML::TreeBuilder->new;
$tree->parse($html);
$tree->eof;

my @products = $tree->look_down(
    _tag  => 'div',
    class => 'product',
);

for my $product (@products) {
    my $name_node  = $product->look_down(_tag => 'h2');
    my $price_node = $product->look_down(
        _tag  => 'span',
        class => 'price',
    );
    my $link_node = $product->look_down(_tag => 'a');

    my $name  = $name_node  ? $name_node->as_text : '';
    my $price = $price_node ? $price_node->as_text : '';
    my $link  = $link_node  ? ($link_node->attr('href') || '') : '';

    print "$name | $price | $link\n";
}

$tree->delete;

The exact selectors must be adapted to the target page. Browser developer tools can reveal the relevant classes and nesting. Prefer a selector tied to the meaning of the content, such as product or price, rather than a generated class containing random numbers. If the site changes its layout, a semantic class usually survives longer.

Links are often relative. A page may contain /products/keyboard instead of a complete address, so turn it into an absolute URL before saving it. The URI module handles this safely:

use URI;

my $absolute = URI->new_abs($link, $url)->as_string;

Text also needs cleaning. as_text may return line breaks and repeated spaces from nested elements. A small normalisation function keeps the output readable:

sub clean_text {
    my ($text) = @_;
    $text //= '';
    $text =~ s/\s+/ /g;
    $text =~ s/^\s+|\s+$//g;
    return $text;
}

Call clean_text on names and prices before writing them. Keep the original value during early testing if accuracy matters; a price such as From $49.95 inc. GST may contain information that should not be discarded until the desired data model is clear.

Writing reliable output

Printing pipe-separated values is convenient for a quick test, but CSV is better when the result will be opened in LibreOffice, imported into a database, or processed by another Perl script. The Text::CSV module takes care of commas, quotes, and embedded newlines:

use Text::CSV;

my $csv = Text::CSV->new({ binary => 1, eol => "\n" })
    or die "Cannot create CSV writer";

open my $out, '>:encoding(UTF-8)', 'products.csv'
    or die "Cannot open products.csv: $!";

$csv->print($out, [qw(name price url collected_at)]);

for my $product (@products) {
    my $name = clean_text(
        ($product->look_down(_tag => 'h2') || '')->as_text
    );

    my $price_node = $product->look_down(
        _tag => 'span',
        class => 'price',
    );
    my $price = $price_node
        ? clean_text($price_node->as_text)
        : '';

    my $link_node = $product->look_down(_tag => 'a');
    my $href = $link_node ? ($link_node->attr('href') || '') : '';
    my $absolute = $href ? URI->new_abs($href, $url)->as_string : '';

    $csv->print($out, [
        $name,
        $price,
        $absolute,
        scalar localtime,
    ]);
}

close $out;

The example includes a collection timestamp. That is valuable when prices or availability change, and it lets a later report distinguish a current observation from an old one. For Australian services operating across a large country, decide whether timestamps should be stored in UTC or in a named local zone. A job scheduled on a server in Sydney may run on a different clock from a report viewed in Perth, particularly around daylight-saving changes.

Missing fields should be recorded deliberately rather than causing the entire run to fail. A product without a price may be out of stock, a sponsored listing may use a different template, or the page may simply have changed. Count these cases and emit a warning:

my $missing_price = 0;

for my $product (@products) {
    my $price_node = $product->look_down(
        _tag => 'span',
        class => 'price',
    );

    if (!$price_node) {
        $missing_price++;
        next;
    }

    # Extract and save the product here.
}

warn "$missing_price products had no price\n"
    if $missing_price;

Validation catches quiet failures. Check that a name is non-empty, that a link begins with http, and that a price resembles the form your application expects. Do not assume every Australian price includes a decimal part: some pages show $50, while others show $49.95. If numerical comparison is required, remove currency symbols carefully and retain the original display value in a separate column.

Expanding the script safely

A single page is a useful starting point, but a production scraper needs pagination and retry behaviour. Pagination may use a page query parameter, a next link, or an infinite-scroll request made through JavaScript. The simplest Perl scraper can handle ordinary linked pages, but it will not automatically reproduce browser JavaScript. If the required data appears only after a script runs, inspect the network requests and determine whether a public JSON endpoint is available.

Retries should be limited and should distinguish temporary failures from permanent ones. A server error such as 503 may justify another attempt after a delay; a 404 usually does not. Keep the retry count small and log the URL, status, and time. Logs turn an unexplained empty CSV file into an event that can be investigated.

The script can also be separated into functions so that fetching, parsing, and output are tested independently:

sub fetch_html {
    my ($ua, $url) = @_;
    my $response = $ua->get($url);

    die $response->status_line . " for $url\n"
        unless $response->is_success;

    return $response->decoded_content;
}

sub product_rows {
    my ($html, $base_url) = @_;
    my $tree = HTML::TreeBuilder->new;
    $tree->parse($html);
    $tree->eof;

    my @rows;
    for my $node ($tree->look_down(_tag => 'div', class => 'product')) {
        my $title = $node->look_down(_tag => 'h2');
        next unless $title;

        push @rows, {
            name => clean_text($title->as_text),
        };
    }

    $tree->delete;
    return \@rows;
}

This arrangement makes unit testing possible with saved HTML fixtures. A fixture representing a normal product, a missing price, and a changed layout can expose parser problems before the next scheduled run. Perl’s testing tools are lightweight, and even a few assertions are preferable to trusting a script that silently produces an empty file.

Automation is the final step. A Unix cron job, a systemd timer, or Windows Task Scheduler can run the scraper at an appropriate interval. Keep credentials, output paths, and request limits in configuration rather than scattering them through the code. If the scraper becomes part of a larger build or reporting process, the principles in Ant build automation are relevant: repeatable tasks, clear dependencies, and visible failures matter just as much for data collection as for compiling software.

A simple Perl scraper works best when it remains modest. Fetch a limited set of pages, parse fields with selectors that reflect the page’s structure, preserve useful source information, and make failures visible. With those habits in place, the script can support a small Australian price watch, a local events archive, or a developer’s research workflow without becoming an intrusive or unmaintainable crawler.