- video url(https://youtu.be/[id]) ๋ฅผ axios์ ํ์ฉํ์ฌ html ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ด
- ๊ฐ์ ธ์จ ๋ฐ์ดํฐ์์ ์ ํ๋ธ ์์ ๊ด๋ จ ์ ๋ณด๋ค์ jsonParsing ํจ
- ํด๋น id ์์ ์ ๋ณด (ex. artist information , video data, thumbnail , title , LIKE number , playTime, recommendVideoData, description . . . )
- ์ถ์ฒ ์์ ์ ๋ณด (playTime,artist information, title,description,videoId,url,thumbnail,playTime(second) . . . )
how to get specific string from html data | ํน์ ๋ฌธ์์ด์ html ๋ฐ์ดํฐ์์ ๊ฐ์ ธ์ค๋ ๋ฒ
const searchStart = '"category":"'; //start of the string | ๋ฌธ์์ด์ ์์๋ถ๋ถ
const searchEnd = '"'; //end of the string | ๋ฌธ์์ด์ ๋๋ถ๋ถ
const indexS = data.indexOf(searchStart); //searchStart location (Number) | ๊ฒ์ํ ๋ ค๋ ๋ฌธ์์ด์ ์๋ถ๋ถ ์์น (Number)
if (indexS < 0) return `Error` //if indexS is not found, it returns `Error` | searchStart ์ ์์น๋ฅผ ์ฐพ์ง ๋ชปํ๋ค๋ฉด `Error` ๋ฆฌํด (๋ฌธ์์ด์ด ์กด์ฌํ์ง์์์ ์๋ฌ ๋ฐ์)
var content = data.slice(indexS + searchStart.length); // remove from data to indexS | data๋ฅผ indexS ๋งํผ ์ ๊ฑฐ (๊ฒ์ํ ๋ ค๋ ๋ฌธ์์ด์ ์๋ถ๋ถ ์ ๊ฑฐ)
const indexE = content.indexOf(searchEnd); //searchEnd location (Number) | searchEnd ์์น (๊ฒ์ํ ๋ ค๋ ๋ฌธ์์ด์ ๋๋ถ๋ถ์ ์์น)
content = content.slice(0, indexE); // remove strings out of range from 0 to indexE in content | content์์ 0๋ฒ์งธ์ indexE๋ฒ์งธ๊น์ง ๋ฌธ์์ด ์ด์ธ์ ๊ฒ์ ์ ๊ฑฐํจ
return JSON.parse(content)-
์ฆ "category":" ๋ก ์์ํ๊ณ " ๋ก ๋๋๋ ๋ถ๋ถ์ axios๋ก ๊ฐ์ ธ์จ html.data์์ ๊ฒ์ํ์ฌ ์ถ์ถํ stringํ์์ json์ผ๋ก ํ์ฑํ๋ ๊ณผ์ ์ด๋ค.
-
์ด ๊ณผ์ ์ ์์ ์ด์ธ์ ๋ชจ๋ ๋ฌธ์์ด์์ ํน์ ๋ฌธ์์ด์ ์ค์ฐจ์์ด ํ์ฑํ ์ ์์ผ๋ฉฐ ์๋ ์์์์๋ ์ ๊ทํํ์์ ์ฌ์ฉํ์ฌ ์ ๊ตํ๊ฒ ํ์ฑํ๋ ๋ฐฉ๋ฒ์ ์๋ ค์ค๋ค.
ํด๋น ๊ตฌ๋ฌธ์ videoData๋ฅผ ์ ๊ทํํ์์ผ๋ก ์ถ์ถํ๋ ์์ค์ฝ๋์ด๋ฉฐ ์์ชฝ์ ์์์์ ์๋ซ ๋ถ๋ถ๋ง ๋ณ๊ฒฝํ์ฌ ์ฌ์ฉํจ
//data = html.data
const regex = /<script nonce="(.+?)">var ytInitialPlayerResponse =/g; // (.+?) ์ ๋ค์ํ ํํ์ ๋ฌธ์์ด์ ํฌํจํ ์์๋ค.
const searchStart = (data.match(regex))[0] //data์์ regex๋ธ๋ถ์ ์ถ์ถํ์ฌ searchStart์ ์ ์ฅ (๊ฒ์ํ ๋ ค๋ ๋ฌธ์์ด์ ์์๋ถ๋ถ)
const searchEnd = ';</script><div id="player" class="skeleton flexy">'; //๊ฒ์ํ ๋ ค๋ ๋ฌธ์์ด์ ๋๋ถ๋ถ- 2์ฃผ๋์ ์ ํ๋ธ data๋ฅผ ๋ถ์ํ๋ฉฐ ๋๋์
์ง์ ์ฝ๋๋ฅผ ์์ ํด๊ฐ๋ฉฐ ๊ตฌ์กฐ๋ฅผ ํ์ ํ๊ณ ์ด์ ๋์์ ์ ๊ทํํ์์ ์ตํ์์์ผ๋ฉฐ ๊ณต์ ์ธ ์ฉ๋๋ก ์ฌ์ฉํ๋ ๊ฒ์ด ์๋๋ผ๋ฉด ์ถฉ๋ถํ ํผ์์ ๋ง๋ค์ด ํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ณด๋ค ๋น ๋ฅธ ์๋๋ก ํฌ๋กค๋ง์ ํ ์์๋ค. ๋ค๋ง html์ body data์ ํน์ง์ ๋นจ๋ฆฌ ํ์ ํ๊ธฐ ํ๋ค๋ค๋ฉด ๊ทธ๋ฅ ytdl-core๋ฅผ ์ฌ์ฉํ๋๊ฒ ์ ์ ๊ฑด๊ฐ์ ์ข๋ค.