Last active
August 25, 2022 13:14
-
-
Save letelete/265551ba27502251a807d25ad8b761c3 to your computer and use it in GitHub Desktop.
Create youtube playlist from video urls in the DOM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const getPlaylistUrl = (firstId, comaSeparatedIds) => { | |
if (typeof comaSeparatedIds !== 'string') { | |
throw new Error( | |
'Ids must be a string of concatenated video ids separated with comma character' | |
); | |
} | |
return `https://www.youtube.com/embed/${firstId}?rel=0&version=3&playlist=${comaSeparatedIds}`; | |
}; | |
const createPlaylistFromIds = (ids) => { | |
if (!ids.length) throw new Error('Ids list cannot be empty'); | |
const firstId = ids[0]; | |
const comaSeparatedIds = ids.reduce( | |
(ids, id, index) => (index ? `${ids},${id}` : id), | |
'' | |
); | |
return getPlaylistUrl(firstId, comaSeparatedIds); | |
}; | |
const getAllVideoIdsFromUrls = (urls) => { | |
return urls | |
.map((url) => { | |
const matches = url.match(/watch\?v=(.+?)$/); | |
return matches.length >= 1 ? matches[1] : null; | |
}) | |
.filter((e) => e); | |
}; | |
const getAllUrlsWithSelector = (selector) => { | |
const elements = document.querySelectorAll(selector); | |
return [...elements].map((e) => e.href); | |
}; | |
/** | |
* | |
* @param {String} selector A html selector (compatible with document.querySelector) | |
* of elements containing a href="..." attribute, | |
* from which the video id can be extracted. | |
* | |
* @example | |
* Given element: <a class="but b_yt" href="https://www.youtube.com/watch?v=dQw4w9WgXcQ" target="_blank">Watch on YouTube</a> | |
* The selector equals .but.b_yt | |
*/ | |
const scrapp = (selector) => { | |
const urls = getAllUrlsWithSelector(selector); | |
const ids = getAllVideoIdsFromUrls(urls); | |
return createPlaylistFromIds(ids); | |
}; | |
const scrappMatemaks = () => scrapp('.but.b_yt'); | |
console.log(scrappMatemaks()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why embedded and not just /watch_videos?video_ids=...? Limit of 50 URLs per request