首页 > 解决方案 > 如何使用 click 和 waitForNavigation?

问题描述

#!/usr/bin/env node
// vim: set noexpandtab tabstop=2:

const puppeteer = require('puppeteer');
const fs = require('fs').promises;

const cookies_json_file = process.argv[2];
const url = process.argv[3];
const timeout = parseInt(process.argv[4], 10);

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    const cookiesString = await fs.readFile(cookies_json_file);
    const cookies = JSON.parse(cookiesString);
    await page.setCookie.apply(page, cookies);
    try {
        await page.goto(url, { waitUntil: 'networkidle2', timeout: timeout });
        const content = await page.content();
        page.on('response', async response => {
            if(response.url().startsWith('https://www.genecards.org/gene/api/data/Enhancers?geneSymbol=')) {
                response.buffer().then(function(data) {
                    fs.writeFile('/dev/stdout', data);
                });
            }
        });

        const linkHandlers = await page.$x('//div[@data-ga-category = "GeneHancer"]//a[@data-role = "show-all"]');
        if (linkHandlers.length > 0) {
            await Promise.all([
                linkHandlers[0].click()
                , page.waitForNavigation({waitUntil: 'networkidle2', timeout: timeout})
            ]);
        } else {
            throw new Error("Link not found");
        }
    } catch (e) {
        console.error(e);
        process.exit(1);
    } finally {
        await browser.close();
    }
})();

我有上面的main.js

$ ./main.js cookies.json 'https://www.genecards.org/cgi-bin/carddisp.pl?gene=BSCL2' 30000

当我使用上面的命令运行时,我得到了这个错误。有人知道如何修复错误吗?谢谢。

TimeoutError: Navigation Timeout Exceeded: 30000ms exceeded
    at /usr/local/lib/node_modules/puppeteer/lib/LifecycleWatcher.js:142:21
  -- ASYNC --
    at Frame.<anonymous> (/usr/local/lib/node_modules/puppeteer/lib/helper.js:110:27)
    at Page.waitForNavigation (/usr/local/lib/node_modules/puppeteer/lib/Page.js:649:49)
    at Page.<anonymous> (/usr/local/lib/node_modules/puppeteer/lib/helper.js:111:23)
    at main.js:33:12
    at processTicksAndRejections (internal/process/task_queues.js:89:5) {
  name: 'TimeoutError'
}
```

标签: node.jspuppeteer

解决方案


您需要通过将 timeout 参数设置为 0 来禁用超时。默认值为 30 秒(您也将其作为示例中的命令行参数传递),因此它的行为符合预期并引发异常,因为超时超过了默认值或用户提供的值 30000 毫秒。

 page.waitForNavigation({waitUntil: 'networkidle2', timeout: 0})

您还可以从命令行将参数作为参数传递,这样最好不要对值进行硬编码:

$ ./main.js cookies.json 'https://www.genecards.org/cgi-bin/carddisp.pl?gene=BSCL2' 0

推荐阅读