From d1c4ffbd70f4a66ec1ac386465f2fc7206346dac Mon Sep 17 00:00:00 2001 From: ali Date: Tue, 28 Jul 2026 15:33:10 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20MysteelGetMinPrice.js?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- MysteelGetMinPrice.js | 470 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 470 insertions(+) create mode 100644 MysteelGetMinPrice.js diff --git a/MysteelGetMinPrice.js b/MysteelGetMinPrice.js new file mode 100644 index 0000000..cdf62f5 --- /dev/null +++ b/MysteelGetMinPrice.js @@ -0,0 +1,470 @@ +// ==UserScript== +// @name Mysteel 钢铁价格提取器 +// @namespace http://tampermonkey.net/ +// @version 6.0 +// @description 合并列表页与详情页的抓取逻辑,统一透视表导出,支持多维筛选及本地缓存 +// @author ali +// @match https://jiancai.mysteel.com/market/* +// @match https://jiancai.mysteel.com/m/* +// @grant none +// ==/UserScript== + +(function() { + 'use strict'; + + // 判断当前页面类型 + const isListPage = window.location.href.includes('/market/'); + const isDetailPage = window.location.href.includes('/m/'); + + // 预设筛选常量 + const FILTER_OPTIONS = { + names: ['高线', '螺纹钢', '盘螺'], + specs: ['Φ6', 'Φ8', 'Φ8-10', 'Φ10', 'Φ12', 'Φ14', 'Φ16', 'Φ18', 'Φ20', 'Φ22', 'Φ25', 'Φ28', 'Φ32', 'Φ36', 'Φ36-40', 'Φ40'], + materials: ['HPB300', 'HRB400', 'HRB400E', 'HRB500E'] + }; + + // 读取本地缓存的筛选条件 + function loadSavedFilters() { + const saved = localStorage.getItem('mysteel_filters'); + if (saved) { + try { + return JSON.parse(saved); + } catch (e) { + console.error('解析缓存筛选条件失败', e); + } + } + return { names: [], specs: [], materials: [] }; + } + + // 保存筛选条件到本地缓存 + function saveFiltersToLocal(filters) { + localStorage.setItem('mysteel_filters', JSON.stringify(filters)); + } + + // 获取当前活动筛选条件 (直接从 DOM 获取) + function getCurrentFilters() { + return { + names: Array.from(document.querySelectorAll('input[name="ms-filter-names"]:checked')).map(el => el.value), + specs: Array.from(document.querySelectorAll('input[name="ms-filter-specs"]:checked')).map(el => el.value), + materials: Array.from(document.querySelectorAll('input[name="ms-filter-materials"]:checked')).map(el => el.value) + }; + } + + // 1. 构建交互 UI (动态适配列表/详情页) + function injectUI() { + if (document.getElementById('mysteel-tool-container')) return; + + const savedFilters = loadSavedFilters(); + + const container = document.createElement('div'); + container.id = 'mysteel-tool-container'; + Object.assign(container.style, { + position: 'fixed', bottom: '50px', right: '50px', + display: 'flex', alignItems: 'flex-end', gap: '10px', + zIndex: '99999', fontFamily: 'sans-serif' + }); + + // --- 主按钮 --- + const btn = document.createElement('button'); + btn.id = 'mysteel-action-btn'; + // 根据页面类型设定按钮文字 + btn.innerText = isListPage ? '🚀 批量导出' : '📊 单日导出'; + + Object.assign(btn.style, { + padding: '12px 24px', + backgroundColor: isListPage ? '#fa541c' : '#1890ff', + color: '#fff', + border: 'none', borderRadius: '6px', fontSize: '16px', fontWeight: 'bold', + boxShadow: '0 4px 12px rgba(0,0,0,0.2)', cursor: 'pointer', transition: '0.3s' + }); + + btn.onmouseover = () => btn.style.backgroundColor = isListPage ? '#ff7875' : '#40a9ff'; + btn.onmouseout = () => btn.style.backgroundColor = isListPage ? '#fa541c' : '#1890ff'; + + // 绑定对应的执行引擎 + if (isListPage) { + btn.addEventListener('click', startBatchProcess); + } else if (isDetailPage) { + btn.addEventListener('click', startSingleProcess); + } + + // --- 齿轮图标 --- + const gearBtn = document.createElement('div'); + gearBtn.innerHTML = '⚙️'; + Object.assign(gearBtn.style, { + width: '46px', height: '46px', backgroundColor: '#fff', + borderRadius: '50%', display: 'flex', justifyContent: 'center', alignItems: 'center', + fontSize: '24px', boxShadow: '0 4px 12px rgba(0,0,0,0.2)', cursor: 'pointer', + userSelect: 'none' + }); + + // --- 悬浮状态提示面板 --- + const tooltip = document.createElement('div'); + Object.assign(tooltip.style, { + display: 'none', position: 'absolute', bottom: '60px', right: '0', + backgroundColor: 'rgba(0,0,0,0.85)', color: '#fff', padding: '12px', + borderRadius: '6px', fontSize: '13px', width: 'max-content', + maxWidth: '300px', lineHeight: '1.5', pointerEvents: 'none', + boxShadow: '0 4px 12px rgba(0,0,0,0.1)' + }); + + // --- 高级筛选配置面板 --- + const panel = document.createElement('div'); + panel.id = 'mysteel-filter-panel'; + Object.assign(panel.style, { + display: 'none', position: 'absolute', bottom: '60px', right: '0', + backgroundColor: '#fff', padding: '20px', borderRadius: '8px', + boxShadow: '0 4px 24px rgba(0,0,0,0.2)', width: '360px', + color: '#333', border: '1px solid #eee' + }); + + // 动态生成带有缓存状态的 Checkbox HTML + const buildCheckboxes = (groupName, options) => { + return options.map(opt => { + const isChecked = savedFilters[groupName].includes(opt) ? 'checked' : ''; + return ` + + `; + }).join(''); + }; + + panel.innerHTML = ` +
高级筛选配置
+
+
类别 (默认全选):
+
${buildCheckboxes('names', FILTER_OPTIONS.names)}
+
+
+
线径 (默认全选):
+
${buildCheckboxes('specs', FILTER_OPTIONS.specs)}
+
+
+
材质 (默认全选):
+
${buildCheckboxes('materials', FILTER_OPTIONS.materials)}
+
+ + `; + + // --- UI 交互逻辑 --- + gearBtn.addEventListener('mouseenter', () => { + if (panel.style.display === 'block') return; + const f = getCurrentFilters(); + const formatF = (arr) => arr.length > 0 ? arr.join(', ') : '全部'; + tooltip.innerHTML = ` +
当前筛选状态:
+
类别:${formatF(f.names)}
+
线径:${formatF(f.specs)}
+
材质:${formatF(f.materials)}
+ `; + tooltip.style.display = 'block'; + }); + + gearBtn.addEventListener('mouseleave', () => { + tooltip.style.display = 'none'; + }); + + gearBtn.addEventListener('click', () => { + tooltip.style.display = 'none'; + panel.style.display = panel.style.display === 'none' ? 'block' : 'none'; + }); + + // 组装 DOM + container.appendChild(panel); + container.appendChild(tooltip); + container.appendChild(btn); + container.appendChild(gearBtn); + document.body.appendChild(container); + + // 绑定保存关闭按钮事件 + document.getElementById('ms-close-panel-btn').addEventListener('click', () => { + const active = getCurrentFilters(); + saveFiltersToLocal(active); // 写入 localStorage + panel.style.display = 'none'; + }); + } + + // ========================================== + // 引擎 A: 详情页单页抓取 (复用已有逻辑) + // ========================================== + function startSingleProcess() { + const btn = document.getElementById('mysteel-action-btn'); + const originalText = btn.innerText; + btn.innerText = '正在提取...'; + btn.disabled = true; + + try { + // 提取日期:从 提取 + const dateEl = document.querySelector('.content-info-text.publish-time'); + if (!dateEl) { + alert('未找到页面的发布时间,请确认当前网页结构!'); + return; + } + // 提取 "2026-07-24 17:41" 中的 "2026-07-24" + const dateStr = dateEl.innerText.trim().split(' ')[0]; + + const activeFilters = getCurrentFilters(); + + // 直接读取当前 DOM 树中的数据 + const flatData = extractDataFromDoc(document, dateStr, activeFilters); + + if (flatData.length > 0) { + generatePivotCSV(flatData, '单日'); + } else { + alert('根据当前筛选条件,未提取到有效数据!'); + } + } catch (error) { + console.error('详情页提取出错:', error); + alert('发生错误,请查看控制台日志。'); + } finally { + btn.innerText = originalText; + btn.disabled = false; + } + } + + // ========================================== + // 引擎 B: 列表页批量抓取 + // ========================================== + async function startBatchProcess() { + const btn = document.getElementById('mysteel-action-btn'); + const originalText = btn.innerText; + btn.disabled = true; + btn.style.backgroundColor = '#ccc'; + + try { + btn.innerText = '正在分析列表...'; + const targetLinks = getTargetLinks(); + if (targetLinks.length === 0) { + alert('未发现符合条件的链接!'); + return; + } + + let flatData = []; + const activeFilters = getCurrentFilters(); + + // 顺序加载每一个页面 + for (let i = 0; i < targetLinks.length; i++) { + const linkObj = targetLinks[i]; + btn.innerText = `正在渲染: ${linkObj.date} (${i + 1}/${targetLinks.length})...`; + + try { + const doc = await getRenderedDocViaIframe(linkObj.url); + if (doc) { + const dailyData = extractDataFromDoc(doc, linkObj.date, activeFilters); + if(dailyData.length > 0) { + flatData = flatData.concat(dailyData); + } + } + } catch (err) { + console.error(`渲染 ${linkObj.date} 失败:`, err); + } + } + + btn.innerText = '正在生成数据透视表...'; + + if (flatData.length > 0) { + generatePivotCSV(flatData, '批量'); + } else { + alert('根据当前筛选条件,未能提取到任何数据!'); + } + + } catch (error) { + console.error('批量处理出错:', error); + alert('发生错误,请查看控制台。'); + } finally { + btn.innerText = originalText; + btn.disabled = false; + btn.style.backgroundColor = '#fa541c'; + } + } + + // ========================================== + // 公共组件区 + // ========================================== + + // 获取列表页的日期链接 + function getTargetLinks() { + const listItems = document.querySelectorAll('#articleList .nlist li'); + const dailyMap = new Map(); + + listItems.forEach(li => { + const dateSpan = li.querySelector('.date'); + const aTag = li.querySelector('a'); + + if (!dateSpan || !aTag) return; + + const text = aTag.innerText.trim(); + const href = aTag.href; + + if (text.includes('工程') || text.includes('采购')) return; + + const dateTimeStr = dateSpan.innerText.trim(); + const [date, time] = dateTimeStr.split(' '); + + if (date && time && href.includes('mysteel.com')) { + if (!dailyMap.has(date) || time > dailyMap.get(date).time) { + dailyMap.set(date, { date, time, url: href, title: text }); + } + } + }); + + return Array.from(dailyMap.values()).sort((a, b) => b.date.localeCompare(a.date)); + } + + // Iframe 静默渲染引擎 + async function getRenderedDocViaIframe(url) { + return new Promise((resolve) => { + const iframe = document.createElement('iframe'); + Object.assign(iframe.style, { + width: '0px', height: '0px', visibility: 'hidden', position: 'absolute', border: 'none' + }); + iframe.src = url; + + iframe.onload = () => { + setTimeout(() => { + try { + const iframeDoc = iframe.contentDocument || iframe.contentWindow.document; + resolve(iframeDoc); + } catch (e) { + resolve(null); + } finally { + document.body.removeChild(iframe); + } + }, 2500); + }; + + iframe.onerror = () => { + document.body.removeChild(iframe); + resolve(null); + }; + + document.body.appendChild(iframe); + }); + } + + // 核心提取与数据清洗过滤引擎 (合并版) + function extractDataFromDoc(doc, dateStr, filters) { + const targetTable = doc.getElementById('marketTable'); + if (!targetTable) return []; + + const tbody = targetTable.querySelector('tbody'); + if (!tbody) return []; + const rows = tbody.querySelectorAll('tr'); + + const dataMap = new Map(); + + for (let row of rows) { + if (row.style.display === 'none' || !row.hasAttribute('table-row-id')) continue; + + const tdBreed = row.querySelector('td[data-type="breed"]'); + const tdSpec = row.querySelector('td[data-type="spec"]'); + const tdMaterial = row.querySelector('td[data-type="material"]'); + const tdPrice = row.querySelector('td[data-type="price"]'); + + if (!tdBreed || !tdSpec || !tdMaterial || !tdPrice) continue; + + const cleanText = (element) => { + let clone = element.cloneNode(true); + let childIcons = clone.querySelectorAll('a, img, div'); + childIcons.forEach(icon => icon.remove()); + return clone.innerText.replace(/[\r\n\t]/g, '').trim(); + }; + + const name = cleanText(tdBreed); + const spec = cleanText(tdSpec); + const material = cleanText(tdMaterial); + + // 执行多维筛选校验:如果有勾选项且当前值不在勾选项内,则拦截跳过 + if (filters.names.length > 0 && !filters.names.includes(name)) continue; + if (filters.specs.length > 0 && !filters.specs.includes(spec)) continue; + if (filters.materials.length > 0 && !filters.materials.includes(material)) continue; + + const priceStr = tdPrice.innerText.replace(/,/g, '').trim(); + const currentPrice = parseFloat(priceStr); + + if (!name || isNaN(currentPrice)) continue; + + const uniqueKey = `${name}_${spec}_${material}`; + + if (!dataMap.has(uniqueKey) || currentPrice < dataMap.get(uniqueKey).priceNum) { + dataMap.set(uniqueKey, { + date: dateStr, + name: name, + spec: spec, + material: material, + priceNum: currentPrice + }); + } + } + return Array.from(dataMap.values()); + } + + // 数据透视与生成 CSV (统一导出逻辑) + function generatePivotCSV(flatData, filePrefix) { + // 1. 提取独立日期并升序排列 (保证横向展示时从老日期到新日期) + const uniqueDates = [...new Set(flatData.map(d => d.date))].sort((a, b) => a.localeCompare(b)); + + // 日期格式化:将 "2026-07-24" 转为 "7/24" + const formatHeaderDate = (dStr) => { + const parts = dStr.split('-'); + if (parts.length === 3) { + return `${parseInt(parts[1], 10)}/${parseInt(parts[2], 10)}`; + } + return dStr; + }; + + const dateHeaders = uniqueDates.map(formatHeaderDate); + + // 2. 将扁平数据转为透视结构的 Map + const pivotMap = new Map(); + flatData.forEach(item => { + const key = `${item.name}_${item.spec}_${item.material}`; + if (!pivotMap.has(key)) { + pivotMap.set(key, { + name: item.name, + spec: item.spec, + material: item.material, + pricesByDate: {} + }); + } + pivotMap.get(key).pricesByDate[item.date] = item.priceNum; + }); + + // 3. 拼接 CSV 内容 + let csvContent = '\uFEFF'; + csvContent += `类别,线径,材质,${dateHeaders.join(',')}\n`; + + pivotMap.forEach(row => { + let rowText = `"${row.name}","${row.spec}","${row.material}"`; + uniqueDates.forEach(date => { + const price = row.pricesByDate[date] ? row.pricesByDate[date] : ''; + rowText += `,"${price}"`; + }); + csvContent += rowText + '\n'; + }); + + // 4. 触发下载 + const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' }); + const url = URL.createObjectURL(blob); + const link = document.createElement('a'); + + const d = new Date(); + const dateStr = `${d.getFullYear()}${(d.getMonth()+1).toString().padStart(2,'0')}${d.getDate().toString().padStart(2,'0')}`; + + link.setAttribute('href', url); + link.setAttribute('download', `钢材透视价格表_${filePrefix}_${dateStr}.csv`); + + document.body.appendChild(link); + link.click(); + + document.body.removeChild(link); + URL.revokeObjectURL(url); + } + + // 延时加载注入,保障单页框架的各种加载时序 + window.addEventListener('load', injectUI); + setTimeout(injectUI, 2000); + setTimeout(injectUI, 5000); + +})(); \ No newline at end of file