const puppeteer = require('puppeteer');
const { KnownDevices } = require('puppeteer');
const fs = require('fs');
const path = require('path');
const { PDFDocument } = require('pdf-lib');
const { readFile } = require('fs/promises');
function delay(time) {
return new Promise(function(resolve) {
setTimeout(resolve, time)
});
}
async function takeScreenshots(url) {
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
// Устанавливаем мобильный User-Agent и разрешение экрана для iPhone 15 Pro
const iPhone = KnownDevices['iPhone 15 Pro'];
await page.emulate(iPhone);
await page.goto(url);
await delay(5000); // Ждем 5 секунд, чтобы страница полностью загрузилась
// Получаем общее количество страниц
const numPages = await page.evaluate(() => window.originTotalPageCount);
console.log(`Total pages: ${numPages}`);
// Создаем папку для сохранения скриншотов, если ее нет
const imagesDir = 'images';
if (!fs.existsSync(imagesDir)) {
fs.mkdirSync(imagesDir);
}
for (let pageNumber = 1; pageNumber <= numPages; pageNumber++) {
// Делаем скриншот всей страницы
const screenshotPath = path.join(imagesDir, `page_${pageNumber}.png`);
await page.screenshot({ path: screenshotPath, fullPage: true });
console.log(`Screenshot saved to ${screenshotPath}`);
// Свайп влево для перехода на следующую страницу
if (pageNumber < numPages) {
const { width, height } = await page.evaluate(() => ({
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight
}));
const startX = width - 10;
const endX = 10;
const swipeY = height / 2;
// Имитация свайпа
await page.touchscreen.touchStart(startX, swipeY);
await delay(100);
await page.touchscreen.touchMove(endX, swipeY);
await delay(100);
await page.touchscreen.touchEnd();
await delay(1000); // Ждем 1 секунду, чтобы страница переключилась
}
}
await browser.close();
// Создаем папку для сохранения PDF, если ее нет
const outputDir = 'output';
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir);
}
// Создаем PDF из изображений
const pdfDoc = await PDFDocument.create();
const imageFiles = fs.readdirSync(imagesDir).sort((a, b) => {
const numA = parseInt(a.match(/\d+/)[0]);
const numB = parseInt(b.match(/\d+/)[0]);
return numA - numB;
});
for (const imageFile of imageFiles) {
const imagePath = path.join(imagesDir, imageFile);
const imageBytes = await readFile(imagePath);
const image = await pdfDoc.embedPng(imageBytes);
const page = pdfDoc.addPage([image.width, image.height]);
page.drawImage(image, {
x: 0,
y: 0,
width: image.width,
height: image.height,
});
}
const pdfBytes = await pdfDoc.save();
const pdfPath = path.join(outputDir, `book.pdf`);
fs.writeFileSync(pdfPath, pdfBytes);
console.log(`PDF saved to ${pdfPath}`);
}
const url = process.argv[2] || 'https://www.yunzhan365.com/book/12345.html'; // Replace with your URL
takeScreenshots(url);
node screenshot.js https://book.yunzhan365.com/klqn/xobm/mobile/index.html
class Typewriter {
constructor(element, texts, speed) {
this.element = element;
this.texts = texts;
this.speed = speed;
this.index = 0;
this.textIndex = 0;
}
start() {
this.type();
}
type() {
if (this.index < this.texts[this.textIndex].length) {
this.element.innerHTML += this.texts[this.textIndex].charAt(this.index);
this.index++;
setTimeout(() => this.type(), this.speed);
} else {
this.index = 0;
this.textIndex = (this.textIndex + 1) % this.texts.length;
this.element.innerHTML = "";
setTimeout(() => this.type(), this.speed);
}
}
}
const qualityElement = document.getElementById("quality");
const TEXTS = ["Креативность ", "Эффективность ", "Индивидуальность "];
const SPEED = 85;
const typewriter = new Typewriter(qualityElement, TEXTS, SPEED);
typewriter.start();
<div id="text">тут</div>
<button id="1" class="button">1</button>
<button id="2" class="button">2</button>
<button id="3" class="button">3</button>
<button id="4" class="button">4</button>
const data = {
1:'текст 1',
2:'текст 2',
3:'текст 3',
4:'текст 4'
}
const buttons = [...document.querySelectorAll('.button')]
buttons.map(item => {
item .addEventListener("click", function() {
document.getElementById("text").innerHTML =
data[this.id]
});
})
const $ = (selector) => document.querySelector(selector);
const out99 = $('.out-31');
const inputW1 = $('.i-31');
const buttonTask = $('.b-31');
const price = {
500: 'Налог составляет 2525 тенге.',
600: 'Налог составляет 8275 тенге.',
1200:'Налог составляет 5050 тенге.',
1900:'Налог составляет 9675 тенге.',
2000: 'Налог составляет 11075 тенге.'
}
const getPrice = () => {
out99.innerHTML = price[inputW1.value] || 'Введена не верная ставка'
};
buttonTask.addEventListener('click', getPrice);
let template = `
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
</head>
<body>
<h1>Результат: {{code}}</h1>
<div class="table-responsive">
<table class="table table-striped">
<thead class="thead-dark">
<tr>
{{#each names}}
<th scope="col">{{this}}</th>
{{/each}}
</tr>
</thead>
<tbody>
{{#each response}}
<tr>
<td>{{userId}}</td>
<td>{{id}}</td>
<td>{{title}}</td>
<td>{{body}}</td>
</tr>
{{/each}}
</tbody>
</table>
</div>
</body>
</html>`;
var data = pm.response.json();
var name = data.map(x=> Object.keys(x));
pm.visualizer.set(template,{
names: [...new Set(name)][0],
code: pm.response.code,
response: data
});
function MyDate(date){
this.date = new Date(date);
const options = {
year: 'numeric',
month: 'numeric',
day: '2-digit'
}
const locale = 'en'
const f = new Intl.DateTimeFormat(locale, options);
const [{ value: mo },,{ value: da },,{ value: ye }] = f.formatToParts(this.date);
this.formatData = () => console.log(`${ye},${mo},${da}`);
}
let d = new MyDate('Tue Apr 27 2021 00:33:00 GMT+0500 (Екатеринбург, стандартное время)');
d.formatData();
const datas = [
{
description: "new",
img: "https://www.svgimages.com/svg-image/s8/air-jordan-logo-256x256.png",
name: "Nike1",
price: 100
}, {
description: "classic",
img: "https://www.freepnglogos.com/uploads/puma-logo-png-1.png",
name: "Adidas1",
price: 120
},
{
description: "new",
img: "https://www.svgimages.com/svg-image/s8/air-jordan-logo-256x256.png",
name: "Nike2",
price: 200
}, {
description: "classic",
img: "https://www.freepnglogos.com/uploads/puma-logo-png-1.png",
name: "Adidas2",
price: 320
}
]
class Products {
constructor(name, price, description, img){
this.name = name;
this.price = price;
this.description = description;
this.img = img;
}
}
class Manager {
constructor(selector = '#tables', data = []) {
this.root = document.querySelector(selector) || document.body;
this.products = data.length === 0 ? this._demoProducts() : data;
}
_demoProducts() {
let nike = new Products("Nike", 100, "new-shoes","https://www.svgimages.com/svg-image/s8/air-jordan-logo-256x256.png");
let adidas = new Products("Adidas", 120, "classic-shoes","https://www.freepnglogos.com/uploads/puma-logo-png-1.png");
return [nike, adidas];
}
getHTMLTemplate() {
return this.products.map(function(product, i) {
return `<div class="info-goods" data-id='${i}'>
<div class="img"><img src=${product.img} width="80" height="80" alt='${product.name}'></div>
<div class="name">${product.name}</div>
<div class="price">${product.price}</div>
<div class="description">${product.description}</div>
</div>`
});
}
init(){
this.root.insertAdjacentHTML('beforeend', this.getHTMLTemplate().join('<hr>'));
}
}
const manager = new Manager();
manager.init();
const fs = require('fs');
const path = require('path');
const HTMLParser = require('node-html-parser');
const folderPath = 'html'
fs.readdirSync(folderPath).map(fileName => {
fs.readFile(path.join(folderPath, fileName), 'utf8', function(err, html){
const root = HTMLParser.parse(html);
console.log(root.querySelector('h2').rawText);
});
});