Как мне посещать один URL-адрес за другим с помощью puppeteer

#javascript #puppeteer

#javascript #puppeteer

Вопрос:

Я начал изучать puppeteer и пытаюсь выполнить некоторый код, чтобы улучшить свое обучение. Я хотел бы выполнить простую задачу, посещая один URL-адрес за другим, однако я не могу его выполнить. прошу вас, пожалуйста, просмотрите мой код и предложите любые изменения.

  const puppeteer = require('puppeteer');
    (async () => {
        const browser = await puppeteer.launch({ headless: false });
        const page = await browser.newPage();
        const urls = ['https://www.google.com/', 'https://www.yahoo.com/']
        for (let i = 0; i < urls.length; i  ) {
            const url = urls[i];
            await page.goto(`${url}`);
            await page.waitForNavigation({ waitUntil: 'networkidle2' });
        }
        await browser.close();
    })();
  

приведенный выше код посещает только google.com а затем выдает ошибку ниже .

 node .testAutomation.js
(node:8564) UnhandledPromiseRejectionWarning: TimeoutError: Navigation timeout of 30000 ms exceeded
    at D:Documentstudyjswebscrappingnode_modulespuppeteerlibcjspuppeteercommonLifecycleWatcher.js:106:111
    at async FrameManager.waitForFrameNavigation (D:Documentstudyjswebscrappingnode_modulespuppeteerlibcjspuppeteercommonFrameManager.js:125:23)
    at async Frame.waitForNavigation (D:Documentstudyjswebscrappingnode_modulespuppeteerlibcjspuppeteercommonFrameManager.js:429:16)
    at async Page.waitForNavigation (D:Documentstudyjswebscrappingnode_modulespuppeteerlibcjspuppeteercommonPage.js:836:16)
    at async D:DocumentstudyjswebscrappingtestAutomation.js:16:9
(node:8564) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:8564) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
  

Ответ №1:

После await page.goto(); этого вам не нужно await page.waitForNavigation(); . Первая команда уже включает ожидание навигации, поэтому последняя просто зависает после нее.

await page.waitForNavigation(); требуется после некоторого взаимодействия с пользователем (например, щелчка) или команды скрипта, которые изменяют URL.

Итак, просто удалите await page.waitForNavigation({ waitUntil: 'networkidle2' }); .