(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);
})();
這是我從 tabnine 獲取的簡單代碼。但是我在 waitForSelector 行上遇到錯誤。我正在嘗試找到解決此問題的方法。
uj5u.com熱心網友回復:
waitForSelector正在超時,因為您的代碼執行方式,它從不等待搜索輸入加載。
我用設定嘗試了你的代碼headless: false并且能夠產生問題。
查看我在下面所做的更改,它現在似乎有效
(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();
})();
有了這個我得到2個截圖


Second screenshot will always be black, you probably need to give a timeout since it's taking screenshot as soon as page loads.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/455145.html
