如果puppeteer浏览器页面对象是通过browser.pages()[0]访问的,则使用后藤方法连续访问多个url失败。如果puppeteer浏览器页面对象是通过browser.newPage()访问的,它现在将创建第二个但活跃的页面,连续访问多个URL也可以。
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()
})()
字符串
以上工程
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:无法读取未定义的属性(阅读“goto”)
任何帮助将不胜感激!
1条答案
按热度按时间8yoxcaq71#
你得到这个错误,因为你试图从挂起状态的
Promise<Page[]>
获取索引为0的页面。要解决这个问题,您应该在Promise被解决时按索引获取页面,如
const page = (await browser.pages())[0];
个或者是
const [page] = await browser.pages();
个或者是
const page = await browser.pages().then(p => p[0]);
个