Я заявляю, что не являюсь опытным программистом :), около месяца я пытался создать скрипт, чтобы делать скриншоты многих URL-адресов за раз и сохранять их локально на моем компьютере.
В скрипте я собираюсь сделать следующее:
1 - я открываю URL из списка url-list. js файл
2 - Я жду загрузки страницы.
3 - Я проверяю, существует ли на моей странице кнопка согласия на конфиденциальность. Если он существует, нажмите на него и дождитесь загрузки рекламных форматов.
4 - Я делаю полную прокрутку страницы, чтобы загрузить все изображения.
5 - Сохраняю снимок экрана на my cpmputer.
6 - Зарегистрируйте через внешний сайт, сколько раз использовался скрипт.
То, что со мной время от времени происходит, и я не могу понять, является следующее:
- Иногда я могу найти кнопку, чтобы принять печенье на странице, даже если она существует в массиве Cook ie.
- Иногда время бежит чтобы найти кнопку для принятия согласия на конфиденциальность, а затем сценарий останавливается.
- Иногда сценарий дает сбой, я не знаю почему ... может быть, он переполняет память?
Прошу вашей помощи, чтобы понять, ошибся ли я, написав этот скрипт, или есть возможность его улучшить в какой-то момент. :)
Скриншот ФАЙЛА. js:
const puppeteer = require('puppeteer');
const os = require('os');
const username = require('username');
//I identify the operating system and the architect of the CPU to run the Google Chrome Patch
var architetturaCPU = os.arch();
var sistemaOperativo = os.type();
console.log('System OS: '+sistemaOperativo+' '+architetturaCPU);
//console.log(os.platform());
// Device width and height - Desktop / Tablet / Mobile
const device_width = 1920;
const device_height = 1080;
//Patch di Chrome
var systemPath = '';
if (sistemaOperativo == 'Darwin'){
console.log('Chrome for MacOS');
var systemPath = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
} else
if(sistemaOperativo == 'Windows_NT' && architetturaCPU == 'x64'){
console.log('Chrome for Windows 64bit');
var systemPath = 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe';
}else
if(sistemaOperativo == 'Windows_NT' && architetturaCPU == 'x32'){
console.log('Chrome for Windows 32bit');
var systemPath = 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe';
}else
if(sistemaOperativo == 'Windows_NT' && architetturaCPU == 'ia32'){
console.log('Chrome for Windows 32bit');
var systemPath = 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe';
}
//I build an Array and insert all the buttons for the consent of the Cookies for the Network sites
const cookie1 = 'button.amecp_button-accetto.iubenda-cs-close-btn';
const cookie2 = 'button.iubenda-cs-accept-btn.iubenda-cs-btn-primary';
var BtnCookie = [
cookie1,
cookie2
];
(async function () {
//I read the url file
var fs = require('fs');
var urlArray = fs.readFileSync('url-list.js').toString().split("\n").filter(a => a);
//Launch Puppeteer
const browser = await puppeteer.launch({
headless: true,
executablePath: systemPath,
args: ['--disable-dev-shm-usage','--no-sandbox']});
//Loop through all the url-list.js URL
var contaUrl = 0;
for(var i = 0; i < urlArray.length; i++){
//Check if empty spaces are present in the url file list
if (urlArray[i].indexOf("http") != '-1'){
//I open the boswser, delete the cache and set the page size
const page = await browser.newPage();
const client = await page.target().createCDPSession();
await client.send('Network.clearBrowserCookies');
await client.send('Network.clearBrowserCache');
await page.setCacheEnabled(false);
await page.setViewport({width: device_width, height: device_height});
await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36');
//Tell me which URL you are working on
console.log(' ');
console.log('\x1b[33m%s','Open URL > '+urlArray[i],'\x1b[0m');
console.log(' ');
await page.goto(urlArray[i],{waitUntil:'networkidle2'});
await page.waitFor(20000);
//Find the class / id of the button on the page to accept cookies
var contaNumeroValoriBtnCookie = BtnCookie.length;
for(var n = 0; n <= BtnCookie.length; n++){
if (await page.$(BtnCookie[n]) !== null ) {
console.log(BtnCookie[n]);
const navigationPromise = page.waitForSelector(BtnCookie[n]);
await page.click(BtnCookie[n]);
await navigationPromise;
console.log('\x1b[32m%s', 'Bypass Cookie... OK!','\x1b[0m');
break;
}else if (n == contaNumeroValoriBtnCookie) {
console.log('\x1b[31m%s', 'Cookie not found!','\x1b[0m');
}else {
//console.log('I'm looking for the cookie...');
}
} //end - Find the class / id of the button on the page to accept cookies
//Scroll the entire page to load the content
await autoScroll(page);
async function autoScroll(page){
await page.evaluate(async () => {
await new Promise((resolve, reject) => {
var totalHeight = 0;
var distance = 100;
var timer = setInterval(() => {
var scrollHeight = document.body.scrollHeight;
window.scrollBy(0, distance);
totalHeight += distance;
if(totalHeight >= scrollHeight){
clearInterval(timer);
resolve();
}
}, 300);
});
});
}
//Go back to the top of the page
await page.evaluate(_ => {window.scrollTo(0, 0);});
await page.waitFor(10000);
//I clean up the URL before saving the file
var str = urlArray[i];
str = str.replace(/[^\w]+/ig,'-');
var convertiUrl = str;
//SAVE screenshot
await page.screenshot({path: './screenshot/'+convertiUrl+i+'.jpg', fullPage: true});
await page.waitFor(5000);
//Register through an external site, on which url the script is most used
if (contaUrl < urlArray.length){
const urlCeck = new URL(urlArray[i]);
var impressionPage = "https://lab.servername.it/track/index1.php?id=6dfc76542a4817a-368/-/"+urlCeck.hostname+"/-/impressionPage";
await page.goto(impressionPage ,{waitUntil:'load'});
}
contaUrl++;
//I register via an external site, the username that used the script and count how many times the script was used in total
if (contaUrl >= urlArray.length){
var userNameScript = await username();
var impressionNomeUtente = "https://lab.servername.it/track/index1.php?id=5a98b9a86118ae6-288/-/"+userNameScript+"/-/userNameScript";
var impressionScript = "https://lab.servername.it/track/index1.php?id=5a98b9a86118ae6-288/-/script_impression/-/script_impression";
await page.goto(impressionNomeUtente, {waitUntil:'load'});
await page.goto(impressionScript, {waitUntil:'load'});
}
await page.close();
}//end if (urlArray[i].indexOf("http") != '-1'){
}//fine loop
browser.close();
console.log(' ');
console.log('\x1b[32m%s', contaUrl+' all screenshot saved :)','\x1b[0m');
console.log(' ');
})(); //end script