【发布时间】:2019-08-07 17:05:59
【问题描述】:
我正在尝试使用 Puppeteer 从页面中的嵌入视频中获取 src 属性。
我已经尝试使用 page.$eval()、page.evaluate() 和 page.evaluateHandle() 使用 document.querySelector()。
const url = await page.$eval('.video > source:nth-child(3)', el => el.src);
HTMl结构如下:
<video class="video media" id="" alt="" height="1080" width="1920" autoplay="" playsinline="" preload="auto" poster="" tabindex="-1">
<source src="" type="video/mp4">
<source src="" type="video/webm">
<source src="" type="video/mp4">
<source src="" type="video/mp4">
<meta itemprop="contentUrl" content="">
</video>
当我尝试使用page.$eval 查找元素时,我收到错误“错误:找不到匹配选择器的元素“.video > source:nth-child(3)””
我可以在控制台中使用document.querySelector('.video > source:nth-child(3)');,它会返回 html 元素:
<source src="https://giant.gfycat.com/VastGrayGazelle.mp4" type="video/mp4">
我还可以通过选择器搜索 HTML 并突出显示元素。
【问题讨论】:
-
您确定,该按钮在页面加载时已经可用?如果在调用函数前加上
await page.waitForSelector('.video > source:nth-child(3)');,是否有效? -
试试这个 -
const videoUrl = await page.evaluate(() => document.querySelector("#<your_id> source").getAttribute("src"))); console.log(videoUrl);
标签: javascript node.js web-scraping puppeteer