使用node.js爬虫抓取m3u8格式视频并转换为mp4

该文章介绍了一种方法,通过前端技术如axios和cheerio抓取网页上的m3u8视频链接,然后利用ffmpeg进行转换,将m3u8格式的视频转为mp4。示例代码展示了整个流程,包括数据获取、视频流处理和错误处理。此外,还推荐了一个在线m3u8转换工具。
摘要由CSDN通过智能技术生成

某天看片时发现网址中的视频为m3u8格式,无法直接保存,那在前端如何使用爬虫去抓取网站中的视频并完成转换呢?

实现思路:
使用cheerio去获取网页中的html,拿到视频的src路径,使用ffmpeg模块去完成m3u8转mp4

完整代码:

const axios = require('axios');
const cheerio = require('cheerio');
const fs = require('fs');
const path = require('path');
const m3u8stream = require('m3u8stream');
const ffmpegStatic = require('ffmpeg-static');
const ffmpeg = require('fluent-ffmpeg');

ffmpeg.setFfmpegPath(ffmpegStatic.path);

async function run() {
  const { data } = await axios.get('https://www.example.com/', {
    headers: {
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
    }
  });

  const $ = cheerio.load(data);

  const m3u8Url = $('video').attr('src'); // 请根据实际情况修改选择器

  if (m3u8Url) {
    const output = path.join(__dirname, './output.mp4');
    const stream = m3u8stream(m3u8Url);

    ffmpeg(stream)
      .inputFormat('mpegts')
      .output(output)
      .on('end', () => {
        console.log('转换完成');
      })
      .on('error', (err) => {
        console.error('转换失败', err);
      })
      .run();
  } else {
    console.error('未找到 m3u8 视频链接');
  }
}

run();

顺便推荐一个m3u8在线转换的工具网站:
https://blog.luckly-mjw.cn/tool-show/m3u8-downloader/index.html

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值