Ahora ni siquiera extrae las imágenes, mira el código:
const extractDescription = (doc) => {
// Selector más robusto y flexible
const descriptionContainer = doc.querySelector('.mk-products-desc div ul') ||
doc.querySelector('.mk-products-desc .mk-products-desc div');
if (descriptionContainer) {
const listItems = descriptionContainer.querySelectorAll('li, p');
const descriptionPoints = Array.from(listItems)
.map(li => li.textContent.trim())
.filter(text => text.length > 0) // Filtrar elementos vacíos
.join('; ');
return descriptionPoints ? [descriptionPoints] : ['N/A'];
}
return ['N/A'];
};
const extractManufacturer = (doc) => {
const manufacturerSpan = doc.querySelector('#mkjs-product-profile');
if (manufacturerSpan) {
const manufacturerText = manufacturerSpan.textContent.trim();
return [manufacturerText];
}
return ['N/A'];
};
const extractAdditionalParameters = (doc) => {
const miniTable = doc.querySelector('.enf-pd-profile-mini-table');
if (!miniTable) {
return {
type: ['N/A'],
powerRange: ['N/A'],
region: ['N/A']
};
}
// Función auxiliar para extraer el valor de una fila específica
const extractRowValue = (rowText) => {
const row = Array.from(miniTable.querySelectorAll('tr')).find(tr =>
tr.querySelector('th')?.textContent.trim().toLowerCase().includes(rowText.toLowerCase())
);
if (row) {
const td = row.querySelector('td');
// Eliminar cualquier imagen o elemento adicional
const cleanText = td.textContent.trim().replace(/\n.*/, '').trim();
return [cleanText || 'N/A'];
}
return ['N/A'];
};
return {
type: extractRowValue('Type'),
powerRange: extractRowValue('Power Range'),
region: extractRowValue('Region')
};
};
// Función para extraer URLs de imágenes (fuera de la clase)
const extractImageUrls = (doc) => {
try {
const multiImageContainer = doc.querySelector('.mk-imgs-box');
if (multiImageContainer) {
const imagePanels = multiImageContainer.querySelectorAll('.tab-pane');
const imageUrls = Array.from(imagePanels).map(panel => {
const img = panel.querySelector('.mk-imgs img');
if (img) {
return {
simpleUrl: img.getAttribute('src') || 'N/A',
fullImageUrl: img.getAttribute('data-imagezoom') || 'N/A'
};
}
return { simpleUrl: 'N/A', fullImageUrl: 'N/A' };
});
return imageUrls; // Devuelve un array con todas las imágenes encontradas
}
// Caso de imagen única
const singleImageContainer = doc.querySelector('.mk-imgs img');
if (singleImageContainer) {
return [{
simpleUrl: singleImageContainer.getAttribute('src') || 'N/A',
fullImageUrl: singleImageContainer.getAttribute('data-imagezoom') || 'N/A'
}];
}
// Si no se encuentran imágenes
return [];
} catch (error) {
logger.log(`Error al extraer imágenes: ${error.message}`, 'error');
return [];
}
};
const extractPriceRange = (doc) => {
try {
const priceContainer = doc.querySelector('.mk-price-body');
if (!priceContainer) {
return ['N/A'];
}
const priceElements = priceContainer.querySelectorAll('.yellow, .price-item');
const extractedPrices = [];
priceElements.forEach(element => {
const fullText = element.textContent.trim();
const priceRegex = /From\s*(€[0-9.,]+)\s*\/\s*(Wp|Unit)/i;
const match = fullText.match(priceRegex);
if (match) {
const price = match[1];
const unit = match[2];
extractedPrices.push(`${price} / ${unit}`);
}
});
return extractedPrices.length > 0
? [extractedPrices.join('; ')]
: ['N/A'];
} catch (error) {
return ['N/A'];
}
};
const extractManufacturerPDF = (doc) => {
const pdfLink = doc.querySelector('.download_pdf_btn.mkjs-a');
if (pdfLink) {
const href = pdfLink.getAttribute('href');
return href ? [href] : ['N/A'];
}
return ['N/A'];
};
const extractManufacturerDetails = (doc) => {
const addressContainer = doc.querySelector('.mk-addresses .dl-horizontal');
if (!addressContainer) {
return {
ManufacturerTelephone: ['N/A'],
ManufacturerURL: ['N/A'],
ManufacturerCountry: ['N/A'],
ManufacturerAddress: ['N/A']
};
}
// Extraer teléfono
const telephoneElement = Array.from(addressContainer.querySelectorAll('dd'))
.find(dd => dd.previousElementSibling?.querySelector('.glyphicon-earphone'));
const ManufacturerTelephone = telephoneElement
? [telephoneElement.textContent.trim()]
: ['N/A'];
// Extraer URL
const urlElement = addressContainer.querySelector('dd a[href^="http"]');
const ManufacturerURL = urlElement
? [urlElement.textContent.trim()]
: ['N/A'];
// Extraer país
const countryElement = Array.from(addressContainer.querySelectorAll('dd'))
.find(dd => dd.querySelector('.enf-flag'));
const ManufacturerCountry = countryElement
? [countryElement.textContent.trim().replace(/\s*\n.*/, '')]
: ['N/A'];
// Extraer dirección
const addressElement = Array.from(addressContainer.querySelectorAll('dd'))
.find(dd => dd.previousElementSibling?.querySelector('.glyphicon-map-marker'));
const ManufacturerAddress = addressElement
? [addressElement.textContent.trim()]
: ['N/A'];
return {
ManufacturerTelephone,
ManufacturerURL,
ManufacturerCountry,
ManufacturerAddress
};
};
// Logger
// En tu archivo de logger
// Logger
class Logger {
constructor() {
this.logContainer = document.getElementById('logContainer');
if (!this.logContainer) {
this.logContainer = document.createElement('div');
this.logContainer.id = 'logContainer';
document.body.appendChild(this.logContainer);
}
this.logs = [];
}
log(message, type = 'info') {
if (!this.logContainer) {
console.error('Log container no encontrado');
return;
}
const logEntry = document.createElement('div');
logEntry.classList.add('log-entry', type);
logEntry.textContent = `[${new Date().toLocaleString()}] ${message}`;
this.logContainer.appendChild(logEntry);
this.logs.push({ message, type, timestamp: new Date() });
this.logContainer.scrollTop = this.logContainer.scrollHeight;
}
exportLogs() {
if (this.logs.length === 0) {
this.log('No hay logs para exportar', 'warning');
return;
}
const logsText = this.logs.map(log =>
`[${log.timestamp.toLocaleString()}] [${log.type}] ${log.message}`
).join('\n');
const blob = new Blob([logsText], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `logs_${new Date().toISOString().replace(/:/g, '-')}.txt`;
a.click();
URL.revokeObjectURL(url);
}
clear() {
if (this.logContainer) {
this.logContainer.innerHTML = '';
}
this.logs = [];
}
}
// Crear una instancia global
window.logger = new Logger();
// Configuración y Constantes
const CONFIG = {
BASE_URL: 'https://www.enfsolar.com/pv/inverter',
API_ENDPOINT: 'https://wavesunpv.com/insertinverter1669.php',
ENCRYPTION_SALT: 'solar_inverter_2024',
MIN_PAGE: 1,
MAX_PAGE: 100,
CONCURRENT_REQUESTS: 5,
MIN_POWER_THRESHOLD: 1,
BRAND_WHITELIST: ['SMA', 'Fronius', 'SolarEdge', 'Huawei']
};
// Gestor de Solicitudes
class RequestManager {
constructor(maxConcurrent = CONFIG.CONCURRENT_REQUESTS) {
this.queue = [];
this.running = 0;
this.maxConcurrent = maxConcurrent;
}
async enqueue(requestFn) {
return new Promise((resolve, reject) => {
this.queue.push({ requestFn, resolve, reject });
this.processQueue();
});
}
async processQueue() {
while (this.queue.length > 0 && this.running < this.maxConcurrent) {
const request = this.queue.shift();
this.running++;
try {
const result = await request.requestFn();
request.resolve(result);
} catch (error) {
request.reject(error);
logger.log(`Request failed: ${error}`, 'error');
} finally {
this.running--;
this.processQueue();
}
}
}
}
// Clase Principal de Scraping
class SolarInverterScraper {
constructor() {
this.requestManager = new RequestManager();
this.scrapedData = [];
this.isRunning = false;
this.isPaused = false;
this.urlMin = CONFIG.MIN_PAGE;
this.urlMax = CONFIG.MAX_PAGE;
this.currentPage = this.urlMin;
}
async initializeScraping() {
logger.log('Iniciando scraping de inversores solares', 'info');
this.isRunning = true;
const progressBar = document.getElementById('scraperProgress');
const statusText = document.getElementById('texto2');
const percentageText = document.getElementById('texto3');
try {
for (let page = this.urlMin; page <= this.urlMax; page++) {
if (!this.isRunning) break;
if (this.isPaused) {
await this.waitForResume();
}
this.currentPage = page;
statusText.innerHTML = `Página: ${this.currentPage}/${this.urlMax}`;
const progreso = (this.currentPage / this.urlMax) * 100;
percentageText.innerHTML = `Porcentaje: ${progreso.toFixed(2)}%`;
progressBar.value = progreso;
const pageUrl = `${CONFIG.BASE_URL}/${page}`;
await this.scrapePageLinks(pageUrl);
}
logger.log('Scraping completado exitosamente', 'success');
} catch (error) {
logger.log(`Error en scraping: ${error}`, 'critical');
} finally {
this.finalizeScraping();
}
}
async scrapePageLinks(url) {
let intentos = 0;
const maxIntentos = 5;
while (intentos < maxIntentos) {
try {
const response = await fetch(url);
if (response.status === 200) {
const htmlText = await response.text();
const doc = new DOMParser().parseFromString(htmlText, 'text/html');
const elements = doc.querySelectorAll("a.enf-product-name.mkjs-a");
const inverterLinks = Array.from(elements).map(a => {
let href = a.getAttribute('href');
href = href.replace('/rter-datasheet/', '/pv/inverter-datasheet/');
return 'https://www.enfsolar.com' + href;
});
logger.log(`Encontrados ${inverterLinks.length} enlaces de inversores`, 'info');
for (let inverterUrl of inverterLinks) {
await this.scrapeInverterDetails(inverterUrl);
}
break;
} else {
throw new Error(`Error en la solicitud: ${response.status}`);
}
} catch (error) {
intentos++;
logger.log(`Intento ${intentos} fallido: ${error}`, 'warning');
if (intentos >= maxIntentos) {
logger.log('Máximo de intentos alcanzado', 'error');
throw error;
}
await new Promise(resolve => setTimeout(resolve, 1000 * intentos));
}
}
}
async scrapeInverterDetails(url) {
let intentos = 0;
const maxIntentos = 5;
while (intentos < maxIntentos) {
try {
const response = await fetch(url);
if (response.status === 200) {
const htmlText = await response.text();
const doc = new DOMParser().parseFromString(htmlText, 'text/html');
const inverterModels = this.extractInverterModels(doc);
if (inverterModels && inverterModels.length > 0) {
await this.processInverterData(inverterModels);
}
return inverterModels;
} else {
throw new Error(`Error en la solicitud: ${response.status}`);
}
} catch (error) {
intentos++;
logger.log(`Intento ${intentos} fallido para ${url}: ${error}`, 'warning');
if (intentos >= maxIntentos) {
logger.log('Máximo de intentos alcanzado', 'error');
throw error;
}
await new Promise(resolve => setTimeout(resolve, 1000 * intentos));
}
}
}
extractInverterModels(doc) {
// Extraer parámetros adicionales al inicio
const additionalParams = extractAdditionalParameters(doc);
// Extraer todas las URLs de imágenes del documento
const imageUrls = extractImageUrls(doc);
const simpleUrls = imageUrls.map(img => img.simpleUrl).join('; ') || 'N/A';
const fullUrls = imageUrls.map(img => img.fullImageUrl).join('; ') || 'N/A';
// Función auxiliar para buscar texto
const findElementWithText = (selector, text) => {
const elements = Array.from(doc.querySelectorAll(selector));
return elements.find(el =>
el.textContent.trim().toLowerCase() === text.toLowerCase()
);
};
// Parámetros que son comunes para todos los modelos (una sola columna)
const commonParameters = [
"Interface",
"Cooling",
"Protection Class",
"Operating Temperature",
"Protection Features",
"Display"
];
// Función para extraer datos de una columna específica
const extractSingleColumnData = (paramName) => {
// Mapeo de nombres para búsqueda más flexible
const parameterMappings = {
"OperatingTemperature": ["Operating Temperature", "Temperature Range"],
"Transformer": ["Transformer", "Transformer Type"],
"ProtectionClass": ["Protection Class", "IP Class"],
"Humidity": ["Humidity", "Relative Humidity"],
"Cooling": ["Cooling", "Cooling Method"],
"Interface": ["Interface", "Communication Interface"],
"ProtectionFeatures": ["Protection Features", "Safety Features"],
"MaxAltitude": [
"Max Altitude",
"Maximum Altitude",
"Altitude",
"Altitude Rating"
],
"Display": [
"Display",
"Screen",
"Display Type",
"Display Characteristics"
]
};
// Obtener variaciones de nombres para búsqueda
const searchVariations = parameterMappings[paramName] || [paramName];
// Buscar todas las filas
const rows = doc.querySelectorAll('tr');
for (let row of rows) {
// Buscar el encabezado de la fila
const th = row.querySelector('th');
if (!th) continue;
// Texto del encabezado
const thText = th.textContent.trim().toLowerCase();
// Verificar si coincide con alguna variación
const matchFound = searchVariations.some(variation =>
thText.includes(variation.toLowerCase())
);
if (matchFound) {
// Buscar la celda con la clase específica
const dataCell = row.querySelector('.mk-td-visible.ar\\:mdtext-right.ar\\:number-direction.ar\\:pr-4');
if (dataCell) {
// Limpiar y devolver el valor
const value = dataCell.textContent.trim();
return [value || 'N/A'];
}
}
}
// Si no se encuentra nada
return ['N/A'];
};
const extractColumnData = (columnIndex, paramName, doc) => {
switch(paramName) {
case "Description":
return extractDescription(doc);
case "Manufacturer":
return extractManufacturer(doc);
case "Type":
return additionalParams.type;
case "Power Range":
return additionalParams.powerRange;
case "Region":
return additionalParams.region;
case "PriceRange":
return extractPriceRange(doc);
case "ManufacturerPDF":
return extractManufacturerPDF(doc);
case "ManufacturerTelephone":
return extractManufacturerDetails(doc).ManufacturerTelephone;
case "ManufacturerURL":
return extractManufacturerDetails(doc).ManufacturerURL;
case "ManufacturerCountry":
return extractManufacturerDetails(doc).ManufacturerCountry;
case "ManufacturerAddress":
return extractManufacturerDetails(doc).ManufacturerAddress;
}
// Parámetros de una sola columna
const singleColumnParams = [
"Operating Temperature",
"Transformer",
"Protection Class",
"Humidity",
"Cooling",
"Interface",
"MaxAltitude", // Nuevo parámetro
"Display", // Nuevo parámetro
"Protection Features"
];
// Si es un parámetro de una sola columna
if (singleColumnParams.includes(paramName)) {
return extractSingleColumnData(paramName);
}
// Lógica original para múltiples columnas
// Buscar fila del encabezado de manera flexible
const findHeaderRowFlexibly = () => {
const allRows = doc.querySelectorAll('tr');
for (let row of allRows) {
const th = row.querySelector('th');
if (!th) continue;
// Normalizar texto del encabezado
const thText = th.textContent.trim().toLowerCase()
.replace(/\s+/g, '')
.replace(/\./g, '');
// Normalizar nombre del parámetro
const normalizedParamName = paramName.toLowerCase()
.replace(/\s+/g, '')
.replace(/\./g, '');
if (thText.includes(normalizedParamName)) {
return row;
}
}
return null;
};
// Buscar fila del encabezado
const headerRow = findHeaderRowFlexibly();
if (!headerRow) {
return [];
}
// Obtener celdas de datos
const dataCells = headerRow.querySelectorAll('.enf-api-spec-cell');
if (dataCells.length === 0) {
return [];
}
const columnValue = dataCells[columnIndex]?.textContent.trim() || 'N/A';
return [columnValue];
};
const headerRow = doc.querySelector('tr th[style*="width:175px"]').closest('tr');
const columnCells = headerRow.querySelectorAll('.enf-api-spec-cell');
const modelColumns = columnCells.length;
const parametersToExtract = [
"Model No.",
"Power",
"Price",
"Price (MSRP)",
"Product Warranty (Min)",
"Max. DC Power",
"Max. DC Voltage",
"Max. DC Current",
"Rated DC Voltage",
"Min. DC Voltage to Start Feed In",
"DC Inputs",
"Nominal DC Voltage",
"MPP(T) Voltage Range",
"No of MPP Trackers",
"Max. AC Power",
"Nominal AC Power",
"Nominal AC Voltage",
"Output AC Voltage Range",
"Rated AC Voltage",
"Max. AC Current",
"Rated AC Current",
"Frequency Range",
"Frequency",
"Power Factor (cosθ)",
"No of feed-in phases",
"Max. Efficiency",
"Euro Efficiency",
"Power Consumption at Night",
"Noise Level",
"Operating Temperature",
"Transformer",
"Protection Class",
"Humidity",
"Cooling",
"Interface",
"Protection Features",
"Dimensions (H/W/D)",
"Connectors",
"Display",
"Max. Altitude",
"Weight",
"Description", // Añade esta línea
"Manufacturer", // Añadir esta línea
"Type", // Añadir estos nuevos parámetros
"Power Range",
"Region",
"ImagesSimpleUrl",
"ImagesFullUrl",
"PriceRange",
"ManufacturerPDF",
"ManufacturerTelephone",
"ManufacturerURL",
"ManufacturerCountry",
"ManufacturerAddress"
];
const inverterModels = Array.from({length: modelColumns}, (_, columnIndex) => {
const modelData = {
imagesSimpleUrl: simpleUrls, // Asignar URLs de imágenes globales
imagesFullUrl: fullUrls // Asignar URLs de imágenes globales
};
parametersToExtract.forEach(param => {
const camelCaseKey = param.replace(/\s+/g, '');
modelData[camelCaseKey] = extractColumnData(columnIndex, param, doc);
});
return modelData;
});
console.log("Modelos de Inversores Extraídos:", inverterModels);
return inverterModels;
}
async processInverterData(inverterModels) {
// Validar entrada
if (!inverterModels || !Array.isArray(inverterModels) || inverterModels.length === 0) {
logger.log('No se encontraron modelos de inversores válidos', 'warning');
return null;
}
// Inicializar allModels si no existe
if (!this.processInverterData.allModels) {
this.processInverterData.allModels = {
modelNo: [], power: [], price: [], pricemsrp: [],
productWarrantyMin: [], maxDCPower: [], maxDCVoltage: [],
maxDCCurrent: [], ratedDCVoltage: [], minDCVoltageToStartFeedIn: [],
dcInputs: [], nominalDCVoltage: [], mppVoltageRange: [],
noOfMPPTrackers: [], maxACPower: [], nominalACPower: [],
nominalACVoltage: [], outputACVoltageRange: [], ratedACVoltage: [],
maxACCurrent: [], ratedACCurrent: [], frequencyRange: [],
frequency: [], powerFactorCosTheta: [], noOfFeedInPhases: [],
maxEfficiency: [], euroEfficiency: [], powerConsumptionAtNight: [],
noiseLevel: [], operatingTemperature: [], transformer: [],
protectionClass: [], humidity: [], cooling: [], interface: [],
protectionFeatures: [], dimensions: [], connectors: [], display: [],
maxAltitude: [], weight: [], description: [], manufacturer: [],
type: [], powerRange: [], region: [], imagesSimpleUrl: [],
imagesFullUrl: [], priceRange: [], ManufacturerPDF: [],
ManufacturerTelephone: [], ManufacturerURL: [],
ManufacturerCountry: [], ManufacturerAddress: []
};
}
try {
// Acumular modelos
inverterModels.forEach(model => {
Object.keys(model).forEach(key => {
// Normalización de nombre de clave
const normalizedKey = key
.toLowerCase() // Convertir a minúsculas
.replace(/\s+/g, '') // Eliminar todos los espacios
.replace(/\./g, '') // Eliminar puntos
.replace(/θ/g, '') // Eliminar θ
.replace(/[\(\)\-\/,:'"]/g, ''); // Eliminar paréntesis, guiones, barras u otros símbolos
// Mapeo de las claves normalizadas a sus versiones esperadas
const keyMap = {
'modelno': 'modelNo',
'power': 'power',
'price': 'price',
'pricemsrp': 'pricemsrp',
'productwarrantymin': 'productWarrantyMin',
'maxdcpower': 'maxDCPower',
'maxdcvoltage': 'maxDCVoltage',
'maxdccurrent': 'maxDCCurrent',
'rateddcvoltage': 'ratedDCVoltage',
'mindcvoltagetostartfeedin': 'minDCVoltageToStartFeedIn',
'dcinputs': 'dcInputs',
'nominaldcvoltage': 'nominalDCVoltage',
'mpptvoltagerange': 'mppVoltageRange',
'noofmpptrackers': 'noOfMPPTrackers',
'maxacpower': 'maxACPower',
'nominalacpower': 'nominalACPower',
'nominalacvoltage': 'nominalACVoltage',
'outputacvoltagerange': 'outputACVoltageRange',
'ratedacvoltage': 'ratedACVoltage',
'maxaccurrent': 'maxACCurrent',
'ratedaccurrent': 'ratedACCurrent',
'frequencyrange': 'frequencyRange',
'frequency': 'frequency',
'powerfactorcos': 'powerFactorCosTheta',
'nooffeedinphases': 'noOfFeedInPhases',
'maxefficiency': 'maxEfficiency',
'euroefficiency': 'euroEfficiency',
'powerconsumptionatnight': 'powerConsumptionAtNight',
'noiselevel': 'noiseLevel',
'operatingtemperature': 'operatingTemperature',
'transformer': 'transformer',
'protectionclass': 'protectionClass',
'humidity': 'humidity',
'cooling': 'cooling',
'interface': 'interface',
'protectionfeatures': 'protectionFeatures',
'dimensionshwd': 'dimensions',
'connectors': 'connectors',
'display': 'display',
'maxaltitude': 'maxAltitude',
'weight': 'weight',
'description': 'description',
'manufacturer': 'manufacturer',
'type': 'type',
'powerrange': 'powerRange',
'region': 'region',
'imagessimpleurl': 'imagesSimpleUrl',
'imagesfullurl': 'imagesFullUrl',
'pricerange': 'priceRange',
'manufacturerpdf': 'ManufacturerPDF',
'manufacturertelephone': 'ManufacturerTelephone',
'manufacturerurl': 'ManufacturerURL',
'manufacturercountry': 'ManufacturerCountry',
'manufactureraddress': 'ManufacturerAddress',
};
const mappedKey = keyMap[normalizedKey] || normalizedKey;
// Validar si la clave ya existe en allModels, inicialízala si es necesario
if (!this.processInverterData.allModels[mappedKey]) {
console.warn(`Clave "${mappedKey}" no está en allModels. Inicializando automáticamente.`);
this.processInverterData.allModels[mappedKey] = [];
}
// Manejo de valores (arrays vacíos y valores existentes)
const value = Array.isArray(model[key]) && model[key].length > 0
? model[key][0] // Primer valor del array si existe
: 'N/A'; // Valor predeterminado si el array está vacío
// Insertar el valor en la clave correspondiente de `allModels`
this.processInverterData.allModels[mappedKey].push(value);
});
});
// Log final del estado de allModels
console.log('Estado actualizado de allModels:', this.processInverterData.allModels);
// Inicializar contador si no existe
this.processInverterData.modelCount =
this.processInverterData.modelCount || 0;
// Incrementar contador
this.processInverterData.modelCount += inverterModels.length;
// Verificar si hemos alcanzado los 20 modelos
if (this.processInverterData.modelCount >= 20) {
// Crear y descargar SQL
await this.createAndDownloadSQL(this.processInverterData.allModels);
// Resetear contadores y modelos
this.processInverterData.modelCount = 0;
this.processInverterData.allModels = null;
}
return this.processInverterData.allModels;
} catch (error) {
logger.log(`Error procesando datos de inversores: ${error}`, 'error');
return null;
}
}
// Método para parsear valores numéricos (fuera del método principal)
parseNumeric(value) {
return (!isNaN(parseFloat(value)) && isFinite(value))
? parseFloat(value)
: 'NULL';
}
createAndDownloadSQL(data) {
// Encontrar un array no vacío para determinar el número de modelos
const numModelos = Object.values(data).find(arr => Array.isArray(arr) && arr.length > 0)?.length || 0;
console.log('Número de modelos a procesar:', numModelos);
// Verificar que tenemos datos
if (numModelos === 0) {
console.error('No hay datos para procesar');
return;
}
// Método de sanitización
const sanitizeValue = (value) => {
if (!value || value === 'N/A') return 'N/A';
return value.toString()
.replace(/'/g, "''")
.replace(/\\/g, "\\\\")
.trim();
};
console.log(data);
// Inicializar contenido SQL
let sqlContent = '';
// Iterar sobre cada modelo
for (let i = 0; i < numModelos; i++) {
sqlContent += `
INSERT INTO miTabla (
modelNo, power, price, pricemsrp, productWarrantyMin,
maxDCPower, maxDCVoltage, maxDCCurrent, ratedDCVoltage,
minDCVoltageToStartFeedIn, dcInputs,
nominalDCVoltage, mppVoltageRange,
noOfMPPTrackers, maxACPower, nominalACPower,
nominalACVoltage, outputACVoltageRange,
ratedACVoltage, maxACCurrent,
ratedACCurrent, frequencyRange,
frequency, powerFactorCosTheta,
noOfFeedInPhases, maxEfficiency,
euroEfficiency, powerConsumptionAtNight,
noiseLevel, operatingTemperature,
transformer, protectionClass,
humidity, cooling, interface,
protectionFeatures, dimensions, connectors,
display, maxAltitude, weight, description, manufacturer, type, powerRange, region, imagesSimpleUrl, imagesFullUrl, priceRange, ManufacturerPDF, ManufacturerTelephone, ManufacturerURL, ManufacturerCountry, ManufacturerAddress
) VALUES (
'sanitizeV{sanitizeValue(data['maxACPower']?.[i] || 'N/A')}',
'{sanitizeValue(data['pricemsrp']?.[i] || 'N/A')}',
'{sanitizeValue(data['maxDCPower']?.[i] || 'N/A')}',
'{sanitizeValue(data['maxDCCurrent']?.[i] || 'N/A')}',
'{sanitizeValue(data['minDCVoltageToStartFeedIn']?.[i] || 'N/A')}',
'{sanitizeValue(data['nominalDCVoltage']?.[i] || 'N/A')}',
'{sanitizeValue(data['noOfMPPTrackers']?.[i] || 'N/A')}',
'{sanitizeValue(data['nominalACPower']?.[i] || 'N/A')}',
'{sanitizeValue(data['outputACVoltageRange']?.[i] || 'N/A')}',
'{sanitizeValue(data['maxACCurrent']?.[i] || 'N/A')}',
'{sanitizeValue(data['frequencyRange']?.[i] || 'N/A')}',
'{sanitizeValue(data['powerFactorCosTheta']?.[i] || 'N/A')}',
'{sanitizeValue(data['maxEfficiency']?.[i] || 'N/A')}',
'{sanitizeValue(data['powerConsumptionAtNight']?.[i] || 'N/A')}',
'{sanitizeValue(data['operatingTemperature']?.[i] || 'N/A')}',
'{sanitizeValue(data['protectionClass']?.[i] || 'N/A')}',
'{sanitizeValue(data['cooling']?.[i] || 'N/A')}',
'{sanitizeValue(data['protectionFeatures']?.[i] || 'N/A')}',
'{sanitizeValue(data['connectors']?.[i] || 'N/A')}',
'{sanitizeValue(data['maxAltitude']?.[i] || 'N/A')}',
'{sanitizeValue(data['description']?.[i] || 'N/A')}',
'{sanitizeValue(data['type']?.[i] || 'N/A')}',
'{sanitizeValue(data['region']?.[i] || 'N/A')}',
'{sanitizeValue(data['imagesFullUrl']?.[i] || 'N/A')}',
'{sanitizeValue(data['ManufacturerPDF']?.[i] || 'N/A')}',
'{sanitizeValue(data['ManufacturerURL']?.[i] || 'N/A')}',
'{sanitizeValue(data['ManufacturerAddress']?.[i] || 'N/A')}'
);\n`;
}
// Descargar el archivo
this.downloadSQL(sqlContent);
}
downloadSQL(sqlContent) {
// Crear Blob con contenido SQL
const blob = new Blob([sqlContent], { type: 'text/sql' });
// Crear enlace de descarga
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
// Nombre de archivo basado en fecha
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
link.download = `inverter_data_${timestamp}.sql`;
// Añadir al documento, hacer clic y limpiar
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
// Liberar memoria
URL.revokeObjectURL(link.href);
}
async sendDataToServer(sql) {
try {
const response = await fetch(CONFIG.API_ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Encryption-Version': '1.0'
},
body: JSON.stringify({
data: sql,
timestamp: new Date().toISOString()
})
});
if (!response.ok) {
throw new Error(`Error en envío: ${response.status}`);
}
const responseData = await response.json();
if (responseData.status === 'success') {
logger.log('Datos enviados exitosamente', 'success');
} else {
logger.log('Respuesta del servidor no exitosa', 'warning');
}
} catch (error) {
logger.log(`Error enviando datos: ${error}`, 'error');
}
}
// Método de sanitización adicional
sanitizeSqlString(sql) {
// Eliminar caracteres no imprimibles
const cleanSql = sql.replace(/[^\x20-\x7E]/g, '');
// Escapar comillas simples
const escapedSql = cleanSql.replace(/'/g, "''");
return escapedSql;
}
finalizeScraping() {
this.isRunning = false;
this.isPaused = false;
logger.log('Proceso de scraping finalizado', 'info');
// Opcional: Exportar logs
logger.exportLogs();
}
waitForResume() {
return new Promise((resolve) => {
const checkPause = setInterval(() => {
if (!this.isPaused) {
clearInterval(checkPause);
resolve();
}
}, 1000);
});
}
}
// Inicialización del Scraper
document.addEventListener('DOMContentLoaded', () => {
const scraper = new SolarInverterScraper();
const startButton = document.getElementById('startScraping');
const pauseButton = document.getElementById('pauseScraping');
const stopButton = document.getElementById('stopScraping');
const exportLogsButton = document.getElementById('exportLogs');
// Verificaciones seguras
if (startButton) {
startButton.addEventListener('click', () => {
try {
scraper.initializeScraping();
} catch (error) {
logger.log(`Error al iniciar scraping: ${error.message}`, 'error');
}
});
}
if (pauseButton) {
pauseButton.addEventListener('click', () => {
scraper.isPaused = true;
logger.log('Scraping pausado', 'warning');
});
}
if (stopButton) {
stopButton.addEventListener('click', () => {
scraper.isRunning = false;
scraper.isPaused = false;
logger.log('Scraping detenido', 'warning');
});
}
if (exportLogsButton) {
exportLogsButton.addEventListener('click', () => {
logger.exportLogs();
});
}
});