如何阻止滚动时div被隐藏?实现全页面商品div批量提取
解决滚动加载页面的商品数据提取问题
方法1:禁用滚动加载的事件监听
- 直接阻断页面的滚动监听逻辑,避免旧元素被移除,同时强制触发所有内容加载:
// 移除全局滚动事件监听 window.removeEventListener('scroll', () => {}); // 强制设置滚动到底部,触发所有内容加载 document.documentElement.scrollTop = document.documentElement.scrollHeight; // 若页面通过scrollY判断位置,可覆盖该属性阻止元素移除 Object.defineProperty(window, 'scrollY', { get: () => 0 }); - 核心逻辑:这类页面靠监听滚动位置加载新内容、移除视口外元素,通过修改滚动相关属性或移除监听,就能让页面保留所有已加载的商品DOM。
方法2:模拟滚动批量抓取
如果第一种方法失效,可通过模拟滚动逐步加载并实时保存数据:
// 存储抓取到的商品数据 const products = []; // 抓取当前可见商品的函数(需替换为页面实际选择器) function scrapeCurrentItems() { const itemNodes = document.querySelectorAll('.product-card'); itemNodes.forEach(node => { const name = node.querySelector('.product-title').textContent.trim(); const price = node.querySelector('.product-price').textContent.trim(); // 避免重复存储 if (name && price && !products.some(p => p.name === name)) { products.push({ name, price }); } }); } // 自动滚动加载的函数 async function autoLoadAndScrape() { let lastPageHeight = document.documentElement.scrollHeight; while (true) { scrapeCurrentItems(); // 滚动到底部 window.scrollTo(0, document.documentElement.scrollHeight); // 等待页面加载新内容(可根据页面速度调整毫秒数) await new Promise(resolve => setTimeout(resolve, 1500)); const newPageHeight = document.documentElement.scrollHeight; // 高度不再变化说明已加载完所有内容 if (newPageHeight === lastPageHeight) { scrapeCurrentItems(); break; } lastPageHeight = newPageHeight; } // 输出结果并导出为CSV console.log('所有商品数据:', products); const csvContent = '商品名称,价格\n' + products.map(p => `${p.name},${p.price}`).join('\n'); const blob = new Blob([csvContent], { type: 'text/csv' }); const downloadLink = document.createElement('a'); downloadLink.href = URL.createObjectURL(blob); downloadLink.download = '商品价格数据.csv'; downloadLink.click(); } // 启动抓取 autoLoadAndScrape();
- 注意:需要根据目标页面的DOM结构,替换代码中的选择器(比如
.product-card、.product-title),调整等待时间适配页面加载速度。
方法3:直接调用后台接口(最高效)
打开浏览器开发者工具(F12)的Network面板,滚动页面时观察XHR/Fetch请求,通常这类页面会通过/api/products?page=1这类接口加载商品数据,直接调用接口比操作DOM更高效:
const products = []; let currentPage = 1; const pageSize = 20; // 从接口参数中获取实际每页数量 async function fetchAllProducts() { while (true) { try { // 替换为页面实际的商品接口地址 const res = await fetch(`/app/api/products?page=${currentPage}&size=${pageSize}`); const data = await res.json(); if (data.length === 0) break; products.push(...data); currentPage++; } catch (err) { console.error('请求出错:', err); break; } } console.log('完整商品数据:', products); } fetchAllProducts();
内容的提问来源于stack exchange,提问作者Bruno Acosta
相关产品推荐
相关产品推荐

