node获取抖音直播间Id

node获取抖音直播间Id

安装依赖

npm install fetch cheerio
# 或
pnpm install fetch cheerio

node代码

// room.js
const fetch = require("fetch");
const cheerio = require("cheerio");
// cookie
var cookieJar = new fetch.CookieJar();

/**
 * 获取连接资源
 * @param {String} url 
 * @returns 
 */
function get(url) {
  return new Promise((resolve, reject) => {
    fetch.fetchUrl(url, { cookieJar }, function (err, response, bytes) {
      if (err) {
        reject(err);
      } else {
        resolve(bytes.toString("utf-8"));
      }
    });
  });
}

/**
 * 解析Html
 * 获取RENDER_DATA
 * @param {String} liveUrl 
 * @param {String} html 
 * @returns 
 */
function loadHtml(liveUrl, html) {
  var $ = cheerio.load(html);
  //var srcipt = $("#RENDER_DATA");
  //const str = srcipt.text();
  //if (str) {
  //  const renderData = decodeURIComponent(str);
  //  return Promise.resolve(renderData);
  //}
  var regRoomId = /roomInfo[\W\w]*?id_str[\W:]{5}[0-9]+/;
  var regNum = /[0-9]+/;
  var roomIds = [];
  $("script").each((index, el) => {
    if (
      el.children.length > 0 &&
      el.children[0].type === "text" &&
      regRoomId.test(el.children[0].data)
    ) {
      var str = regRoomId.exec(el.children[0].data)[0];
      var num = regNum.exec(str);
      if (num) {
        roomIds.push(num[0])
      }
    }
  });
  if (roomIds.length > 0) {
    return Promise.resolve({ roomId: roomIds.join(',') });
  }
  return getRoomInfo(liveUrl);
}
let count = 0;
/**
 * 根据直播地址获取直播房间ID
 * @param {String} liveUrl 
 * @returns 
 */
function getRoomInfo(liveUrl) {
  count++;
  if(count > 5){
    return Promise.reject('获取直播间Id失败。')
  }
  return new Promise((resolve, reject) => {
    get(liveUrl)
      .then((html) => {
        loadHtml(liveUrl, html)
          .then((res) => {
            if (typeof res === "string") {
              var data = JSON.parse(res);
              resolve(data.app.initialState.roomStore.roomInfo);
            } else resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      })
      .catch((err) => {
        reject(err);
      });
  });
};

module.exports = getRoomInfo
// test.js
const getRoomInfo = require("./room");
// 查看https://live.douyin.com/1的房间Id
getRoomInfo("https://live.douyin.com/1").then((res) => {
  const { roomId } = res;
  console.log(roomId); // output  6760514382213548814

  // 写入文件查看
  //const { writeFileSync } = require("fs");
  //writeFileSync("./room.json", JSON.stringify(res, null, 2));
});

你可能感兴趣的:(nodejs,javascript)