添加debug模式

This commit is contained in:
ali
2026-07-29 14:39:45 +08:00
parent 0d4b855718
commit 4b15c4d16e
+134 -20
View File
@@ -2,7 +2,7 @@
// @name Mysteel 钢铁价格提取器 // @name Mysteel 钢铁价格提取器
// @namespace http://tampermonkey.net/ // @namespace http://tampermonkey.net/
// @version 6.5 // @version 6.5
// @description 合并列表页与详情页的抓取逻辑,统一透视表导出csv,支持多维筛选及本地缓存,加入登录状态拦截 // @description 实现列表页与详情页的抓取逻辑,统一透视表导出csv/xlsx,支持多维筛选及本地缓存
// @author ali // @author ali
// @mail solitude@hraulein.com // @mail solitude@hraulein.com
// @match *://*.mysteel.com/market/* // @match *://*.mysteel.com/market/*
@@ -19,12 +19,20 @@
const isDetailPage = window.location.href.includes('/m/'); const isDetailPage = window.location.href.includes('/m/');
// 预设筛选常量 // 预设筛选常量
const FILTER_OPTIONS = { let FILTER_OPTIONS = {
names: ['高线', '螺纹钢', '盘螺'], names: ['盘螺', '螺纹钢', '高线', '测试'],
specs: ['Φ6', 'Φ8', 'Φ8-10', 'Φ10', 'Φ12', 'Φ14', 'Φ16', 'Φ18', 'Φ20', 'Φ22', 'Φ25', 'Φ28', 'Φ32', 'Φ36', 'Φ36-40', 'Φ40'], specs: ['Φ6', 'Φ8', 'Φ8-10', 'Φ10', 'Φ12', 'Φ14', 'Φ16', 'Φ18', 'Φ20', 'Φ22', 'Φ25', 'Φ28', 'Φ32', 'Φ36', 'Φ36-40', 'Φ40'],
materials: ['HPB300', 'HRB400', 'HRB400E', 'HRB500E'] materials: ['HPB300', 'HRB400', 'HRB400E', 'HRB500E']
}; };
// 尝试加载本地存储的动态筛选项目
try {
const dynamicOpts = localStorage.getItem('mysteel_dynamic_options');
if (dynamicOpts) {
Object.assign(FILTER_OPTIONS, JSON.parse(dynamicOpts));
}
} catch (e) { }
// ========================================== // ==========================================
// 状态守卫区 // 状态守卫区
// ========================================== // ==========================================
@@ -41,7 +49,7 @@
// 读取本地缓存的筛选条件 // 读取本地缓存的筛选条件
function loadSavedFilters() { function loadSavedFilters() {
const defaultFilters = { names: [], specs: [], materials: [], exportFormat: 'csv', exportFilename: '钢材透视价格表' }; const defaultFilters = { names: [], specs: [], materials: [], exportFormat: 'csv', exportFilename: '钢材透视价格表', debugMode: false };
const saved = localStorage.getItem('mysteel_filters'); const saved = localStorage.getItem('mysteel_filters');
if (saved) { if (saved) {
try { try {
@@ -62,12 +70,14 @@
function getCurrentFilters() { function getCurrentFilters() {
const formatEl = document.getElementById('ms-filter-format'); const formatEl = document.getElementById('ms-filter-format');
const filenameEl = document.getElementById('ms-filter-filename'); const filenameEl = document.getElementById('ms-filter-filename');
const debugModeEl = document.getElementById('ms-debug-mode');
return { return {
names: Array.from(document.querySelectorAll('input[name="ms-filter-names"]:checked')).map(el => el.value), 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), 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), materials: Array.from(document.querySelectorAll('input[name="ms-filter-materials"]:checked')).map(el => el.value),
exportFormat: formatEl ? formatEl.value : 'csv', exportFormat: formatEl ? formatEl.value : 'csv',
exportFilename: filenameEl ? filenameEl.value : '钢材透视价格表' exportFilename: filenameEl ? filenameEl.value : '钢材透视价格表',
debugMode: debugModeEl ? debugModeEl.checked : false
}; };
} }
@@ -157,15 +167,15 @@
<div style="font-size:16px; font-weight:bold; margin-bottom:15px; border-bottom:1px solid #eee; padding-bottom:8px;">高级筛选配置</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;"> <div style="margin-bottom:12px;">
<div style="font-size:13px; color:#333; font-weight:bold; margin-bottom:8px;">类别:</div> <div style="font-size:13px; color:#333; font-weight:bold; margin-bottom:8px;">类别:</div>
<div style="display:grid; grid-template-columns:repeat(5, 1fr); gap:8px 4px;">${buildCheckboxes('names', FILTER_OPTIONS.names)}</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>
<div style="margin-bottom:12px;"> <div style="margin-bottom:12px;">
<div style="font-size:13px; color:#333; font-weight:bold; margin-bottom:8px;">线径:</div> <div style="font-size:13px; color:#333; font-weight:bold; margin-bottom:8px;">线径:</div>
<div style="display:grid; grid-template-columns:repeat(5, 1fr); gap:8px 4px;">${buildCheckboxes('specs', FILTER_OPTIONS.specs)}</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>
<div style="margin-bottom:15px;"> <div style="margin-bottom:15px;">
<div style="font-size:13px; color:#333; font-weight:bold; margin-bottom:8px;">材质:</div> <div style="font-size:13px; color:#333; font-weight:bold; margin-bottom:8px;">材质:</div>
<div style="display:grid; grid-template-columns:repeat(4, 1fr); gap:8px 4px;">${buildCheckboxes('materials', FILTER_OPTIONS.materials)}</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>
<div style="font-size:16px; font-weight:bold; margin-bottom:15px; border-bottom:1px solid #eee; padding-bottom:8px;">导出配置</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="margin-bottom:12px; display:flex; gap:10px; align-items:flex-end;">
@@ -181,6 +191,15 @@
<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;"> <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> </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;">
<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>
</div>
<div style="margin-bottom:15px;">
<button id="ms-extract-options-btn" style="width:100%; padding:6px; background:#fff; color:#ff4d4f; border:1px solid #ff4d4f; border-radius:4px; cursor:pointer; font-weight:bold; font-size:12px;">更新/提取页面筛选项目</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> <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>
`; `;
@@ -217,6 +236,59 @@
container.appendChild(gearBtn); container.appendChild(gearBtn);
document.body.appendChild(container); 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-close-panel-btn').addEventListener('click', () => { document.getElementById('ms-close-panel-btn').addEventListener('click', () => {
const active = getCurrentFilters(); const active = getCurrentFilters();
@@ -230,8 +302,9 @@
// 引擎 A: 详情页单页抓取 // 引擎 A: 详情页单页抓取
// ========================================== // ==========================================
function startSingleProcess() { function startSingleProcess() {
const filters = getCurrentFilters();
// 🔒 登录状态守卫拦截 // 🔒 登录状态守卫拦截
if (!isUserLoggedIn()) { if (!filters.debugMode && !isUserLoggedIn()) {
showToast('请登录 Mysteel 账号后重试!', 'error'); showToast('请登录 Mysteel 账号后重试!', 'error');
return; return;
} }
@@ -278,8 +351,9 @@
// 引擎 B: 列表页批量抓取 // 引擎 B: 列表页批量抓取
// ========================================== // ==========================================
async function startBatchProcess() { async function startBatchProcess() {
const filters = getCurrentFilters();
// 🔒 登录状态守卫拦截 // 🔒 登录状态守卫拦截
if (!isUserLoggedIn()) { if (!filters.debugMode && !isUserLoggedIn()) {
showToast('请登录 Mysteel 账号后重试!', 'error'); showToast('请登录 Mysteel 账号后重试!', 'error');
return; return;
} }
@@ -479,7 +553,7 @@
if (!tdBreed || !tdSpec || !tdMaterial || !tdPrice) continue; if (!tdBreed || !tdSpec || !tdMaterial || !tdPrice) continue;
if (tdPrice.querySelector('.icon-key')) { if (tdPrice.querySelector('.icon-key')) {
throw new Error('NO_PERMISSION'); if (!filters.debugMode) throw new Error('NO_PERMISSION');
} }
const cleanText = (element) => { const cleanText = (element) => {
@@ -499,13 +573,18 @@
if (filters.materials.length > 0 && !filters.materials.includes(material)) continue; if (filters.materials.length > 0 && !filters.materials.includes(material)) continue;
const priceStr = tdPrice.innerText.replace(/,/g, '').trim(); const priceStr = tdPrice.innerText.replace(/,/g, '').trim();
const currentPrice = parseFloat(priceStr); let currentPrice = parseFloat(priceStr);
if (!name || isNaN(currentPrice)) continue; if (!name) continue;
if (isNaN(currentPrice)) {
if (!filters.debugMode) continue;
currentPrice = tdPrice.querySelector('.icon-key') ? '无权限(锁)' : (priceStr || '无数据');
}
const uniqueKey = `${name}_${spec}_${material}`; const uniqueKey = `${name}_${spec}_${material}`;
if (!dataMap.has(uniqueKey) || currentPrice < dataMap.get(uniqueKey).priceNum) { if (!dataMap.has(uniqueKey)) {
dataMap.set(uniqueKey, { dataMap.set(uniqueKey, {
date: dateStr, date: dateStr,
name: name, name: name,
@@ -513,6 +592,15 @@
material: material, material: material,
priceNum: currentPrice 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()); return Array.from(dataMap.values());
@@ -552,18 +640,42 @@
// 读取导出设置 // 读取导出设置
const filters = getCurrentFilters(); const filters = getCurrentFilters();
const exportFormat = filters.exportFormat || 'csv'; 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 exportFilename = filters.exportFilename || '钢材透视价格表';
const d = new Date(); const d = new Date();
const dateStr = `${d.getFullYear()}${(d.getMonth() + 1).toString().padStart(2, '0')}${d.getDate().toString().padStart(2, '0')}`; 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}`; const finalFilename = `${exportFilename}_${filePrefix}_${dateStr}`;
if (exportFormat === 'xlsx' && typeof XLSX !== 'undefined') { if (exportFormat === 'xlsx' && typeof XLSX !== 'undefined') {
const aoa = []; const aoa = [];
aoa.push(['类别', '线径', '材质', ...dateHeaders]); aoa.push(['类别', '线径', '材质', ...dateHeaders]);
pivotMap.forEach(row => { rows.forEach(row => {
const rowData = [row.name, row.spec, row.material]; const rowData = [row.name, row.spec, row.material];
uniqueDates.forEach(date => { uniqueDates.forEach(date => {
rowData.push(row.pricesByDate[date] ? row.pricesByDate[date] : ''); rowData.push(row.pricesByDate[date] !== undefined ? row.pricesByDate[date] : '');
}); });
aoa.push(rowData); aoa.push(rowData);
}); });
@@ -572,14 +684,14 @@
XLSX.utils.book_append_sheet(wb, ws, "Sheet1"); XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
XLSX.writeFile(wb, `${finalFilename}.xlsx`); XLSX.writeFile(wb, `${finalFilename}.xlsx`);
} else { } else {
// 3. 拼接 CSV 内容 // 4. 拼接 CSV 内容
let csvContent = '\uFEFF'; let csvContent = '\uFEFF';
csvContent += `类别,线径,材质,${dateHeaders.join(',')}\n`; csvContent += `类别,线径,材质,${dateHeaders.join(',')}\n`;
pivotMap.forEach(row => { rows.forEach(row => {
let rowText = `"${row.name}","${row.spec}","${row.material}"`; let rowText = `"${row.name}","${row.spec}","${row.material}"`;
uniqueDates.forEach(date => { uniqueDates.forEach(date => {
const price = row.pricesByDate[date] ? row.pricesByDate[date] : ''; const price = row.pricesByDate[date] !== undefined ? row.pricesByDate[date] : '';
rowText += `,"${price}"`; rowText += `,"${price}"`;
}); });
csvContent += rowText + '\n'; csvContent += rowText + '\n';
@@ -599,6 +711,8 @@
document.body.removeChild(link); document.body.removeChild(link);
URL.revokeObjectURL(url); URL.revokeObjectURL(url);
} }
showToast('导出成功!已触发下载。', 'success');
} }
// 延时加载注入 // 延时加载注入