使用 waitForSelector() 时出现 Puppeteer 超时错误

Puppeteer timeout error while using waitForSelector()

(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 行上遇到错误。我正在尝试找到解决此问题的方法。

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 个屏幕截图

第二个屏幕截图将始终为黑色,您可能需要超时,因为它会在页面加载后立即截取屏幕截图。