index_question.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**
  2. * 在无头浏览器中将一个网页截图保存为图片
  3. */
  4. const fs = require('fs')
  5. const path = require('path')
  6. const axios = require('axios')
  7. const FormData = require('form-data')
  8. const puppeteer = require('puppeteer');
  9. const saveScreenshot = async (url) => {
  10. // 启动浏览器
  11. const browser = await puppeteer.launch({
  12. headless: true
  13. });
  14. // 打开页面
  15. const page = await browser.newPage();
  16. // 设置浏览器视窗
  17. page.setViewport({
  18. width: 1920,
  19. height: 1080,
  20. })
  21. // 地址栏输入网页地址
  22. await page.goto(url, {
  23. // 等界面加载完
  24. waitUntil: 'networkidle0'
  25. });
  26. capchaAndUpload(page);
  27. // 关闭浏览器
  28. // await browser.close();
  29. };
  30. saveScreenshot('file:////Users/admin/Documents/D Disk/git/mingxue/testevaluation/code/test/test-ui/public/collectImgNew/index.html');
  31. async function capchaAndUpload(page) {
  32. await page.waitForSelector('#title');
  33. let store = await page.evaluate(() => JSON.stringify(localStorage));
  34. store = JSON.parse(store)
  35. console.log('------------------' + store.questionId + '请求成功!-------------------')
  36. let clip = await page.evaluate((scope) => {
  37. let {
  38. x,
  39. y,
  40. width,
  41. height
  42. } = document.getElementById('title').getBoundingClientRect();
  43. window.scope = scope;
  44. return {
  45. x,
  46. y,
  47. width,
  48. height
  49. };
  50. });
  51. const filename = `./preview/${store.questionId}.png`;
  52. const options = {
  53. path: filename,
  54. fullPage: false,
  55. clip
  56. }
  57. await page.screenshot(options).then(res => {
  58. let base64 = Buffer.from(res).toString('base64');//转为base64编码字符串
  59. const formData = new FormData()
  60. formData.append('questionId', store.questionId)
  61. formData.append('imageBase64', base64)
  62. upload(page, formData, store.questionId);
  63. });
  64. }
  65. function upload(page, formData, questionId) {
  66. const reqUrl = 'https://front.mingxuejinbang.com/prod-api/front/questionCollection/uploadQuestionImage';
  67. axios.post(reqUrl, formData)
  68. .then((res) => {
  69. if (res.data.code === 200) {
  70. console.log(questionId + '上传成功!')
  71. // 获取下一个问题
  72. page.click('#next');
  73. setTimeout(() => {
  74. capchaAndUpload(page);
  75. }, 100)
  76. } else {
  77. console.log('出错了')
  78. }
  79. });
  80. }