const cheerio = require('cheerio'); const webdriver = require('selenium-webdriver'); var entities = require('html-entities').XmlEntities; const { saveFile } = require('../tools/save-file'); function skuData(driver) { return new Promise(async (resolve, reject) => { let typeList = await driver.findElements(webdriver.By.js(() => document.querySelectorAll('.tb-sku .tb-prop .J_TSaleProp'))) let _sizeList = await typeList[0].findElements(webdriver.By.tagName('li:not(.tb-out-of-stock)')); const sizeList = await _sizeList.filter(async item => { const styleStr = await item.getAttribute('style'); return styleStr.indexOf('none') !== -1; }); let _colorList = await typeList[1].findElements(webdriver.By.tagName('li:not(.tb-out-of-stock)')); const colorList = await _colorList.filter(async function (item) { const styleStr = await item.getAttribute('style'); return styleStr.indexOf('none') != -1; }); let sku = []; let sizeIndex = 0; async function eachSize(sizeIndex) { const size = sizeList[sizeIndex]; let sizeClass = await size.getAttribute('class'); if (sizeClass.indexOf('tb-selected') === -1) { size.click(); } let colorIndex = 0; function eachColor(colorIndex) { return new Promise((resolve2, reject2) => { async function eachColor2(colorIndex) { const color = colorList[colorIndex]; let colorClass = await color.getAttribute('class'); if (colorClass.indexOf('tb-selected') === -1) { color.click(); } await driver.sleep(500); console.log(sizeIndex, colorIndex); const htmlStr = await driver.getPageSource(); const d = getSkuData(htmlStr); if (d) { sku.push(d); } colorIndex++; console.log('colorIndex', colorIndex, colorList.length); if (colorIndex === colorList.length) { color.click(); resolve2(); } else { eachColor2(colorIndex); } } eachColor2(colorIndex) }); } await driver.sleep(500); await eachColor(colorIndex); sizeIndex++; console.log('color完毕', sizeIndex, sizeList.length); if (sizeIndex === sizeList.length) { resolve(sku); } else { eachSize(sizeIndex); } } eachSize(sizeIndex) }); } function getSkuData(htmlStr) { const data = {}; const $ = cheerio.load(htmlStr); data.size = $('[data-property="尺码"] .tb-selected span').text() || $('[data-property="尺寸"] .tb-selected span').text(); if (data.size.indexOf('加入购物车') != -1) { data.size = '默认' } data.color = $('[data-property="颜色分类"] .tb-selected span').text(); console.log(['写入规格:', 'size:', data.size, 'color:', data.color]); data.bigImg = $('#J_ImgBooth').attr('src'); data.colorImg = $('[data-property="颜色分类"] .tb-selected a').attr('style') // console.log([data.colorImg, 'colorImg']); data.colorImg = data.colorImg ? data.colorImg.replace(/(.+)\(([^\>)]+)\)(.+)/igm, '$2') : ''; data.stock = $('#J_EmStock').text(); // console.log([data.stock, 'stock']); data.stock = data.stock ? data.stock.replace(/[^\d]+(\d+)[^\d]+/, '$1') : ''; return data; } exports.skuData = skuData;