741 lines
32 KiB
JavaScript
741 lines
32 KiB
JavaScript
// ==UserScript==
|
|
// @name Mysteel 钢铁价格提取器
|
|
// @namespace http://tampermonkey.net/
|
|
// @version 6.5
|
|
// @description 实现列表页与详情页的抓取逻辑,统一透视表导出csv/xlsx,支持多维筛选及本地缓存
|
|
// @author ali
|
|
// @mail solitude@hraulein.com
|
|
// @match *://*.mysteel.com/market/*
|
|
// @match *://*.mysteel.com/m/*
|
|
// @grant none
|
|
// @require https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js
|
|
// ==/UserScript==
|
|
|
|
(function () {
|
|
'use strict';
|
|
|
|
// 判断当前页面类型
|
|
const isListPage = window.location.href.includes('/market/');
|
|
const isDetailPage = window.location.href.includes('/m/');
|
|
|
|
// 预设筛选常量
|
|
let FILTER_OPTIONS = {
|
|
names: ["盘螺", "螺纹钢", "高线"],
|
|
specs: ["Φ6", "Φ8-10", "Φ8", "Φ10", "Φ12", "Φ14", "Φ16", "Φ18", "Φ20", "Φ22", "Φ25", "Φ28", "Φ32", "Φ36-40", "Φ36", "Φ40"],
|
|
materials: ["HPB300", "HRB400", "HRB400E", "HRB500E"]
|
|
};
|
|
|
|
// 尝试加载本地存储的动态筛选项目
|
|
try {
|
|
const dynamicOpts = localStorage.getItem('mysteel_dynamic_options');
|
|
if (dynamicOpts) {
|
|
Object.assign(FILTER_OPTIONS, JSON.parse(dynamicOpts));
|
|
}
|
|
} catch (e) { }
|
|
|
|
// ==========================================
|
|
// 状态守卫区
|
|
// ==========================================
|
|
|
|
// 校验登录状态
|
|
function isUserLoggedIn() {
|
|
// 未登录时页面存在带有 'topbar-nav-login' 类的元素
|
|
const loginElement = document.querySelector('.topbar-nav-login');
|
|
if (loginElement) {
|
|
return false; // 存在“登录”按钮,说明未登录
|
|
}
|
|
return true; // 已登录
|
|
}
|
|
|
|
// 读取本地缓存的筛选条件
|
|
function loadSavedFilters() {
|
|
const defaultFilters = { names: [], specs: [], materials: [], exportFormat: 'csv', exportFilename: '钢材透视价格表', debugMode: false };
|
|
const saved = localStorage.getItem('mysteel_filters');
|
|
if (saved) {
|
|
try {
|
|
return { ...defaultFilters, ...JSON.parse(saved) };
|
|
} catch (e) {
|
|
console.error('解析缓存筛选条件失败', e);
|
|
}
|
|
}
|
|
return defaultFilters;
|
|
}
|
|
|
|
// 保存筛选条件到本地缓存
|
|
function saveFiltersToLocal(filters) {
|
|
localStorage.setItem('mysteel_filters', JSON.stringify(filters));
|
|
}
|
|
|
|
// 获取当前活动筛选条件 (直接从 DOM 获取)
|
|
function getCurrentFilters() {
|
|
const formatEl = document.getElementById('ms-filter-format');
|
|
const filenameEl = document.getElementById('ms-filter-filename');
|
|
const debugModeEl = document.getElementById('ms-debug-mode');
|
|
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),
|
|
exportFormat: formatEl ? formatEl.value : 'csv',
|
|
exportFilename: filenameEl ? filenameEl.value : '钢材透视价格表',
|
|
debugMode: debugModeEl ? debugModeEl.checked : false
|
|
};
|
|
}
|
|
|
|
// ==========================================
|
|
// 构建交互 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 `
|
|
<label style="display:flex; align-items:center; font-size:13px; cursor:pointer;">
|
|
<input type="checkbox" name="ms-filter-${groupName}" value="${opt}" style="margin-right:4px;" ${isChecked}> ${opt}
|
|
</label>
|
|
`;
|
|
}).join('');
|
|
};
|
|
|
|
panel.innerHTML = `
|
|
<div style="font-size:16px; font-weight:bold; margin-bottom:15px; border-bottom:1px solid #eee; padding-bottom:8px; display:flex; justify-content:space-between; align-items:center;">
|
|
<span>高级筛选配置</span>
|
|
<button id="ms-extract-options-btn" title="从当前页面获取筛选项目并更新到脚本配置中" style="background:none; border:none; cursor:pointer; color:#1890ff; padding:2px; display:flex; align-items:center; justify-content:center; border-radius:4px; outline:none;">
|
|
<svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round">
|
|
<polyline points="23 4 23 10 17 10"></polyline>
|
|
<polyline points="1 20 1 14 7 14"></polyline>
|
|
<path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"></path>
|
|
</svg>
|
|
</button>
|
|
</div>
|
|
<div style="margin-bottom:12px;">
|
|
<div style="font-size:13px; color:#333; font-weight:bold; margin-bottom:8px;">类别:</div>
|
|
<div id="ms-names-container" style="display:grid; grid-template-columns:repeat(5, 1fr); gap:8px 4px;">${buildCheckboxes('names', FILTER_OPTIONS.names)}</div>
|
|
</div>
|
|
<div style="margin-bottom:12px;">
|
|
<div style="font-size:13px; color:#333; font-weight:bold; margin-bottom:8px;">线径:</div>
|
|
<div id="ms-specs-container" style="display:grid; grid-template-columns:repeat(5, 1fr); gap:8px 4px;">${buildCheckboxes('specs', FILTER_OPTIONS.specs)}</div>
|
|
</div>
|
|
<div style="margin-bottom:15px;">
|
|
<div style="font-size:13px; color:#333; font-weight:bold; margin-bottom:8px;">材质:</div>
|
|
<div id="ms-materials-container" style="display:grid; grid-template-columns:repeat(4, 1fr); gap:8px 4px;">${buildCheckboxes('materials', FILTER_OPTIONS.materials)}</div>
|
|
</div>
|
|
<div style="font-size:16px; font-weight:bold; margin-bottom:15px; border-bottom:1px solid #eee; padding-bottom:8px;">导出配置</div>
|
|
<div style="margin-bottom:12px; display:flex; gap:10px; align-items:flex-end;">
|
|
<div style="flex:1;">
|
|
<div style="font-size:13px; color:#333; font-weight:bold; margin-bottom:6px;">导出格式:</div>
|
|
<select id="ms-filter-format" style="width:100%; padding:4px 8px; font-size:13px; height:28px; box-sizing:border-box; border:1px solid #ccc; border-radius:4px; outline:none;">
|
|
<option value="csv" ${savedFilters.exportFormat === 'csv' ? 'selected' : ''}>CSV</option>
|
|
<option value="xlsx" ${savedFilters.exportFormat === 'xlsx' ? 'selected' : ''}>XLSX</option>
|
|
</select>
|
|
</div>
|
|
<div style="flex:2;">
|
|
<div style="font-size:13px; color:#333; font-weight:bold; margin-bottom:6px;">自定义文件名称:</div>
|
|
<input type="text" id="ms-filter-filename" value="${savedFilters.exportFilename || '钢材透视价格表'}" style="width:100%; padding:4px 8px; font-size:13px; height:28px; box-sizing:border-box; border:1px solid #ccc; border-radius:4px; outline:none;">
|
|
</div>
|
|
</div>
|
|
<div style="font-size:16px; font-weight:bold; margin-bottom:15px; border-bottom:1px solid #eee; padding-bottom:8px; margin-top:15px;">开发者选项</div>
|
|
<div style="margin-bottom:12px; display:flex; justify-content:space-between; align-items:center;">
|
|
<label style="display:flex; align-items:center; font-size:13px; cursor:pointer; color:#ff4d4f; font-weight:bold;">
|
|
<input type="checkbox" id="ms-debug-mode" style="margin-right:4px;" ${savedFilters.debugMode ? 'checked' : ''}> DEBUG_MODE
|
|
</label>
|
|
<button id="ms-reset-options-btn" title="恢复出厂设置并清除所有缓存数据" style="background:#ff4d4f; color:#fff; border:none; padding:4px 8px; border-radius:4px; font-size:12px; cursor:pointer; font-weight:bold; outline:none;">RESET</button>
|
|
</div>
|
|
|
|
<button id="ms-close-panel-btn" style="width:100%; padding:8px; background:#1890ff; color:#fff; border:none; border-radius:4px; cursor:pointer; font-weight:bold;">保存并关闭</button>
|
|
`;
|
|
|
|
// --- UI 交互逻辑 ---
|
|
gearBtn.addEventListener('mouseenter', () => {
|
|
if (panel.style.display === 'block') return;
|
|
const f = getCurrentFilters();
|
|
const formatF = (arr) => arr.length > 0 ? arr.join(', ') : '全部';
|
|
tooltip.innerHTML = `
|
|
<div style="font-weight:bold; margin-bottom:4px;">当前筛选状态:</div>
|
|
<div>类别:${formatF(f.names)}</div>
|
|
<div>线径:${formatF(f.specs)}</div>
|
|
<div>材质:${formatF(f.materials)}</div>
|
|
<div style="margin-top:4px; border-top:1px solid rgba(255,255,255,0.2); padding-top:4px;">
|
|
格式:${f.exportFormat.toUpperCase()}
|
|
</div>
|
|
`;
|
|
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-extract-options-btn').addEventListener('click', () => {
|
|
const getList = (num) => {
|
|
const ul = document.querySelector(`.table-filter-select[sort-line-num="${num}"] .table-filter-select-dropdown-list`);
|
|
if (!ul) return [];
|
|
return Array.from(ul.querySelectorAll('li')).map(li => li.innerText.trim());
|
|
};
|
|
const extractedNames = getList('1');
|
|
const extractedSpecs = getList('2');
|
|
const extractedMaterials = getList('3');
|
|
|
|
if (extractedNames.length === 0 && extractedSpecs.length === 0 && extractedMaterials.length === 0) {
|
|
showToast('提取失败:当前页面未发现相关的筛选列表节点!\n请确认当前在列表页或页面结构未改变。', 'error');
|
|
return;
|
|
}
|
|
|
|
// 对提取的数据进行格式化处理 (类别倒序,线径从小到大)
|
|
const sortedNames = extractedNames.reverse();
|
|
const sortedSpecs = extractedSpecs.sort((a, b) => {
|
|
const nA = parseFloat(a.replace('Φ', '').split('-')[0]) || 0;
|
|
const nB = parseFloat(b.replace('Φ', '').split('-')[0]) || 0;
|
|
return nA - nB;
|
|
});
|
|
|
|
// 更新内存与本地缓存
|
|
FILTER_OPTIONS.names = sortedNames;
|
|
FILTER_OPTIONS.specs = sortedSpecs;
|
|
FILTER_OPTIONS.materials = extractedMaterials;
|
|
localStorage.setItem('mysteel_dynamic_options', JSON.stringify({
|
|
names: sortedNames,
|
|
specs: sortedSpecs,
|
|
materials: extractedMaterials
|
|
}));
|
|
|
|
// 更新 DOM 呈现
|
|
document.getElementById('ms-names-container').innerHTML = buildCheckboxes('names', FILTER_OPTIONS.names);
|
|
document.getElementById('ms-specs-container').innerHTML = buildCheckboxes('specs', FILTER_OPTIONS.specs);
|
|
document.getElementById('ms-materials-container').innerHTML = buildCheckboxes('materials', FILTER_OPTIONS.materials);
|
|
|
|
const code = ` const FILTER_OPTIONS = {\n names: ${JSON.stringify(sortedNames)},\n specs: ${JSON.stringify(sortedSpecs)},\n materials: ${JSON.stringify(extractedMaterials)}\n };`;
|
|
console.log('【提取并排序后的筛选项目】\\n' + code);
|
|
|
|
if (navigator.clipboard && window.isSecureContext) {
|
|
navigator.clipboard.writeText(code).then(() => {
|
|
showToast('提取成功!代码已复制到剪贴板。', 'success');
|
|
}).catch(() => {
|
|
showToast('提取成功!请按 F12 前往控制台复制。', 'success');
|
|
});
|
|
} else {
|
|
showToast('提取成功!请按 F12 前往控制台复制。', 'success');
|
|
}
|
|
});
|
|
|
|
// 绑定恢复出厂设置按钮事件
|
|
document.getElementById('ms-reset-options-btn').addEventListener('click', () => {
|
|
if (confirm('确定要恢复出厂设置吗?\n这将清除所有保存的配置和提取的筛选参数。')) {
|
|
localStorage.removeItem('mysteel_filters');
|
|
localStorage.removeItem('mysteel_dynamic_options');
|
|
showToast('恢复出厂设置成功!即将刷新页面...', 'success');
|
|
setTimeout(() => window.location.reload(), 1000);
|
|
}
|
|
});
|
|
|
|
// 绑定保存关闭按钮事件
|
|
document.getElementById('ms-close-panel-btn').addEventListener('click', () => {
|
|
const active = getCurrentFilters();
|
|
saveFiltersToLocal(active); // 写入 localStorage
|
|
panel.style.display = 'none';
|
|
showToast('配置已保存', 'success');
|
|
});
|
|
}
|
|
|
|
// ==========================================
|
|
// 引擎 A: 详情页单页抓取
|
|
// ==========================================
|
|
function startSingleProcess() {
|
|
const filters = getCurrentFilters();
|
|
// 🔒 登录状态守卫拦截
|
|
if (!filters.debugMode && !isUserLoggedIn()) {
|
|
showToast('请登录 Mysteel 账号后重试!', 'error');
|
|
return;
|
|
}
|
|
|
|
const btn = document.getElementById('mysteel-action-btn');
|
|
const originalText = btn.innerText;
|
|
btn.innerText = '正在提取...';
|
|
btn.disabled = true;
|
|
|
|
try {
|
|
// 提取日期:从 <span class="content-info-text publish-time"> 提取
|
|
const dateEl = document.querySelector('.content-info-text.publish-time');
|
|
if (!dateEl) {
|
|
showToast('未找到页面的发布时间,请确认当前网页结构!', 'error');
|
|
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) {
|
|
generatePivotExport(flatData, '单日');
|
|
} else {
|
|
showToast('根据当前筛选条件,未提取到有效数据!', 'warning');
|
|
}
|
|
} catch (error) {
|
|
if (error.message === 'NO_PERMISSION') {
|
|
showToast('当前账号暂无权限查看价格数据,请确认是否已购买或开通相关权限!', 'warning');
|
|
} else {
|
|
console.error('详情页提取出错:', error);
|
|
showToast('发生错误,请查看控制台日志。', 'error');
|
|
}
|
|
} finally {
|
|
btn.innerText = originalText;
|
|
btn.disabled = false;
|
|
}
|
|
}
|
|
|
|
// ==========================================
|
|
// 引擎 B: 列表页批量抓取
|
|
// ==========================================
|
|
async function startBatchProcess() {
|
|
const filters = getCurrentFilters();
|
|
// 🔒 登录状态守卫拦截
|
|
if (!filters.debugMode && !isUserLoggedIn()) {
|
|
showToast('请登录 Mysteel 账号后重试!', 'error');
|
|
return;
|
|
}
|
|
|
|
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) {
|
|
showToast('未发现符合条件的链接!', 'warning');
|
|
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);
|
|
}
|
|
} else {
|
|
showToast(`日期 ${linkObj.date} 页面加载失败或因跨域重定向,已跳过`, 'warning');
|
|
}
|
|
} catch (err) {
|
|
if (err.message === 'NO_PERMISSION') throw err;
|
|
console.error(`渲染 ${linkObj.date} 失败:`, err);
|
|
}
|
|
}
|
|
|
|
btn.innerText = '正在生成数据透视表...';
|
|
|
|
if (flatData.length > 0) {
|
|
generatePivotExport(flatData, '批量');
|
|
} else {
|
|
showToast('根据当前筛选条件,未能提取到任何数据!', 'warning');
|
|
}
|
|
|
|
} catch (error) {
|
|
if (error.message === 'NO_PERMISSION') {
|
|
showToast('当前账号暂无权限查看价格数据,请确认是否已购买或开通相关权限!', 'warning');
|
|
} else {
|
|
console.error('批量处理出错:', error);
|
|
showToast('发生错误,请查看控制台。', 'error');
|
|
}
|
|
} finally {
|
|
btn.innerText = originalText;
|
|
btn.disabled = false;
|
|
btn.style.backgroundColor = '#fa541c';
|
|
}
|
|
}
|
|
|
|
// ==========================================
|
|
// 公共组件区
|
|
// ==========================================
|
|
|
|
// Toast 提示组件
|
|
function showToast(message, type = 'info') {
|
|
const toast = document.createElement('div');
|
|
toast.innerText = message;
|
|
|
|
let bgColor = '#1890ff';
|
|
if (type === 'error') bgColor = '#ff4d4f';
|
|
else if (type === 'success') bgColor = '#52c41a';
|
|
else if (type === 'warning') bgColor = '#faad14';
|
|
|
|
Object.assign(toast.style, {
|
|
position: 'fixed',
|
|
top: '30vh',
|
|
left: '50%',
|
|
transform: 'translateX(-50%)',
|
|
backgroundColor: bgColor,
|
|
color: '#fff',
|
|
padding: '12px 24px',
|
|
borderRadius: '4px',
|
|
boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
|
|
zIndex: '999999',
|
|
fontSize: '14px',
|
|
whiteSpace: 'pre-wrap',
|
|
opacity: '0',
|
|
transition: 'opacity 0.3s, top 0.3s',
|
|
pointerEvents: 'none',
|
|
textAlign: 'center',
|
|
lineHeight: '1.5'
|
|
});
|
|
|
|
document.body.appendChild(toast);
|
|
|
|
// 动画显示
|
|
requestAnimationFrame(() => {
|
|
toast.style.opacity = '1';
|
|
toast.style.top = '33vh';
|
|
});
|
|
|
|
// 定时移除
|
|
setTimeout(() => {
|
|
toast.style.opacity = '0';
|
|
toast.style.top = '30vh';
|
|
setTimeout(() => {
|
|
if (toast.parentNode) {
|
|
toast.parentNode.removeChild(toast);
|
|
}
|
|
}, 300);
|
|
}, 5000);
|
|
}
|
|
|
|
// 获取列表页的日期链接
|
|
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;
|
|
|
|
if (tdPrice.querySelector('.icon-key')) {
|
|
if (!filters.debugMode) throw new Error('NO_PERMISSION');
|
|
}
|
|
|
|
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();
|
|
let currentPrice = parseFloat(priceStr);
|
|
|
|
if (!name) continue;
|
|
|
|
if (isNaN(currentPrice)) {
|
|
if (!filters.debugMode) continue;
|
|
currentPrice = tdPrice.querySelector('.icon-key') ? '无权限(锁)' : (priceStr || '无数据');
|
|
}
|
|
|
|
const uniqueKey = `${name}_${spec}_${material}`;
|
|
|
|
if (!dataMap.has(uniqueKey)) {
|
|
dataMap.set(uniqueKey, {
|
|
date: dateStr,
|
|
name: name,
|
|
spec: spec,
|
|
material: material,
|
|
priceNum: currentPrice
|
|
});
|
|
} else {
|
|
const existing = dataMap.get(uniqueKey);
|
|
if (typeof currentPrice === 'number' && typeof existing.priceNum === 'number') {
|
|
if (currentPrice < existing.priceNum) {
|
|
existing.priceNum = currentPrice;
|
|
}
|
|
} else if (typeof currentPrice === 'number') {
|
|
existing.priceNum = currentPrice;
|
|
}
|
|
}
|
|
}
|
|
return Array.from(dataMap.values());
|
|
}
|
|
|
|
// 数据透视与生成 CSV 或 XLSX
|
|
function generatePivotExport(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;
|
|
});
|
|
|
|
// 读取导出设置
|
|
const filters = getCurrentFilters();
|
|
const exportFormat = filters.exportFormat || 'csv';
|
|
|
|
// 3. 排序逻辑
|
|
const rows = Array.from(pivotMap.values());
|
|
const nameOrder = {};
|
|
FILTER_OPTIONS.names.forEach((n, i) => nameOrder[n] = i);
|
|
const specOrder = {};
|
|
FILTER_OPTIONS.specs.forEach((s, i) => specOrder[s] = i);
|
|
|
|
rows.sort((a, b) => {
|
|
const nA = nameOrder[a.name] !== undefined ? nameOrder[a.name] : 99;
|
|
const nB = nameOrder[b.name] !== undefined ? nameOrder[b.name] : 99;
|
|
if (nA !== nB) return nA - nB;
|
|
|
|
const sA = specOrder[a.spec] !== undefined ? specOrder[a.spec] : 99;
|
|
const sB = specOrder[b.spec] !== undefined ? specOrder[b.spec] : 99;
|
|
return sA - sB;
|
|
});
|
|
|
|
const exportFilename = filters.exportFilename || '钢材透视价格表';
|
|
const d = new Date();
|
|
const Y = d.getFullYear();
|
|
const M = (d.getMonth() + 1).toString().padStart(2, '0');
|
|
const D = d.getDate().toString().padStart(2, '0');
|
|
const H = d.getHours().toString().padStart(2, '0');
|
|
const m = d.getMinutes().toString().padStart(2, '0');
|
|
const S = d.getSeconds().toString().padStart(2, '0');
|
|
const dateStr = `${Y}${M}${D}${H}${m}${S}`;
|
|
const finalFilename = `${exportFilename}_${filePrefix}_${dateStr}`;
|
|
|
|
if (exportFormat === 'xlsx' && typeof XLSX !== 'undefined') {
|
|
const aoa = [];
|
|
aoa.push(['类别', '线径', '材质', ...dateHeaders]);
|
|
rows.forEach(row => {
|
|
const rowData = [row.name, row.spec, row.material];
|
|
uniqueDates.forEach(date => {
|
|
rowData.push(row.pricesByDate[date] !== undefined ? row.pricesByDate[date] : '');
|
|
});
|
|
aoa.push(rowData);
|
|
});
|
|
const ws = XLSX.utils.aoa_to_sheet(aoa);
|
|
const wb = XLSX.utils.book_new();
|
|
XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
|
|
XLSX.writeFile(wb, `${finalFilename}.xlsx`);
|
|
} else {
|
|
// 4. 拼接 CSV 内容
|
|
let csvContent = '\uFEFF';
|
|
csvContent += `类别,线径,材质,${dateHeaders.join(',')}\n`;
|
|
|
|
rows.forEach(row => {
|
|
let rowText = `"${row.name}","${row.spec}","${row.material}"`;
|
|
uniqueDates.forEach(date => {
|
|
const price = row.pricesByDate[date] !== undefined ? 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');
|
|
|
|
link.setAttribute('href', url);
|
|
link.setAttribute('download', `${finalFilename}.csv`);
|
|
|
|
document.body.appendChild(link);
|
|
link.click();
|
|
|
|
document.body.removeChild(link);
|
|
URL.revokeObjectURL(url);
|
|
}
|
|
|
|
showToast('导出成功!已触发下载。', 'success');
|
|
}
|
|
|
|
// 延时加载注入
|
|
window.addEventListener('load', injectUI);
|
|
setTimeout(injectUI, 2000);
|
|
setTimeout(injectUI, 5000);
|
|
|
|
})(); |