1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- /**
- * 在无头浏览器中将一个网页截图保存为图片
- */
- const fs = require('fs')
- const path = require('path')
- const axios = require('axios')
- const FormData = require('form-data')
- const puppeteer = require('puppeteer');
- const saveScreenshot = async (url) => {
- // 启动浏览器
- const browser = await puppeteer.launch({
- headless: true
- });
- // 打开页面
- const page = await browser.newPage();
- // 设置浏览器视窗
- page.setViewport({
- width: 1920,
- height: 1080,
- })
- // 地址栏输入网页地址
- await page.goto(url, {
- // 等界面加载完
- waitUntil: 'networkidle0'
- });
- capchaAndUpload(page);
- // 关闭浏览器
- // await browser.close();
- };
- saveScreenshot('file:///Users/admin/Desktop/headless/index.html');
- async function capchaAndUpload(page) {
- await page.waitForSelector('#title');
- let store = await page.evaluate(() => JSON.stringify(localStorage));
- store = JSON.parse(store)
- let clip = await page.evaluate((scope) => {
- let {
- x,
- y,
- width,
- height
- } = document.getElementById('title').getBoundingClientRect();
- window.scope = scope;
- return {
- x,
- y,
- width,
- height
- };
- });
- const filename = `./preview/${store.questionId}.png`;
- const options = {
- path: filename,
- fullPage: false,
- clip
- }
- await page.screenshot(options);
- let buffers = fs.readFileSync(path.resolve(filename));//同步读取文件
- let base64 = Buffer.from(buffers).toString('base64');//转为base64编码字符串
- const formData = new FormData()
- formData.append('questionId', store.questionId)
- formData.append('imageBase64', base64)
- const reqUrl = 'https://front.mingxuejinbang.com/prod-api/front/questionCollection/uploadQuestionImage';
- axios.post(reqUrl, formData)
- .then((res) => {
- if (res.data.code === 200) {
- console.log(store.questionId + '上传成功!')
- // 获取下一个问题
- page.click('#next');
- setTimeout(() => {
- capchaAndUpload(page);
- }, 1000)
- } else {
- console.log('出错了')
- }
- });
- }
|