首页 > 解决方案 > 为什么 [el] 显示未定义?

问题描述

我正在尝试使用 puppeteer 进行抓取。

app.get("/info", async (req, res) => {

    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://www.youtube.com/watch?v=RQonuvvoXko&t=2s')

    // console.log(el)

    const [el] = await page.$x('//*[@id="description"]/yt-formatted-string')
    const text = await el.getProperty('textContent')
    const description = text.toString();

    // var descArr = description.split('/PC([^;]+)\n/')
    // const descText = /News([^;]+)\n/.exec(description)[1];
    browser.close()
    console.log(description);
    res.send(description)

    // console.log(text.toString())    
})

我收到以下错误:
TypeError: Cannot read property 'getProperty' of undefined

编辑:
我已经检查了我的页面和 DOM 是否已成功加载这些...

page.on('load', () => console.log('page loaded', page.url()))
page.on('domcontentloaded' , () => console.log('dom loaded'))

标签: javascriptexpressweb-scrapingundefinedpuppeteer

解决方案


尝试更换

const [el] = await page.$x('//*[@id="description"]/yt-formatted-string');

const el = await page.waitForXPath('//*[@id="description"]/yt-formatted-string');

此外,似乎

const description = text.toString();

应该:

const description = await text.jsonValue();

推荐阅读