Chapter 9

Actual Scraping

We have built the extension interface and the tools for configuring a scraper. Now we can look at the part that actually performs the crawl. This is the job of scraper.js.

The important thing to notice is that scraper.js does not need to know which website we are scraping. It reads the configuration stored by the UI and uses that configuration to discover listings, navigate between pages, extract data, and maintain its progress.

Scraper State Helpers

const DELAY = 3000;

function getScraper() {
    return JSON.parse(localStorage.getItem("scraper"));
}

function setScraper(scraper) {
    localStorage.setItem("scraper", JSON.stringify(scraper));
}

function scraperExists() {
    if (getScraper() == null) return false;
    else return true;
}

function scraperIsRunning() {
    if (scraperExists()) {
        let scraper = getScraper();
        return scraper.running;
    }
}

The first functions provide a small interface around local storage. getScraper() loads the scraper configuration and converts the stored JSON string back into a JavaScript object.

setScraper() performs the opposite operation. It receives a JavaScript object, converts it to JSON with JSON.stringify(), and stores it in local storage.

The other two functions provide convenient checks. scraperExists() tells us whether a scraper configuration exists, while scraperIsRunning() checks the running flag.

The DELAY constant controls how long the scraper waits between navigations. A delay is useful because our scraper is navigating through a real website and should not immediately fire one navigation after another.

Generating CSS Selectors

function getCssSelector(element, all) {
    if (element.id && !all) return `#${CSS.escape(element.id)}`;
    let path = [];
    while (element && element.nodeType === Node.ELEMENT_NODE) {
        let selector = element.tagName.toLowerCase();
        if (element.classList.length > 0) {
            selector += [...element.classList]
                .map(cls => `.${CSS.escape(cls)}`)
                .join("");
        } if (!all && document.querySelectorAll(selector).length === 1) {
            path.unshift(selector);
            break;
        } if (!all) {
            let sibling = element;
            let index = 1;
            while (sibling = sibling.previousElementSibling) {
                if (sibling.tagName === element.tagName) {
                    index++;
                }
            } selector += `:nth-of-type(${index})`;
        } path.unshift(selector);
        element = element.parentElement;
    } return path.join(" > ");
}

getCssSelector() is one of the key functions behind our visual selector system. Given an HTML element, it attempts to construct a CSS selector that can later be used to find that element again.

The function first checks whether the element has an ID. If it does, the ID can provide a very simple selector such as #price.

If there is no suitable ID, the function walks up through the element's parents and builds a selector from the element's tag name and CSS classes. If necessary, it adds :nth-of-type() information to distinguish the element from other elements of the same type.

The individual parts are collected in the path array and finally joined with >. The result might look something like body > div > article > h2.

The all parameter changes this behavior slightly. When it is false, the function tries to create a selector that identifies a particular element. When working with selectors intended to match multiple elements, the function can instead build a less restrictive selector.

This function is what allows the user interface to turn a mouse click on a real HTML element into a selector that can be saved in the scraper configuration.

Finding Listing URLs

function extractListingUrls(cardUrlSelector) {
    let listingUrls = "";
    for (let card of document.querySelectorAll(cardUrlSelector))
      listingUrls += card.href + "\n";
    return listingUrls;
}

extractListingUrls() is primarily used while configuring the scraper. It takes the selector for listing cards and finds all matching elements on the current page.

Each matching element is expected to be a link, so its href is added to the result. The function returns the URLs as a string so the UI can display them to the user during the preview and configuration process.

Finding the Next Page

function extractNextPage(nextPageSelector) {
    try { return document.querySelector(nextPageSelector); }
    catch(e) { return ""; }
}

extractNextPage() finds the element responsible for pagination. Unlike extractListingUrls(), it returns the actual DOM element rather than its URL.

This is important because different websites can implement pagination differently. The next page might be an ordinary link with an href, or it might be a button that requires JavaScript to be executed. The scraper handles both cases later.

Extracting Data

function extractData() {
    let scraper = getScraper();
    let data = {};
    try {
        for (let key of Object.keys(scraper.selectors)) {
            let selector = document.querySelector(scraper.selectors[key]);
            selector.style.outline = "2px solid green";
            data[key] = selector.textContent.trim();
        }
        return data;
    } catch(e) { return {}; }
}

extractData() is where our configured field selectors become actual scraped data. The function reads the selectors object from the scraper configuration and loops through each named selector.

For every selector, document.querySelector() finds the corresponding element. Its text is then cleaned with trim() and stored under the selector's name.

For example, if the configuration contains "title" and "price", the resulting object might look like this:

{
    "title": "Beautiful apartment in Madrid",
    "price": "€350,000"
}

The green outline is also applied to the extracted element. This gives us visual feedback when previewing the data and makes it immediately obvious which elements are being used.

Discovering Listings

function parseLinks(scraper) {
    let linkSelectors = document.querySelectorAll(scraper.cardUrlSelector);
    for (let url of linkSelectors) scraper.listingUrls.push(url.href);
}

parseLinks() is the crawling version of extractListingUrls(). Instead of returning a string for display, it adds every discovered listing URL directly to the scraper's listingUrls array.

