Update micBrowserSession.js via upload script - 2026-09-20 17:32:47
This commit is contained in:
parent
758561d93b
commit
7ef00c9a72
|
|
@ -0,0 +1,318 @@
|
||||||
|
// MIC产品上传 — 浏览器会话
|
||||||
|
// 每个会话对应一个无头 Chromium 实例,通过 CDP screencast 把画面实时推给前端,
|
||||||
|
// 并在"手动登录"阶段把前端鼠标/键盘事件转发进浏览器。选择器与填表流程照搬自
|
||||||
|
// uploader_enhanced.py(v33.0),仅去掉了本地 .env 自动登录(改为人工登录)
|
||||||
|
// 和批量循环(本版本一次只处理一个产品)。
|
||||||
|
|
||||||
|
const { chromium } = require('playwright');
|
||||||
|
|
||||||
|
function sleep(ms) {
|
||||||
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
class MicBrowserSession {
|
||||||
|
constructor(id, { onFrame, onLog } = {}) {
|
||||||
|
this.id = id;
|
||||||
|
this.onFrame = onFrame || (() => {});
|
||||||
|
this.onLog = onLog || (() => {});
|
||||||
|
this.browser = null;
|
||||||
|
this.context = null;
|
||||||
|
this.page = null;
|
||||||
|
this.cdp = null;
|
||||||
|
this.viewport = { width: 1280, height: 800 };
|
||||||
|
this.closed = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
log(msg, level = 'INFO') {
|
||||||
|
this.onLog({ level, msg, ts: Date.now() });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------ 生命周期 ------------------------------
|
||||||
|
|
||||||
|
async start() {
|
||||||
|
this.browser = await chromium.launch({
|
||||||
|
headless: true,
|
||||||
|
args: ['--disable-blink-features=AutomationControlled'],
|
||||||
|
});
|
||||||
|
this.context = await this.browser.newContext({
|
||||||
|
viewport: this.viewport,
|
||||||
|
locale: 'en-US',
|
||||||
|
userAgent:
|
||||||
|
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' +
|
||||||
|
'(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
|
||||||
|
});
|
||||||
|
this.page = await this.context.newPage();
|
||||||
|
this.cdp = await this.context.newCDPSession(this.page);
|
||||||
|
|
||||||
|
await this.cdp.send('Page.startScreencast', {
|
||||||
|
format: 'jpeg',
|
||||||
|
quality: 70,
|
||||||
|
maxWidth: this.viewport.width,
|
||||||
|
maxHeight: this.viewport.height,
|
||||||
|
everyNthFrame: 1,
|
||||||
|
});
|
||||||
|
this.cdp.on('Page.screencastFrame', async (frame) => {
|
||||||
|
this.onFrame(frame.data); // base64 jpeg,前端直接拼成 data URL 画到 canvas
|
||||||
|
try {
|
||||||
|
await this.cdp.send('Page.screencastFrameAck', { sessionId: frame.sessionId });
|
||||||
|
} catch (e) {
|
||||||
|
// 会话可能已经在关闭中,忽略
|
||||||
|
}
|
||||||
|
});
|
||||||
|
this.log('浏览器会话已启动');
|
||||||
|
}
|
||||||
|
|
||||||
|
async close() {
|
||||||
|
if (this.closed) return;
|
||||||
|
this.closed = true;
|
||||||
|
try { await this.cdp?.send('Page.stopScreencast'); } catch (e) {}
|
||||||
|
try { await this.browser?.close(); } catch (e) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// -------------------------- 输入转发(登录阶段用) --------------------------
|
||||||
|
// 前端 canvas 按 viewport 等比缩放后把坐标换算回真实像素再传过来
|
||||||
|
|
||||||
|
async mouseMove(x, y) { await this.page.mouse.move(x, y); }
|
||||||
|
async mouseDown(x, y, button = 'left') { await this.page.mouse.move(x, y); await this.page.mouse.down({ button }); }
|
||||||
|
async mouseUp(x, y, button = 'left') { await this.page.mouse.move(x, y); await this.page.mouse.up({ button }); }
|
||||||
|
async wheel(dx, dy) { await this.page.mouse.wheel(dx, dy); }
|
||||||
|
async keyDown(key) { try { await this.page.keyboard.down(key); } catch (e) {} }
|
||||||
|
async keyUp(key) { try { await this.page.keyboard.up(key); } catch (e) {} }
|
||||||
|
async typeText(text) { await this.page.keyboard.insertText(text); }
|
||||||
|
|
||||||
|
// ------------------------------ 导航 ------------------------------
|
||||||
|
|
||||||
|
async gotoLogin() {
|
||||||
|
this.log('正在打开 Made-in-China 登录页...');
|
||||||
|
try {
|
||||||
|
await this.page.goto('https://login.made-in-china.com/', {
|
||||||
|
waitUntil: 'domcontentloaded',
|
||||||
|
timeout: 30000,
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
this.log(`登录页加载警告: ${e.message}`, 'WARNING');
|
||||||
|
}
|
||||||
|
this.log('请在右侧画面里手动完成登录,登录成功后点击"已登录,继续"');
|
||||||
|
}
|
||||||
|
|
||||||
|
// templateUrl 形如 https://membercenter.made-in-china.com/productmanage.do?xcase=addSimilar&prodId=xxxx
|
||||||
|
// 由品类→模板ID配置表给出(见 micUploadRoutes.js 的 /templates 接口)
|
||||||
|
async gotoPublishTemplate(templateUrl) {
|
||||||
|
for (let attempt = 1; attempt <= 3; attempt++) {
|
||||||
|
try {
|
||||||
|
await this.page.goto(templateUrl, { waitUntil: 'domcontentloaded', timeout: 40000 });
|
||||||
|
break;
|
||||||
|
} catch (e) {
|
||||||
|
if (String(e).includes('interrupted') && attempt < 3) {
|
||||||
|
this.log(`导航被中断(第${attempt}次),等待后重试...`, 'WARNING');
|
||||||
|
await sleep(4000);
|
||||||
|
} else {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await sleep(3000);
|
||||||
|
this.log('已进入仿造发布页面');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------ 表单填写 ------------------------------
|
||||||
|
|
||||||
|
async slowType(locator, text, delay = 20) {
|
||||||
|
await locator.click();
|
||||||
|
await sleep(150);
|
||||||
|
await locator.press('Control+a');
|
||||||
|
await locator.press('Delete');
|
||||||
|
await sleep(50);
|
||||||
|
await locator.type(text, { delay });
|
||||||
|
}
|
||||||
|
|
||||||
|
async checkCenterWord() {
|
||||||
|
let clicked = false;
|
||||||
|
try {
|
||||||
|
await this.page.click('.J-center-words input[type="checkbox"]', { timeout: 3000 });
|
||||||
|
this.log('✓ 已勾选中心词');
|
||||||
|
clicked = true;
|
||||||
|
} catch (e) { /* 走 JS 兜底 */ }
|
||||||
|
|
||||||
|
if (!clicked) {
|
||||||
|
try {
|
||||||
|
const result = await this.page.evaluate(() => {
|
||||||
|
const containers = document.querySelectorAll('.J-center-words, .center-words, [class*="center-word"]');
|
||||||
|
for (const cont of containers) {
|
||||||
|
const cb = cont.querySelector('input[type="checkbox"]');
|
||||||
|
if (cb && !cb.checked) { cb.click(); return true; }
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
if (result) { this.log('✓ 已通过JS勾选中心词'); clicked = true; }
|
||||||
|
} catch (e) { /* 忽略 */ }
|
||||||
|
}
|
||||||
|
if (!clicked) this.log('⚠️ 未能勾选中心词,继续执行', 'WARNING');
|
||||||
|
|
||||||
|
await sleep(1500);
|
||||||
|
try { await this.page.waitForLoadState('networkidle', { timeout: 5000 }); } catch (e) {}
|
||||||
|
await sleep(500);
|
||||||
|
}
|
||||||
|
|
||||||
|
async fillTitle(name) {
|
||||||
|
const el = await this.page.waitForSelector('textarea[name="prodName"]', { timeout: 15000 });
|
||||||
|
await this.slowType(el, name, 20);
|
||||||
|
await el.evaluate((e) => e.blur());
|
||||||
|
await this.page.mouse.click(100, 250);
|
||||||
|
await sleep(800);
|
||||||
|
this.log('✓ 产品名称已填写');
|
||||||
|
}
|
||||||
|
|
||||||
|
async fillKeywords(keywords) {
|
||||||
|
try {
|
||||||
|
await this.page.waitForSelector('#prodKeyword0', { timeout: 10000 });
|
||||||
|
} catch (e) {
|
||||||
|
this.log(`⚠️ 关键词区域未出现,尝试继续: ${e.message}`, 'WARNING');
|
||||||
|
}
|
||||||
|
let filled = 0;
|
||||||
|
for (let i = 0; i < keywords.length; i++) {
|
||||||
|
try {
|
||||||
|
const el = await this.page.waitForSelector(`#prodKeyword${i}`, { timeout: 8000 });
|
||||||
|
await el.scrollIntoViewIfNeeded();
|
||||||
|
await this.slowType(el, keywords[i], 15);
|
||||||
|
filled++;
|
||||||
|
await sleep(100);
|
||||||
|
} catch (e) {
|
||||||
|
this.log(`关键词${i + 1}填写失败: ${String(e).slice(0, 60)}`, 'WARNING');
|
||||||
|
break; // 首个关键词就失败说明页面有问题,不继续死等
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.log(`✓ 关键词填写完成 (${filled}/${keywords.length})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async fillModel(model) {
|
||||||
|
const el = await this.page.waitForSelector('input[name="prodModel"]', { timeout: 10000 });
|
||||||
|
await this.slowType(el, model, 20);
|
||||||
|
this.log(`✓ 型号: ${model}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// attrList: [{ name, value }, ...],已由 micFieldMapping.js 净化/排序好
|
||||||
|
async fillAttributes(attrList) {
|
||||||
|
const MAX_ATTRS = 20;
|
||||||
|
const list = attrList.slice(0, MAX_ATTRS);
|
||||||
|
if (list.length === 0) {
|
||||||
|
this.log('⚠️ 没有可填写的产品属性(字段均为空)', 'WARNING');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.page.locator('#JcustomPropName0').scrollIntoViewIfNeeded();
|
||||||
|
await sleep(1000);
|
||||||
|
} catch (e) {
|
||||||
|
this.log(`⚠️ 无法滚动到属性区域: ${e.message}`, 'WARNING');
|
||||||
|
}
|
||||||
|
|
||||||
|
const fillRow = async (rowIndex, name, value) => {
|
||||||
|
const nameId = `JcustomPropName${rowIndex}`;
|
||||||
|
const valueId = `JcustomPropValue${rowIndex}`;
|
||||||
|
try {
|
||||||
|
const nameEl = this.page.locator(`#${nameId}`).first();
|
||||||
|
await nameEl.scrollIntoViewIfNeeded();
|
||||||
|
await this.slowType(nameEl, name, 10);
|
||||||
|
await this.page.evaluate((id) => {
|
||||||
|
document.getElementById(id)?.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
document.getElementById(id)?.dispatchEvent(new Event('change', { bubbles: true }));
|
||||||
|
}, nameId);
|
||||||
|
} catch (e) {
|
||||||
|
this.log(`⚠️ 属性名[${rowIndex}] 失败: ${e.message}`, 'WARNING');
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const valEl = this.page.locator(`#${valueId}`).first();
|
||||||
|
await valEl.scrollIntoViewIfNeeded();
|
||||||
|
await this.slowType(valEl, value, 10);
|
||||||
|
await this.page.evaluate((id) => {
|
||||||
|
document.getElementById(id)?.dispatchEvent(new Event('input', { bubbles: true }));
|
||||||
|
document.getElementById(id)?.dispatchEvent(new Event('change', { bubbles: true }));
|
||||||
|
}, valueId);
|
||||||
|
} catch (e) {
|
||||||
|
this.log(`⚠️ 属性值[${rowIndex}] 失败: ${e.message}`, 'WARNING');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const clickAddButton = async () => {
|
||||||
|
const selectors = [
|
||||||
|
'button:has-text("添加自定义属性")',
|
||||||
|
'a:has-text("添加自定义属性")',
|
||||||
|
'span:has-text("添加自定义属性")',
|
||||||
|
'.J-custom-add-btn',
|
||||||
|
'[class*="add-prop"]',
|
||||||
|
];
|
||||||
|
for (const sel of selectors) {
|
||||||
|
try {
|
||||||
|
const btn = this.page.locator(sel).first();
|
||||||
|
if (await btn.isVisible({ timeout: 2000 })) {
|
||||||
|
const before = await this.page.locator('input[name="customPropName"]').count();
|
||||||
|
await btn.scrollIntoViewIfNeeded();
|
||||||
|
await btn.click();
|
||||||
|
this.log(` 点击添加按钮 (${sel})`);
|
||||||
|
await sleep(1500);
|
||||||
|
try {
|
||||||
|
await this.page.waitForFunction(
|
||||||
|
(n) => document.querySelectorAll('input[name="customPropName"]').length > n,
|
||||||
|
before,
|
||||||
|
{ timeout: 5000 },
|
||||||
|
);
|
||||||
|
const after = await this.page.locator('input[name="customPropName"]').count();
|
||||||
|
return after - 1;
|
||||||
|
} catch (e) {
|
||||||
|
this.log(' 添加后行数未变化', 'WARNING');
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.log(' ❌ 未找到添加自定义属性按钮', 'WARNING');
|
||||||
|
return -1;
|
||||||
|
};
|
||||||
|
|
||||||
|
let customAdded = 0;
|
||||||
|
for (let i = 0; i < list.length; i++) {
|
||||||
|
const { name, value } = list[i];
|
||||||
|
const currentRows = await this.page.locator('input[name="customPropName"]').count();
|
||||||
|
if (i < currentRows) {
|
||||||
|
this.log(`[${i + 1}/${list.length}] 预设行 ${i}: ${name}`);
|
||||||
|
await fillRow(i, name, value);
|
||||||
|
} else {
|
||||||
|
this.log(`[${i + 1}/${list.length}] 新增自定义行: ${name}`);
|
||||||
|
let newIdx = await clickAddButton();
|
||||||
|
if (newIdx < 0) newIdx = (await this.page.locator('input[name="customPropName"]').count()) - 1;
|
||||||
|
if (newIdx >= 0) {
|
||||||
|
await fillRow(newIdx, name, value);
|
||||||
|
customAdded++;
|
||||||
|
} else {
|
||||||
|
this.log(`无法新增第${i + 1}行,跳过`, 'WARNING');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await sleep(300);
|
||||||
|
}
|
||||||
|
this.log(`✅ 产品属性填写完成 (${list.length}项,新增${customAdded}行)`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async submit() {
|
||||||
|
try {
|
||||||
|
const btn = await this.page.waitForSelector('button.J-product-submit', { timeout: 10000 });
|
||||||
|
await btn.scrollIntoViewIfNeeded();
|
||||||
|
await btn.click();
|
||||||
|
this.log('已点击提交按钮');
|
||||||
|
} catch (e) {
|
||||||
|
try {
|
||||||
|
await this.page.click('button:has-text("提交")');
|
||||||
|
this.log('已点击备用提交按钮');
|
||||||
|
} catch (e2) {
|
||||||
|
this.log(`提交失败: ${e2.message}`, 'ERROR');
|
||||||
|
throw e2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await sleep(4000);
|
||||||
|
this.log('✅ 发布流程完成', 'SUCCESS');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { MicBrowserSession };
|
||||||
Loading…
Reference in New Issue