英文:
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]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论