【问题标题】:Cheerio selector after page loaded页面加载后的 Cheerio 选择器
【发布时间】:2021-09-04 23:42:22
【问题描述】:

我想抓取这个网站中 iframe 的 url 值:https://lk21online.digital/nonton-profile-2021-subtitle-indonesia/
当我从视图页面源搜索 iframe 时,它​​没有找到,我认为 iframe 是在 javascript 加载页面后加载的
还是我的选择器错了?
请有人帮我检查我的选择器或我需要为我的代码做什么
对不起我的英语不好......

这是我的代码:

async function getDetail(res, url) {
    try {
        const html = await scraping(res, url)
        const $ = cheerio.load(html)
        const article = $('#site-container #content .gmr-maincontent #primary #main .gmr-box-content #muvipro_player_content_id #player1-tab-content')
        let result = []

        setTimeout(() => {
            article.each(function () {
                const title = $(this).find('.item-article h2').text()
                const watch = $(this).find('iframe').attr('src')

                result.push({
                    title,
                    watch,
                })

            })
            res.json({ result })
        }, 5000)


    }
    catch (err) {
        console.log(err)
    }
}

this is video iframe

【问题讨论】:

    标签: javascript html node.js web-scraping cheerio


    【解决方案1】:

    您不能为此使用cheerio。 Cheerio 不是动态的,它只是加载从请求返回的任何 html。

    看看你的网页,大部分内容都是异步加载的,所以初始的 html 会很空。

    此外,视频源在进入浏览器窗口时会延迟加载。因此,您必须使用实际的无头浏览器来完成任务。这是一个例子:

    // iframeUrl.js
    const puppeteer = require("puppeteer");
    
    (async () => {
      const browser = await puppeteer.launch();
      const page = await browser.newPage();
      // Goto page
      await page.goto("https://lk21online.digital/nonton-profile-2021-subtitle-indonesia/");
      // Scroll down
      page.evaluate((_) => window.scrollBy(0, 1000));
      // Wait a bit
      await new Promise((resolve) => setTimeout(resolve, 5000));
      // Get the src of the iframe
      const iframeUrl = await page.evaluate(`$("#player1-tab-content iframe").attr("src")`);
      console.log(iframeUrl);
      await browser.close();
      process.exit(0);
    })();
    

    【讨论】:

    • 它完全符合我的要求,感谢您的建议!
    猜你喜欢
    • 2011-05-12
    • 2021-09-25
    • 2023-03-06
    • 2015-12-18
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-21
    相关资源
    最近更新 更多