Skip to content

Instantly share code, notes, and snippets.

@dzmitry-savitski
Last active January 30, 2025 20:28
Show Gist options
  • Save dzmitry-savitski/7699aff5e4d680be53e078d74a68d166 to your computer and use it in GitHub Desktop.
Save dzmitry-savitski/7699aff5e4d680be53e078d74a68d166 to your computer and use it in GitHub Desktop.
puppeteer examle
const browser = await puppeteer.launch({ headless: false });
const page = await browser.newPage();
let openedAt = null;
let redirectedAt = null;
let endedAt = null;
// Promise to track when a redirect happens
let redirectPromise = new Promise(resolve => {
page.on('response', response => {
const status = response.status();
const request = response.request();
if (status >= 300 && status < 400) {
const location = response.headers()['location'];
if (location) {
redirectedAt = new Date();
console.log(`Redirected at: ${redirectedAt.toISOString()} - ${request.url()}${location}`);
resolve(); // Resolves the promise when the first redirect occurs
}
}
});
});
const puppeteer = require("puppeteer");
const START_URL = "https://start.example.com"; // Replace with your start URL
const FINAL_URL = "https://end.example.com"; // Replace with your final URL
(async () => {
const attempts = 100; // Number of runs
let totalDuration = 0; // To calculate the average time
const results = []; // Store each attempt duration
// Launch Puppeteer with your installed Chrome
const browser = await puppeteer.launch({
headless: false, // Run in visible mode
executablePath: "/path/to/your/chrome", // Optional: Replace with your Chrome path if needed
defaultViewport: null, // Use full viewport of your screen
});
for (let i = 0; i < attempts; i++) {
const startTime = Date.now();
const page = await browser.newPage();
// Clear cookies and cache
const client = await page.target().createCDPSession();
await client.send("Network.clearBrowserCookies");
await client.send("Network.clearBrowserCache");
// Open the start URL and wait for the final URL
await page.goto(START_URL);
await page.waitForFunction(
(finalUrl) => window.location.href === finalUrl,
{},
FINAL_URL
);
const endTime = Date.now();
const duration = endTime - startTime;
totalDuration += duration;
results.push(duration);
console.log(`Attempt ${i + 1}: ${duration}ms`);
await page.close();
}
// Calculate the average time
const averageDuration = totalDuration / attempts;
console.log(`\nAverage Time: ${averageDuration}ms`);
// Log all attempts
console.log("\nIndividual Durations:");
results.forEach((duration, index) => {
console.log(`Run ${index + 1}: ${duration}ms`);
});
await browser.close();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment