Js puppteer页面转到不会转到下一个链接。

huangapple go评论78阅读模式
英文:

Js puppteer page goto does not go to next link

问题

如果使用 browser.pages()[0] 访问 Puppeteer 浏览器页面对象,连续访问多个 URL 时,使用 goto 方法会失败。

但是,如果使用 browser.newPage() 来创建第二个但是活跃的页面,那么连续访问多个 URL 就可以正常工作。

上述代码片段中的第一个示例是有效的,而第二个示例会导致 TypeError 错误。

希望这有所帮助!

英文:

If puppeteer browser page object is accessed with browser.pages()[0], going to multiple urls consecutively fail with goto method.
Where if puppeteer browser page object is accessed with browser.newPage() which will now create a second but active page, going to multiple urls consecutively works.

const puppeteer = require('puppeteer-core');

(async () => {
    const browser = await puppeteer.launch({
        executablePath: 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
        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 browser.close()
})()

Above works

const puppeteer = require('puppeteer-core');

(async () => {
    const browser = await puppeteer.launch({
        executablePath: 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
        headless: false 
    })

    const page = await browser.pages()[0]
    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 browser.close()
})()

TypeError: Cannot read properties of undefined (reading 'goto')

Any help will be appreciated!

答案1

得分: 0

你遇到这个错误是因为你试图从处于挂起状态的Promise<Page[]>中获取索引为0的页面。

要解决这个问题,你应该在Promise被解析后按索引获取页面,比如:

const page = (await browser.pages())[0];

或者

const [page] = await browser.pages();

或者

const page = await browser.pages().then(p => p[0]);
英文:

You got this error, because you are trying to get page with index 0 from Promise<Page[]> in pending status.

To solve this issue, you should get page by index, when Promise is resolved, like

const page = (await browser.pages())[0];

or

const [page] = await browser.pages();

or

const page = await browser.pages().then(p => p[0]);

huangapple
  • 本文由 发表于 2023年7月28日 04:08:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76783100.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定