我创建了一个可在offline
中运行的Puppeteer脚本,我得到了以下代码以截取屏幕截图。在命令提示符下运行offline-login-check.js
脚本时,是否可以有人建议添加屏幕快照的位置?
const puppeteer = require("puppeteer");
(async() => {
const browser = await puppeteer.launch({
headless: true,
chromeWebSecurity: false,
args: ['--no-sandbox']
});
try {
// Create a new page
const page = await browser.newPage()
// Connect to Chrome DevTools
const client = await page.target().createCDPSession()
// Navigate and take a screenshot
await page.waitFor(3000);
await page.goto('https://sometestsite.net/home',{waitUntil: 'networkidle0'})
//await page.goto(url, {waitUntil: 'networkidle0'});
await page.evaluate('navigator.serviceWorker.ready');
console.log('Going offline');
await page.setOfflineMode(true);
// Does === true for the main page but the fallback content isn't being served.
page.on('response', r => console.log(r.fromServiceWorker()));
await page.reload({waitUntil: 'networkidle0'});
await page.waitFor(5000);
await page.screenshot({path: 'screenshot.png',fullPage: true})
await page.waitForSelector('mat-card[id="route-tile-card]');
await page.click('mat-card[id="route-tile-card]');
await page.waitFor(3000);
} catch(e) {
// handle initialization error
console.log ("Timeout or other error: ", e)
}
await browser.close();
})();
答案 0 :(得分:1)
const puppeteer = require('puppeteer');
(async() => {
const browser = await puppeteer.launch({
headless: false,
chromeWebSecurity: false,
args: ['--no-sandbox']
});
try {
// Create a new page
const page = await browser.newPage();
// Connect to Chrome DevTools
const client = await page.target().createCDPSession();
// Navigate and take a screenshot
await page.goto('https://example.com', {waitUntil: 'networkidle0'});
// await page.evaluate('navigator.serviceWorker.ready');
console.log('Going offline');
await page.setOfflineMode(true);
// Does === true for the main page but the fallback content isn't being served.
page.on('response', r => console.log(r.fromServiceWorker()));
await page.reload({waitUntil: 'networkidle0'});
await page.screenshot({path: 'screenshot2.png',fullPage: true})
// await page.waitForSelector('mat-card[id="route-tile-card]');
// await page.click('mat-card[id="route-tile-card]');
} catch(e) {
// handle initialization error
console.log ("Timeout or other error: ", e)
}
await browser.close();
})();
然后在命令行中运行ls | GREP .png
,您应该在此处看到屏幕截图。请注意,我删除了await page.evaluate('navigator.serviceWorker.ready');
,它可能已指定给您的网站
答案 1 :(得分:0)
您的脚本很完美。没问题!
screenshot.png应该位于您运行node offline-login-check.js
命令的目录上。
如果它不存在,则可能是在运行page.screenshot
命令之前您遇到了一些错误/超时。由于脚本正常,这可能是由网络问题或页面问题引起的。例如,如果您的页面具有永无休止的连接(例如WebSocket),请将“ networkidle0”更改为“ networkidle2”或“ load”,否则第一个page.goto
会卡住。
同样,您的脚本很完美。您不必更改它。