const webdriver = require('selenium-webdriver'); const { Options } = require('selenium-webdriver/chrome'); const { Command } = require('selenium-webdriver/lib/command'); const { saveFile } = require('../tools/save-file'); const fs = require('fs'); const { get } = require('superagent'); const caps = webdriver.Capabilities.chrome(); const options = new Options(); // 设置chrome.exe 位置 options.setChromeBinaryPath('C:\\Users\\cr150\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe'); // 设置为开发者模式,防止被各大网站识别出来使用了Selenium options.addArguments('disable-blink-features=AutomationControlled') // 淘宝账号密码 const userName = '18683971105'; const password = 'chengrang.'; /** * * @param {obj} opts 配置 * noImg: false, * strategy: eager normal none */ async function login(opts = {}) { // 不加载图片, 提升速度 if(opts.noImg){ options.addArguments('blink-settings=imagesEnabled=false') } // 页面加载策略 eager normal none if(opts.strategy){ caps.setPageLoadStrategy(opts.strategy); } let driver = new webdriver.Builder() .setChromeOptions(options) .withCapabilities(caps) .build(); // await driver.get('https://login.taobao.com/') await driver.get('https://login.tmall.com') // 判断是否有cookie const cacheCookiesStr = fs.readFileSync('./cookie/cookie.json', 'utf8'); if (cacheCookiesStr) { // cookie登录 const cacheCookies = JSON.parse(cacheCookiesStr); for (let item of cacheCookies) { item.sameSite = 'Lax'; await driver.manage().addCookie(item); } // await driver.get('https://www.taobao.com/'); await driver.get('https://www.tmall.com'); try { const loginEle = await driver.findElement(webdriver.By.xpath('//*[@id="login-info"]/span[1]/a[1]')); console.log('cookie登录成功'); } catch (error) { // 自动登录 await autoLogin(driver); } } else { // 自动登录 await autoLogin(driver); } return driver; } // 自动登录 async function autoLogin(driver) { await driver.get('https://login.taobao.com/member/login.jhtml?tpl_redirect_url=https%3A%2F%2Flumn.tmall.com%2Fsearch.htm%3Fspm%3Da1z10.3-b-s.w5002-15438998724.1.48a63b51L03f6W%26search%3Dy&style=miniall&enup=true&newMini2=true&full_redirect=true&sub=true&from=tmall&allp=assets_css%3D3.0.10/login_pc.css&pms=1599124573437'); // 检测登录框 await driver.wait(webdriver.until.elementLocated(webdriver.By.xpath('//*[@id="fm-login-id"]')), 60000, '未检测到登录框'); // 获取登录元素 const accountEle = await driver.findElement(webdriver.By.xpath('//*[@id="fm-login-id"]')); const passwordEle = await driver.findElement(webdriver.By.xpath('//*[@id="fm-login-password"]')); const submitBtn = await driver.findElement(webdriver.By.xpath('//*[@id="login-form"]/div[4]/button')); // 模拟输入 await accountEle.sendKeys(userName) await passwordEle.sendKeys(password); await submitBtn.click(); await driver.wait(webdriver.until.elementLocated(webdriver.By.xpath('//*[@id="login-info"]/span[1]/a[1]')), 60000, '登陆超时未成功'); console.log('自动登录成功'); // 保存cookie const cookie = await (await driver).manage().getCookies(); saveFile('cookie.json', JSON.stringify(cookie, null, 4), './cookie/'); return driver; } module.exports = login;