This is the first major step of our crawling process. We arrive on a listing page, find all of its individual listings, and save their URLs so they can be processed one by one.

Parsing an Individual Listing

function parseListing(scraper) {
    try {
        let data = extractData();
        console.log(JSON.stringify(data, null, 4))
        console.log("\nCurrent page:", scraper.currentPage);
        scraper.data.push(data)
    } catch(e) {}
}

parseListing() is responsible for processing one individual listing. It calls extractData(), prints the result to the browser console for debugging, and then adds the extracted object to the scraper's data array.

Notice how little website-specific logic exists here. The function does not know whether the field is a title, price, address, or something else. The selectors stored in the scraper configuration determine what gets extracted.

Waiting Between Pages

async function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

The sleep() helper pauses the asynchronous crawling process for the requested number of milliseconds. It is used before navigating to another page so that the scraper does not immediately jump from one page to another.

The Crawl Function

async function crawl() {
    let scraper = getScraper();
    if (scraper == null) return;
    else if (scraper.running) {
        if (scraper.currentPage == location.href) {
            scraper.currentPage = "";
            if (scraper.nextPageSelector.includes("button")) {
                document.querySelector(scraper.nextPageSelector).click();
                location.reload();
            } else location.href = document.querySelector(scraper.nextPageSelector).href
            return;
        } else if (scraper.listingUrls.length == 0) {
            parseLinks(scraper);
            scraper.currentPage = location.href;
            setScraper(scraper);
        } else parseListing(scraper);
        scraper.listingUrlIndex++;
        setScraper(scraper);
        if (scraper.listingUrlIndex == scraper.listingUrls.length) {
            scraper.listingUrls = [];
            scraper.listingUrlIndex = -1;
            localStorage.setItem("scraper", JSON.stringify(scraper));
            await sleep(DELAY);
            location.href = scraper.currentPage;
        } else {
            await sleep(DELAY);
            location.href = scraper.listingUrls[scraper.listingUrlIndex]
        }
    }
}; crawl();

The crawl() function is the heart of scraper.js. It ties all the previous functions together and implements the listing website model we introduced earlier.

First, the function loads the scraper configuration. If there is no scraper, there is nothing to do. If the scraper exists but running is false, the function also does nothing.

Returning to the Listing Page

if (scraper.currentPage == location.href) {
    scraper.currentPage = "";
    if (scraper.nextPageSelector.includes("button")) {
        document.querySelector(scraper.nextPageSelector).click();
        location.reload();
    } else location.href = document.querySelector(scraper.nextPageSelector).href
    return;
}

The first important branch checks whether we have returned to the listing page stored in currentPage. This means that all listings from that page have been processed.

The scraper then moves to the next listing page. If the configured selector identifies a button, it clicks that button and reloads the page. Otherwise, it assumes the element is a link and navigates directly to its href.

This small distinction is useful because pagination is not implemented consistently across websites. Some sites use ordinary links, while others use buttons controlled by JavaScript.

Discovering the Listings

else if (scraper.listingUrls.length == 0) {
    parseLinks(scraper);
    scraper.currentPage = location.href;
    setScraper(scraper);
} else parseListing(scraper);

If we are not returning from the individual listings and the listingUrls array is empty, we must be on a new listing page. The scraper calls parseLinks() to discover the listing URLs and remembers the current page.

On subsequent page loads, the array is no longer empty, so the scraper knows that it is currently processing one of the individual listings. It therefore calls parseListing().

This is a particularly useful part of the design. The scraper does not need a complicated external crawler queue to know what it should be doing. The state stored in local storage tells it where it is in the process.

Moving Through the Listings

scraper.listingUrlIndex++;
setScraper(scraper);
if (scraper.listingUrlIndex == scraper.listingUrls.length) {
    scraper.listingUrls = [];
    scraper.listingUrlIndex = -1;
    localStorage.setItem("scraper", JSON.stringify(scraper));
    await sleep(DELAY);
    location.href = scraper.currentPage;
} else {
    await sleep(DELAY);
    location.href = scraper.listingUrls[scraper.listingUrlIndex]
}

After processing a listing, listingUrlIndex is incremented and the updated state is saved.

If the index has reached the end of the URL array, the scraper has finished all listings from the current page. It clears the URL list, resets the index, waits for the configured delay, and returns to currentPage.

If there are still URLs left, the scraper waits and navigates directly to the next listing URL.

The Browser as the Crawler

This is the key difference between this implementation and the Scrapy example. In Scrapy, the framework manages requests, responses, and the crawling queue. Here, the browser itself performs the navigation.

Every time location.href changes, the current page is left and a new page loads. The extension's content scripts are injected again, crawl() runs again, and the scraper reads its state from local storage to determine what should happen next.

In other words, page navigation becomes part of the crawler's control flow. The browser repeatedly loads pages, while local storage allows the scraper to remember what happened before the current page was loaded.

The Complete Loop

Listing page → discover listing URLs → save state → open listing → extract data → move to next listing → return to listing page → move to next listing page → repeat.

That loop is the core of our browser-based scraper. Everything we have built around it — the popup, configuration, selectors, visual interface, and storage management — exists to make this loop configurable and practical to use.