javascript - 为什么 [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'))
解决方案
尝试更换
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();
推荐阅读
- amazon-web-services - Amazon Forecast boto3 服务员
- json - 来自 ESP8266 的 Firestore REST API POST 请求
- javascript - 带有 SAP UI5 的 Javascript 渲染管理器:创建自定义控件
- cucumber - 如何在黄瓜特征文件中传递复杂对象
- wordpress - Wordress 管理员网址将 www 更改为管理员
- html - 尝试使用 reactjs 和语义 ui 创建英雄图像
- java - 如何从 Java 中获取可用磁盘空间 *IN A FOLDER*
- linux - setrlimit 是否限制内核空间中的内存分配?
- c++ - C++ unordered_map 默认分配器
- reactjs - 我们可以使用 react native 为整个班级做隐藏和显示吗