Example Listing Scraper
We now have enough background to build a small browser-based scraper and see how the ideas we have discussed fit together. Before looking at the code, however, let's return to the structure we introduced earlier.
Think back to the listing website model we introduced earlier: a listing page contains links to multiple individual listings, and each individual listing page contains the data we want to extract. Our scraper first discovers the listing URLs, then visits those URLs one by one and extracts the data from each listing.
This simple structure was the foundation of the Scrapy example. The interesting part is that we can use exactly the same mental model inside the browser.
From Scrapy to the Browser
In our Python Scrapy scraper, start_requests() opened the initial listing page, parse_links() discovered the individual listing URLs, and parse_listing() extracted the data from each listing. Pagination then moved the scraper to the next listing page and the process repeated.
Our browser-based implementation follows the same flow, but instead of a crawler framework managing requests and responses, the browser itself navigates between pages.
parseLinks()corresponds to the Scrapyparse_links()function and collects the URLs of individual listings.parseListing()corresponds to the Scrapyparse_listing()function and extracts the data from an individual listing.listingUrlsstores the URLs discovered on the current listing page.listingUrlIndexkeeps track of which listing URL we are currently processing.currentPageremembers the listing page so that we can return to it after processing its listings.datastores the extracted results.location.hrefreplaces the request/navigation mechanism that Scrapy normally provides.
The important point is that the underlying scraping algorithm has not really changed. We have moved the same basic workflow from an external Python crawler into JavaScript running inside the browser.
The Example
The following example is a simplified Chrome extension scraper targeting a real estate listing website. It demonstrates the complete basic crawling loop: creating scraper state, discovering listing URLs, visiting individual listings, extracting data, returning to the listing page, moving to the next page, and finally downloading the collected data.
/*
A Chrome extension to scrape data from
https://www.idealista.com/
*/
// Request delay constant
const DELAY = 5000;
// UI message handler
chrome.runtime.onMessage.addListener((message) => {
// Get scraper status
if (message.action == "status") {
// Load scraper storage if available
let scraperStorage = JSON.parse(localStorage.getItem("scraper"));
// Scraper storage doesn't exist
if (scraperStorage == null) alert("Scraper storage doesn't exist");
// Show current scraper status
else alert("Scraper " + (scraperStorage.running ? "is" : "is not") + " running");
}
// Create scraper storage
else if (message.action == "create") {
// Load scraper storage if available
let scraperStorage = JSON.parse(localStorage.getItem("scraper"));
// Create scraper storage instance if needed
if (scraperStorage == null) {
localStorage.setItem("scraper", JSON.stringify({
"running": false,
"currentPage": "",
"listingUrls": [],
"listingUrlIndex": -1,
"data": []
}));
alert("Scraper storage has been created");
}
// Scraper storage exists
else alert("Scraper storage already exists");
}
// Clear scraper storage
else if (message.action == "remove") {
// Load scraper storage if available
let scraperStorage = JSON.parse(localStorage.getItem("scraper"));
// Scraper storage doesn't exist
if (scraperStorage == null) alert("Scraper storage doesn't exist");
// Remove scraper storage
else {
localStorage.removeItem("scraper");
alert("Scraper storage has been removed");
}
}
// Start scraper
else if (message.action == "start") {
// Load scraper storage if available
let scraperStorage = JSON.parse(localStorage.getItem("scraper"));
// Scraper storage doesn't exist
if (scraperStorage == null) alert("Scraper storage doesn't exist");
// Already running
else if (scraperStorage.running == true) alert("Scraper is running");
// Start scraper
else {
scraperStorage.running = true;
localStorage.setItem("scraper", JSON.stringify(scraperStorage));
alert("Scraper has been started");
location.reload();
}
}
// Stop scraper
else if (message.action == "stop") {
// Load scraper storage if available
let scraperStorage = JSON.parse(localStorage.getItem("scraper"));
// Scraper storage doesn't exist
if (scraperStorage == null) alert("Scraper storage doesn't exist");
// Already stopped
else if (scraperStorage.running == false) alert("Scraper is not running");
// Start scraper
else {
scraperStorage.running = false;
localStorage.setItem("scraper", JSON.stringify(scraperStorage));
alert("Scraper has been stopped");
}
}
// Download scraped data
else if (message.action == "download") {
// Load scraper storage if available
let scraperStorage = JSON.parse(localStorage.getItem("scraper"));
// Scraper storage doesn't exist
if (scraperStorage == null) alert("Scraper storage doesn't exist");
// Extract scraped data from local browser storage
else {
let data = JSON.parse(localStorage.getItem("scraper")).data;
// Create data blob
const blob = new Blob(
[JSON.stringify(data, null, 2)],
{ type: "text/json;charset=utf-8" }
);
// Create URL
const url = URL.createObjectURL(blob);
// Create download link
const link = document.createElement("a");
link.href = url;
link.download = "data_" + Date().toString().split(" ").slice(0, 5) + ".json";
// "Click" download URL
link.click();
// Clear download URL
URL.revokeObjectURL(url);
}
}
});
// Extract useful data from target HTML page
function parseLinks(scraperStorage) {
let linkSelectors = document.getElementsByClassName("item-link");
for (let link of linkSelectors) scraperStorage.listingUrls.push(link.href);
}
// Navigate to the next listing URL
function parseListing(scraperStorage) {
try {
// Extract features
let features = [];
let featureSelector = document.getElementsByClassName("details-property_features");
// Loop over features
for (let div of featureSelector) {
for (let ul of div.children) {
for (let li of ul.children) {
// Collect features
features.push(li.textContent.trim().replace("\n", ""));
}
}
}
// Extract listing data
let data = {
"url": location.href,
"title": document.getElementsByClassName("main-info__title-main")[0].innerHTML,
"price": document.getElementsByClassName("info-data-price")[0].children[0].innerHTML,
"features": features,
"description": document.getElementsByClassName("comment")[0].textContent.trim().replaceAll("\n", ""),
}
// Log extracted data to console
console.log(JSON.stringify(data, null, 2))
console.log("\nCurrent page:", scraperStorage.currentPage);
// Save listing to the browser local storage
scraperStorage.data.push(data)
} catch(e) {}
}
// Wait before going to the next page
async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Crawl through URLs
(async () => {
// Load scraper storage if available
let scraperStorage = JSON.parse(localStorage.getItem("scraper"));
// Do nothing if no scrape storage available
if (scraperStorage == null) return;
else if (scraperStorage.running) {
// We are done crawling all listings on this page
if (scraperStorage.currentPage == location.href) {
// Go to the next page
scraperStorage.currentPage = "";
location.href = document.getElementsByClassName("icon-arrow-right-after")[0].href
return;
}
// We just landed on a page
if (scraperStorage.listingUrls.length == 0) {
// Get the list of listing URLs
parseLinks(scraperStorage);
// Store current page to back to it later
scraperStorage.currentPage = location.href;
// Update scraper storage state in local browser storage
localStorage.setItem("scraper", JSON.stringify(scraperStorage));
}
// We are crawling through listing URLs within the current page
else parseListing(scraperStorage);
// Update URL index
scraperStorage.listingUrlIndex++;
// Update scraper storage state in local browser storage
localStorage.setItem("scraper", JSON.stringify(scraperStorage));
// If no more URLs to crawl
if (scraperStorage.listingUrlIndex == scraperStorage.listingUrls.length) {
// Reset listing URL list
scraperStorage.listingUrls = [];
scraperStorage.listingUrlIndex = -1;
// Update scraper storage state in local browser storage
localStorage.setItem("scraper", JSON.stringify(scraperStorage));
// Wait for a while
await sleep(DELAY);
// Go to the next page
location.href = scraperStorage.currentPage;
}
// Otherwise we crawl through listings on current page
else {
// Wait for a while
await sleep(DELAY);
// Navigate to listing URL
location.href = scraperStorage.listingUrls[scraperStorage.listingUrlIndex]
}
}
})();
Following the Scraping Loop
When the scraper is started, it first loads its state from local storage. If the scraper is on a listing page and no listing URLs have been collected yet, parseLinks() finds the links to the individual listings and stores them in listingUrls.
The scraper then remembers the current listing page in currentPage. This is important because it will temporarily leave that page while visiting each individual listing.
It then navigates to the first URL in listingUrls. When the individual listing page loads, parseListing() extracts the fields we are interested in and adds the resulting object to data.
The listingUrlIndex is then incremented and the scraper navigates to the next listing. This continues until every listing URL from the current page has been processed.
Once the list is exhausted, the scraper clears listingUrls, resets listingUrlIndex, waits for the configured delay, and returns to currentPage. Once back on the listing page, it follows the pagination link and begins the same process again.
This is essentially the same workflow as our earlier Scrapy scraper. The major difference is that the browser is now responsible for navigation and page loading, while local storage keeps track of the crawler's state between page loads.
A Simplified Example
There are a few important things to keep in mind about this code. It is intentionally a simplified example rather than the final scraper extension we are going to build.
For example, we have omitted the UI buttons that would allow a user to create storage, start and stop the scraper, remove its state, and download the collected data. We have also omitted the middleware code responsible for communicating between the scraper and the target page.
The selectors in this example are also hard-coded specifically for the target website. A useful general-purpose scraper cannot require us to modify JavaScript every time we want to scrape a different website.
Those limitations are intentional. At this point, we are interested in understanding the fundamental structure of a browser-based scraper, not in building the complete user interface or configuration system.
We have now seen that the listing-page → listing-URL → individual-listing → extracted-data model works just as well inside the browser as it does in a traditional scraping framework.
From Example to Full Extension
Now that we understand what the basic scraper looks like and how it operates in a browser environment, we can start adding the more general pieces that turn this example into a reusable scraping tool.
We will build a user interface for controlling the scraper state, visual selectors that allow us to configure what should be extracted without writing selectors by hand, and storage housekeeping for managing the scraper's configuration, progress, and collected data.
These components are not just optional conveniences. Together they form the main core of the approach presented in this book. From this point forward, we will move away from the hard-coded example and begin building the full Chrome extension.