自己从0到1开发的,微信小程序【云顶宝藏】求求点个5星好评吧!
需求:拿到所有英雄的信息
思路:点击每个英雄,进入英雄详情页,拿信息,并返回,继续下一个英雄**
最终效果
本地环境 window系统 node版本:v18.16.1
puppeteer中文技术文档: https://pptr.nodejs.cn/guides/query-selectors
英文技术文档:https://pptr.dev/api/puppeteer.mouse.click
示例源码下载:https://chaozhenrihuajianhang.oss-cn-hangzhou.aliyuncs.com/csdn/demo-puppeteer.zip
安装puppeteer
npm install -g cnpm --registry=https://registry.npmmirror.com
cnpm install puppeteer
引入
const puppeteer = require('puppeteer')
puppeteer使用
const main = async () => {// 启动浏览器const browser = await puppeteer.launch({headless: false,defaultViewport: null,args: ['--start-maximized'],ignoreDefaultArgs: ['--enable-automation']}); // 创建一个新页面 const page = await browser.newPage(); // 获取Vue组件的HTML// const html = await page.evaluate(() => document.querySelector('#app').innerHTML)// 同步英雄await initYingxiong(page)// 截取网页的屏幕截图// await page.screenshot({path: 'example.png'});// 关闭浏览器 await browser.close();
}
const initYingxiong = async (page) => {// 访问一个网址 await page.goto('https://lol.qq.com/tft/#/champion');// 等待Vue组件加载完毕await page.waitForSelector('#app');// 延迟1秒await new Promise(resolve => setTimeout(resolve, 1000))await setYingxiong(page)
}
const setYingxiong= async (page) => {// 获取所有英雄的dom元素const elements = await page.$$('.champion-list .champion-item-big');for (let i = 0; i < elements.length; i++) {// 点击每个英雄,进入英雄详情await elements[i].click()// 获取父容器const obj = await page.$('.champion-detail-info')// 费用const grade = await obj.$eval('.component-champion .champion-price', node => node.innerText)// 头像const head_image = await obj.$eval('.component-champion .champion-pic img', node => node.src)// 背景头像let bg_image = await obj.$eval('.detail-info-1 .champion-big-pic', node => node.style.backgroundImage)bg_image = bg_image.replace('url("', 'https:')bg_image = bg_image.replace('")', '')// 名称const name = await obj.$eval('.champion-name', node => node.innerText)const nameArr = name.split(' ')// 技能图const skill_image = await obj.$eval('.champion-skill .skill-pic img', node => node.src)// 技能名称const skill_name = await obj.$eval('.champion-skill .skill-txt .skill-name', node => node.innerText)// 技能被动或主动const skill_trigger = await obj.$eval('.champion-skill .skill-txt .skill-type', node => node.innerText)// 技能描述const skill_details = await obj.$eval('.champion-skill .skill-desc', node => node.innerText)// 羁绊图片const jibanImg = await obj.$$eval('.detail-info-3 img', node => node.map(n => n.src))// 属性let jibenshuxing = await obj.$eval('.detail-info-2 .detail-info-desc', node => node.innerText)jibenshuxing = jibenshuxing.split('\n').map(i => i.replace(':', '/')).map(i => i.split('/'))let info = {grade,head_image,name,nameArr,skill_image,skill_name,skill_trigger,skill_details,jibanImg,jibenshuxing}// 跑数据库逻辑if (false) {console.log('【英雄】已存在执行修改', info)} else {console.log('【英雄】不存在执行新增', info)}// 点击右上角返回,英雄列表const search_btn = await page.$(`.page-btn-title:nth-child(2)`)await search_btn.click()}
}
请开始你的表演…