(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto("https://youtube.com");
await page.type("#search", "Fleetwood Mac Dreams");
await page.click("button#search-icon-legacy");
await page.waitForSelector("ytd-thumbnail.ytd-video-renderer");
await page.screenshot({ path: "youtube_fm_dreams_list.png" });
const videos = await page.$$("ytd-thumbnail.ytd-video-renderer");
await videos[2].click();
await page.waitForSelector(".html5-video-container");
await page.screenshot({ path: screenshot });
await browser.close();
console.log("See screenshot: " screenshot);
})();
It's simple code that I picked up from tabnine. But I'm getting error on waitForSelector line. I'm trying to find a way to fix this.
CodePudding user response:
waitForSelector
is timing out because the way your code is executing, it never waits for search input to load.
I tried your code with headless: false
setting and was able to produce the issue.
Check out the changes I made below, it now seems to work
(async () => {
const browser = await puppeteer.launch({ headless: false }); // <-- You can remove headless: flase if u like good for debugging
const page = await browser.newPage();
await page.setViewport({ width: 1280, height: 800 }); // <-- Not needed if not using headless: flase
await page.goto('https://youtube.com', {
waitUntil: 'networkidle2', // <-- good practice to wait for page to fully load
});
await page.waitForSelector('input[id="search"]', { timeout: 5000 });
const input = await page.$('input[id="search"]');
await input.type('Fleetwood Mac Dreams');
await page.click('button#search-icon-legacy');
await page.waitForSelector('ytd-thumbnail.ytd-video-renderer');
await page.screenshot({ path: 'youtube_fm_dreams_list.png' });
const videos = await page.$$('ytd-thumbnail.ytd-video-renderer');
await videos[2].click();
await page.waitForSelector('.html5-video-container');
await page.screenshot({ path: 'youtube_fm_dreams_list_1.png' }); // <-- You can change the path accordingly
await browser.close();
})();
With this I get 2 screenshots
Second screenshot will always be black, you probably need to give a timeout since it's taking screenshot as soon as page loads.