Creating a backend service for web scraping can be done using various programming languages and libraries. Considering simplicity and your request for either Python or JavaScript, I will demonstrate a basic example using Node.js with the express, axios, and cheerio libraries for the backend server, which are popular and well-suited for this task.
First, you need to set up the backend directory. Inside your project directory, create a new folder (server or similar) and initialize a new Node.js project:
mkdir server
cd server
npm init -y
Then, install the required dependencies:
npm install express axios cheerio tar-fs rimraf --save
Now, create a file called server.js inside the server directory:
// server.js
const express = require('express');
const axios = require('axios');
const cheerio = require('cheerio');
const tar = require('tar-fs');
const rimraf = require('rimraf');
const fs = require('fs');
const path = require('path');
const app = express();
const port = 5000; // Backend server port
app.use(express.json());
app.post('/scrape', async (req, res) => {
const { url } = req.body;
if(!url) {
return res.status(400).send('URL is required');
}
try {
// Fetch the HTML from the provided URL
const response = await axios.get(url);
const html = response.data;
const $ = cheerio.load(html);
// Create a temporary directory to store images and text
const tempDir = `temp-${Date.now()}`;
fs.mkdirSync(tempDir);
// Extract and save the text content
const textContent = $('body').text();
fs.writeFileSync(`${tempDir}/content.txt`, textContent.trim(), 'utf-8');
// TODO: Extract and download images, save to tempDir
// Create a tar.gz archive of the tempDir
const tarPath = `${tempDir}.tar.gz`;
await new Promise(resolve => {
tar.pack(`./${tempDir}`)
.pipe(fs.createWriteStream(tarPath))
.on('finish', resolve);
});
// Send the tar.gz archive
res.download(tarPath, (err) => {
// Clean up: remove the temporary directory and tar file
rimraf.sync(`./${tempDir}`);
fs.unlinkSync(tarPath);
});
} catch (error) {
console.error(error);
res.status(500).send('An error occurred while scraping the website');
}
});
app.listen(port, () => console.log(`Server is running on port ${port}`));
In the given server.js:
- An Express app is created with a single endpoint
/scrape that accepts POST requests with JSON body containing the URL to be scraped.
- The URL is fetched, and the HTML is processed with Cheerio to extract text content.
- The content is then saved into a temporary directory, which is then archived into a
tar.gz file using tar-fs.
- The archive is sent back to the client and the temporary files are cleaned up after the download.
To run the backend server, from the server directory, execute:
node server.js
In the React app, you would make a POST request to this backend endpoint with the website URL. Here's an example of how to modify the handleScrape function:
// Add this function inside your App component.
const handleScrape = async (e) => {
e.preventDefault();
try {
const response = await fetch('http://localhost:5000/scrape', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ url }),
});
if (response.ok) {
const blob = await response.blob();
const downloadUrl = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = downloadUrl;
link.setAttribute('download', 'website-content.tar.gz');
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
} else {
console.error('Server responded with an error');
}
} catch (error) {
console.error('An error occurred during the scrape:', error);
}
};
Please complete the TODO part for the images extraction on the backend by writing a function that finds image URLs and downloads them into the temporary directory created for each scraping operation.
Don't forget to set the appropriate CORS headers or use a proxy to avoid CORS issues during development.
This tutorial provides only a basic starting point and is not a robust or production-ready application. You must respect the target website's robots.txt rules and ensure you are legally allowed to scrape it. If you plan to scrape a large number of pages or require more advanced features, consider additional error handling, rate limiting, and adhering to concurrency best practices.