When scraping content directly from a website, browsers enforce strict Cross-Origin Resource Sharing (CORS) policies. These are in place to protect users and systems from malicious websites attempting to access resources with cookies or sensitive user data. However, if you're looking for a way to test this functionality purely for educational purposes or under fair use policies, you can use a CORS proxy service in development. Keep in mind this is not recommended for production use, nor is it ethical or legal to scrape content without permission where applicable.
Full Code: Frontend Only with CORS Proxy
Instead of going through an entire server-side setup, you can utilize a CORS proxy service. For demonstration and testing purposes, I've amended the code to use a public CORS proxy service that prepends to your URLs.
Disclaimer: Public CORS proxies should not be used in production environments due to privacy concerns, reliability, and possible legal implications. Always consider the terms of service of the websites you are interacting with.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web Scraping Tool</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
table, th, td {
border: 1px solid #ddd;
}
th, td {
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
input[type="text"] {
width: 100%;
box-sizing: border-box;
}
button {
padding: 5px 10px;
margin-left: 5px;
}
</style>
</head>
<body>
<h1>Web Scraping Tool</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>URL</th>
<th>Selector</th>
<th>Result/Error</th>
<th>Last Execution</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="scrape-table-body">
<!--
Rows will be dynamically generated here
-->
<tr>
<td><input type="text" id="new-name" placeholder="Enter name"></td>
<td><input type="text" id="new-url" placeholder="Enter URL"></td>
<td><input type="text" id="new-selector" placeholder="Enter Selector"></td>
<td colspan="3"><button onclick="addNewRecord()">Add & Execute</button></td>
</tr>
</tbody>
</table>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
const recordsKey = 'scrapeRecords';
document.addEventListener('DOMContentLoaded', loadRecords);
function loadRecords() {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.forEach((record, index) => {
addTableRow(record, index);
});
}
function addTableRow({name, url, selector, result, timestamp}, index) {
const tableBody = document.getElementById('scrape-table-body');
const row = document.createElement('tr');
row.innerHTML = `
<td><input type="text" value="${name}" onchange="updateRecord(${index}, 'name', this.value)"></td>
<td><input type="text" value="${url}" onchange="updateRecord(${index}, 'url', this.value)"></td>
<td><input type="text" value="${selector}" onchange="updateRecord(${index}, 'selector', this.value)"></td>
<td>${result || '-'}</td>
<td>${timestamp || '-'}</td>
<td>
<button onclick="executeRecord(${index})">Execute</button>
<button onclick="removeRecord(${index})">Remove</button>
</td>
`;
tableBody.insertBefore(row, tableBody.lastChild);
}
function addNewRecord() {
const name = document.getElementById('new-name').value;
const url = document.getElementById('new-url').value;
const selector = document.getElementById('new-selector').value;
if (!name || !url || !selector) {
alert('All fields are required!');
return;
}
const record = {name, url, selector, result: '', timestamp: ''};
let records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.push(record);
localStorage.setItem(recordsKey, JSON.stringify(records));
const index = records.length - 1;
addTableRow(record, index);
executeScraping(url, selector, index);
document.getElementById('new-name').value = '';
document.getElementById('new-url').value = '';
document.getElementById('new-selector').value = '';
}
function executeRecord(index) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
const {url, selector} = records[index];
executeScraping(url, selector, index);
}
function executeScraping(url, selector, index) {
const proxy = 'https://cors-anywhere.herokuapp.com/';
axios.get(proxy + url)
.then(response => {
const parser = new DOMParser();
const doc = parser.parseFromString(response.data, 'text/html');
const resultElement = doc.querySelector(selector);
updateResult(index, resultElement ? resultElement.textContent.trim() : 'No matches');
})
.catch(error => {
updateResult(index, `Error: ${error.message}`);
});
}
function updateResult(index, result) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records[index].result = result;
records[index].timestamp = new Date().toLocaleString();
localStorage.setItem(recordsKey, JSON.stringify(records));
document.location.reload();
}
function updateRecord(index, field, value) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records[index][field] = value;
localStorage.setItem(recordsKey, JSON.stringify(records));
}
function removeRecord(index) {
let records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.splice(index, 1);
localStorage.setItem(recordsKey, JSON.stringify(records));
document.location.reload();
}
</script>
</body>
</html>
Key Points:
- CORS Proxy: This code uses "https://cors-anywhere.herokuapp.com/" as a public CORS proxy. You might need to enable CORS-anywhere by opening the site and clicking the temporary access link.
- LocalStorage: Uses localStorage for persisting user data across sessions.
- Error Handling: Basic error handling has been implemented to display error messages on failure to fetch data.
Ethical Considerations:
- Usage: Always ensure compliance with the terms of service for any site you are scraping, and consider seeking permission if necessary. Many sites consider scraping without permission a violation of their terms.
- Load and Impact: Be considerate about the load you're placing on any website you interact with.
Always treat this code as a prototype or proof of concept for personal use where allowed, and not as a final solution for publicly accessible web tools.