如何解决页面加载后的 Cheerio 选择器
我想抓取本网站中 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)
}
}
解决方法
您不能为此使用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);
})();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。