Files
scan-sfera/debug-current-wb.js
2025-07-19 17:56:06 +03:00

143 lines
5.3 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const puppeteer = require('puppeteer');
async function debugWildberries() {
console.log('🔍 Запускаем диагностику структуры Wildberries...');
const browser = await puppeteer.launch({
headless: false, // Открываем браузер для визуального контроля
devtools: true, // Открываем DevTools
args: ['--no-sandbox', '--disable-setuid-sandbox']
});
const page = await browser.newPage();
await page.setUserAgent(
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
);
const searchQuery = 'лабубу';
const url = `https://www.wildberries.ru/catalog/0/search.aspx?search=${encodeURIComponent(searchQuery)}`;
console.log(`📖 Открываем: ${url}`);
try {
await page.goto(url, { waitUntil: 'networkidle2', timeout: 30000 });
// Ждем 3 секунды для полной загрузки
await new Promise(resolve => setTimeout(resolve, 3000));
console.log('🔍 Анализируем структуру страницы...');
// Проверяем разные селекторы
const selectors = [
'[data-nm-id]',
'.product-card',
'.product-card__wrapper',
'.goods-name',
'.product-card__link',
'.j-card-link',
'article',
'[class*="product"]',
'[class*="card"]'
];
console.log('\n🎯 Результаты поиска селекторов:');
for (const selector of selectors) {
const count = await page.$$eval(selector, elements => elements.length);
console.log(`${selector}: ${count} элементов`);
if (count > 0 && count < 20) {
// Показываем первые несколько найденных элементов
const elements = await page.$$eval(selector, (elements, sel) => {
return elements.slice(0, 3).map((el, index) => ({
index,
tagName: el.tagName,
className: el.className,
id: el.id,
dataNmId: el.getAttribute('data-nm-id'),
href: el.href || (el.querySelector('a') ? el.querySelector('a').href : null),
text: el.textContent ? el.textContent.substring(0, 100) : null
}));
}, selector);
console.log(` Примеры элементов для ${selector}:`);
elements.forEach(el => {
console.log(` ${el.index + 1}. <${el.tagName}> class="${el.className}" data-nm-id="${el.dataNmId}" href="${el.href}"`);
if (el.text) console.log(` текст: "${el.text.trim()}"`);
});
}
}
// Проверяем наличие товаров с конкретным артикулом
console.log('\n🎯 Поиск товара с артикулом 447020075:');
const articleFound = await page.evaluate(() => {
const article = '447020075';
// Ищем по data-nm-id
const byDataNmId = document.querySelector(`[data-nm-id="${article}"]`);
if (byDataNmId) {
return {
method: 'data-nm-id',
element: byDataNmId.tagName,
className: byDataNmId.className,
parent: byDataNmId.parentElement ? byDataNmId.parentElement.tagName : null
};
}
// Ищем в href
const byHref = document.querySelector(`a[href*="${article}"]`);
if (byHref) {
return {
method: 'href',
element: byHref.tagName,
className: byHref.className,
href: byHref.href,
parent: byHref.parentElement ? byHref.parentElement.tagName : null
};
}
// Ищем в тексте
const allElements = document.querySelectorAll('*');
for (let el of allElements) {
if (el.textContent && el.textContent.includes(article)) {
return {
method: 'text content',
element: el.tagName,
className: el.className,
text: el.textContent.substring(0, 200)
};
}
}
return null;
});
if (articleFound) {
console.log(`✅ Товар найден методом: ${articleFound.method}`);
console.log(` Элемент: <${articleFound.element}> class="${articleFound.className}"`);
if (articleFound.href) console.log(` Ссылка: ${articleFound.href}`);
if (articleFound.text) console.log(` Текст: ${articleFound.text}`);
} else {
console.log('❌ Товар с артикулом 447020075 не найден');
}
// Сохраняем HTML для анализа
const htmlContent = await page.content();
require('fs').writeFileSync('wb-debug.html', htmlContent);
console.log('\n💾 HTML страницы сохранен в wb-debug.html');
console.log('\n⏸ Браузер остается открытым для ручного анализа. Нажмите Enter для закрытия...');
// Ждем ввода пользователя
await new Promise(resolve => {
process.stdin.once('data', resolve);
});
} catch (error) {
console.error('❌ Ошибка:', error);
} finally {
await browser.close();
}
}
debugWildberries().catch(console.error);