<h2>Getting Started</h2>
<p>
To get started with WebScraper Pro, clone the repository and follow the installation instructions in the
<code>README.md</code>. Once set up, you can customize your scraping tasks by configuring the URLs and specifying the
selectors or regex patterns you need.
</p>
<p>
WebScraper Pro is the perfect choice for developers, analysts, and researchers looking to automate data collection
and streamline their workflow. Contribute to this project by submitting pull requests and stay tuned for future updates!
</p>
<div>Icons Attribution:</div>
<ul>
<li>Multiply by Kozan from <a href="https://thenounproject.com/browse/icons/term/multiply/"
target="_blank" title="multiply Icons">Noun Project</a> (CC BY
3.0)
</li>
<li>Multiply by Sunisih from <a href="https://thenounproject.com/browse/icons/term/multiply/"
target="_blank" title="multiply Icons">Noun Project</a> (CC BY
3.0)
</li>
<li>Eye by Fahmi Ramdani from <a href="https://thenounproject.com/browse/icons/term/eye/"
target="_blank" title="Eye Icons">Noun Project</a> (CC BY
3.0)</li>
<li>add by Elin Erkani from <a href="https://thenounproject.com/browse/icons/term/add/"
target="_blank" title="add Icons">Noun Project</a> (CC BY
3.0)</li>
<li>clear by iconmas from <a href="https://thenounproject.com/browse/icons/term/clear/"
target="_blank" title="clear Icons">Noun Project</a> (CC BY
3.0)</li>
</ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
const recordsKey = 'scrapeRecords';
const autoFetchKey = 'autoFetch';
const maxResultLength = 50;
document.addEventListener('DOMContentLoaded', () => {
const autoFetchState = localStorage.getItem(autoFetchKey);
const autoFetch = (autoFetchState === 'true');
const autoFetchSwitch = document.getElementById('auto-fetch-switch');
autoFetchSwitch.checked = autoFetch;
loadRecords(autoFetch);
});
function exportData() {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
const blob = new Blob([JSON.stringify(records)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'scrape_records.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
function importData(event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function (evt) {
const data = JSON.parse(evt.target.result);
localStorage.setItem(recordsKey, JSON.stringify(data));
document.location.reload();
};
reader.readAsText(file);
}
function toggleAutoFetch(isEnabled) {
localStorage.setItem(autoFetchKey, isEnabled);
if (isEnabled) {
executeAllRecords();
}
}
function loadRecords(autoFetch) {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.forEach((record, index) => {
addTableRow(record, index);
if (autoFetch) {
executeRecord(index);
}
});
}
function addTableRow({ name, url, selector, isRegex, result, debugInfo }, index) {
const tableBody = document.getElementById('scrape-table-body');
const row = document.createElement('tr');
row.innerHTML = `
<td><input type="text" value="${escapeHtml(name)}" onchange="updateRecord(${index}, 'name', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td><input type="text" value="${escapeHtml(url)}" onchange="updateRecord(${index}, 'url', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td><input type="text" value="${escapeHtml(selector)}" onchange="updateRecord(${index}, 'selector', this.value)" onkeydown="checkEnter(event, ${index})"></td>
<td>
<label class="regex-switch">
<input type="checkbox" id="regex-${index}" onchange="updateRecord(${index}, 'isRegex', this.checked)" ${isRegex ? 'checked' : ''}>
<span class="slider"></span>
</label>
</td>
<td id="result-${index}">${escapeHtml(result || '')}</td>
<td>
<button class="icon-button" onclick="executeRecord(${index})">
<img src="media/run.png" alt="Run">
</button>
<button class="icon-button button-spacing" onclick="toggleDebugPanel(${index}, false)">
<img src="media/info.png" alt="Info">
</button>
<button class="icon-button" onclick="removeRecord(${index})">
<img src="media/delete.png" alt="Delete">
</button>
</td>
`;
tableBody.insertBefore(row, tableBody.lastElementChild);
}
function checkEnter(event, index) {
if (event.key === 'Enter') {
updateRecord(index, 'result', '');
executeRecord(index);
}
}
function addNewRecord() {
const name = document.getElementById('new-name').value.trim();
const url = document.getElementById('new-url').value.trim();
const selector = document.getElementById('new-selector').value.trim();
const isRegex = document.getElementById('new-regex').checked;
if (!name || !url || !selector) {
alert('All fields are required!');
return;
}
const record = { name, url, selector, isRegex, result: '', debugInfo: {} };
let records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.push(record);
localStorage.setItem(recordsKey, JSON.stringify(records));
const index = records.length - 1;
addTableRow(record, index);
executeRecord(index);
document.getElementById('new-name').value = '';
document.getElementById('new-url').value = '';
document.getElementById('new-selector').value = '';
document.getElementById('new-regex').checked = false;
}
function executeRecord(index) {
const records = JSON.parse(localStorage.getItem(recordsKey));
const record = records[index];
document.getElementById(`result-${index}`).textContent = '⏳';
executeScraping(record.url, record.selector, record.isRegex, index);
}
function executeScraping(url, selector, isRegex, index) {
const proxy = 'https://cors-anywhere.herokuapp.com/';
const options = {
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'Accept-Language': 'en-US,en;q=0.9'
}
};
axios.get(proxy + url, options)
.then(response => {
const fetchedData = response.data;
let resultText = 'No matches';
if (isRegex) {
try {
const regex = new RegExp(selector);
const match = regex.exec(fetchedData);
resultText = match ? match[0] : 'No matches';
} catch (e) {
console.error('Invalid regex:', e);
resultText = 'Invalid regex';
}
} else {
const parser = new DOMParser();
const doc = parser.parseFromString(fetchedData, 'text/html');
const resultElement = doc.querySelector(selector);
resultText = resultElement ? resultElement.textContent.trim() : 'No matches';
}
document.getElementById(`result-${index}`).textContent = resultText.substring(0, maxResultLength) + (resultText.length > maxResultLength ? '...' : '');
const records = JSON.parse(localStorage.getItem(recordsKey));
records[index].result = resultText;
records[index].debugInfo = {
html: fetchedData,
timestamp: new Date().toISOString()
};
localStorage.setItem(recordsKey, JSON.stringify(records));
})
.catch(error => {
console.error(`Error fetching the URL: ${url}`, error);
document.getElementById(`result-${index}`).textContent = 'Error occurred';
const records = JSON.parse(localStorage.getItem(recordsKey));
records[index].result = 'Error occurred';
records[index].debugInfo = {
error: error.toString(),
timestamp: new Date().toISOString()
};
localStorage.setItem(recordsKey, JSON.stringify(records));
});
}
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();
}
function toggleDebugPanel(index, close = false) {
const debugPanel = document.getElementById('debug-panel');
const debugContent = document.getElementById('debug-content');
const overlay = document.getElementById('overlay');
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
if (close || index === null) {
debugPanel.style.display = 'none';
overlay.style.display = 'none';
debugContent.innerHTML = '';
return;
}
const debugInfo = records[index].debugInfo;
if (debugInfo) {
debugContent.innerHTML = `<strong>Timestamp:</strong> ${debugInfo.timestamp}<br><br>
<strong>HTML:</strong><pre>${escapeHtml(debugInfo.html || '')}</pre>
<strong>Error:</strong> ${debugInfo.error || 'None'}`;
} else {
debugContent.innerHTML = 'No debug information available';
}
debugPanel.style.display = 'block';
overlay.style.display = 'block';
}
function toggleAboutPanel(close = false) {
const aboutPanel = document.getElementById('about-panel');
const overlay = document.getElementById('overlay');
if (close) {
aboutPanel.style.display = 'none';
overlay.style.display = 'none';
return;
}
aboutPanel.style.display = 'block';
overlay.style.display = 'block';
}
function closePanels() {
toggleDebugPanel(null, true);
toggleAboutPanel(true);
}
function escapeHtml(text) {
if (typeof text !== "string") return '';
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}
function executeAllRecords() {
const records = JSON.parse(localStorage.getItem(recordsKey)) || [];
records.forEach((_, index) => {
executeRecord(index);
});
}
function clearAllRecords() {
if (confirm('Are you sure you want to clear all records? This action cannot be undone.')) {
localStorage.removeItem(recordsKey);
document.getElementById('scrape-table-body').innerHTML = `
<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 or Regex"></td>
<td>
<label class="regex-switch">
<input type="checkbox" id="new-regex">
<span class="slider"></span>
</label>
</td>
<td colspan="2"><button class="add-icon-button" onclick="addNewRecord()"><img src="media/add.png" alt="Add"></button></td>
</tr>
`;
}
}
</script>
Certainly! Here is the project specification in a code block format for easy copying:
## Project Specification: Web Scraping Tool Generator
### Objective
Develop an HTML and JavaScript-based web application for a web scraping tool, capable of extracting data from web pages using CSS selectors or regular expressions. The tool should manage and store user records, handle data import/export, and provide an easy-to-use interface with auto-fetch capabilities.
### Features
1. **Responsive Structure**
- Use `HTML` to structure the webpage.
- Ensure the page is responsive using CSS Flexbox layout.
2. **Styling**
- Apply `CSS` for basic styling with a neumorphic design theme using box-shadow and color gradients.
- Use a neutral color palette with shades of gray (e.g., `#e0e0e0`, `#bebebe`, `#ffffff`).
- Interactive elements like buttons and inputs should have hover and focus styles.
3. **Data Table**
- Include a dynamic HTML table to display stored scraping records.
- Each row represents a record with fields: Name, URL, Selector/Regex, Use Regex, and Results.
- New records can be added via an input row at the end of the table.
4. **Data Management**
- Implement JavaScript for managing records in `localStorage`.
- Include functionality to save, update, and delete records.
5. **Data Import/Export**
- Users should be able to export data as a JSON file and import it back.
- Use `FileReader` API for handling file imports.
6. **Functionality**
- The tool should be able to fetch data from user-specified URLs.
- Use `Axios` for making HTTP requests.
- Optionally use the CORS-anywhere proxy to handle CORS issues.
- Implement data extraction using either CSS selectors or regular expressions.
7. **User Interface Elements**
- Add toggle switches for features like auto-fetch and using regex.
- Include icon buttons for exporting data, clearing records, and accessing an "About" panel.
8. **Panels**
- Include an "About" panel with information about the tool.
- Implement a debug panel that displays details about fetch operations.
- Overlay function for both panels with close functionality.
9. **Dynamic Script Execution**
- When a record is executed, fetch the specified URL and parse the response.
- Display extraction results and manage errors gracefully.
- Support CSS selector extraction by parsing fetched HTML with the DOMParser.
10. **Icons and Images**
- Include icons for various buttons, with attributions for icon sources.
### Technical Requirements
- Use `localStorage` to manage user data persistence.
- Use the `DOMContentLoaded` event to initialize page state.
- Provide feedback for each scraping operation, including results or error messages.
- Allow user-interaction through dynamic form inputs and actionable buttons.
### Instructions
- Describe the implementation logic in human-readable terms for each feature above.
- Use vanilla JavaScript for DOM manipulation and event handling.
- Utilize external libraries like Axios for HTTP requests.