【问题标题】:Why is [el] showing undefined?为什么 [el] 显示未定义?
【发布时间】:2021-09-03 10:49:03
【问题描述】:

我正在尝试使用 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:无法读取未定义的属性“getProperty”

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

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

【问题讨论】:

  • el 是数组,而数组没有任何名为getProperty的属性
  • 它有。它适用于其他网站。
  • el 不是数组,不是吗?它获取$x 返回的数组的第一个元素。但是,如果这些元素不在页面上并且$x 的数组为空,则el 将是未定义的
  • @MayukhDasgupta 它可能会出现最终,但可能只有在页面完成额外渲染之后
  • 我不知道page.goto 什么时候完成,确切地说。我的猜测是在 DOM ready 事件发生的时候。您可能需要放入某种循环或计时器来反复检查直到元素存在。

标签: javascript express web-scraping undefined puppeteer


【解决方案1】:

尝试替换

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();

【讨论】:

  • 只使用 el 以后不会给我 getProperty 方法,并且描述的东西工作正常。
  • @MayukhDasgupta 它将:page.$x() 返回一个元素句柄数组,而 page.waitForXPath() 返回一个元素句柄本身。它等待元素出现。
  • 我查过了。用 el 替换 [el] 不会给我 getProperty 方法。 @vsemozhebuty
  • @MayukhDasgupta 您是否也将page.$x() 替换为page.waitForXPath()
  • 是的,我以前也这样做过
猜你喜欢
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
  • 2018-02-27
  • 1970-01-01
  • 1970-01-01
  • 2012-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多