Skip to content

Instantly share code, notes, and snippets.

@letelete
Last active August 25, 2022 13:14
Show Gist options
  • Save letelete/265551ba27502251a807d25ad8b761c3 to your computer and use it in GitHub Desktop.
Save letelete/265551ba27502251a807d25ad8b761c3 to your computer and use it in GitHub Desktop.
Create youtube playlist from video urls in the DOM
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());
@letelete
Copy link
Author

Usage: just call the scrapp() method with your selector and paste the code into a browser console

@letelete
Copy link
Author

letelete commented Feb 25, 2021

Why embedded and not just /watch_videos?video_ids=...? Limit of 50 URLs per request

@kshalot
Copy link

kshalot commented Aug 25, 2022

🥇

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment