node获取抖音直播间Id
信息位置
直播间信息存放在id是RENDER_DATA的script标签里
安装依赖
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);
}
return getRoomInfo(liveUrl);
}
/**
* 根据直播地址获取直播房间信息和主播信息
* @param {String} liveUrl
* @returns
*/
function getRoomInfo(liveUrl) {
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));
});