12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- /**
- * 在无头浏览器中将一个网页截图保存为图片
- */
- 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/Documents/D Disk/git/mingxue/testevaluation/code/test/test-ui/public/collectImgNew/index.html');
- async function capchaAndUpload(page) {
- await page.waitForSelector('#title');
- let store = await page.evaluate(() => JSON.stringify(localStorage));
- store = JSON.parse(store)
- console.log('------------------' + store.questionId + '请求成功!-------------------')
- 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).then(res => {
- let base64 = Buffer.from(res).toString('base64');//转为base64编码字符串
- const formData = new FormData()
- formData.append('questionId', store.questionId)
- formData.append('imageBase64', base64)
- upload(page, formData, store.questionId);
- });
- }
- function upload(page, formData, questionId) {
- const reqUrl = 'https://front.mingxuejinbang.com/prod-api/front/questionCollection/uploadQuestionImage';
- axios.post(reqUrl, formData)
- .then((res) => {
- if (res.data.code === 200) {
- console.log(questionId + '上传成功!')
- // 获取下一个问题
- page.click('#next');
- setTimeout(() => {
- capchaAndUpload(page);
- }, 100)
- } else {
- console.log('出错了')
- }
- });
- }
|