【问题标题】:page.$eval() not finding selector, selector works in consolepage.$eval() 找不到选择器,选择器在控制台中工作
【发布时间】: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 &gt; source:nth-child(3)');,它会返回 html 元素:

<source src=​"https:​/​/​giant.gfycat.com/​VastGrayGazelle.mp4" type=​"video/​mp4">​

我还可以通过选择器搜索 HTML 并突出显示元素。

【问题讨论】:

  • 您确定,该按钮在页面加载时已经可用?如果在调用函数前加上await page.waitForSelector('.video &gt; source:nth-child(3)');,是否有效?
  • 试试这个 - const videoUrl = await page.evaluate(() =&gt; document.querySelector("#&lt;your_id&gt; source").getAttribute("src"))); console.log(videoUrl);

标签: javascript node.js web-scraping puppeteer


【解决方案1】:

这应该可以工作

    const node = await page.$('.video > source:nth-child(3)');
    const url = await page.evaluate(body => body.getAttribute('src'), node);
    console.log(url);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-29
    • 2022-06-16
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    相关资源
    最近更新 更多