Created
September 30, 2023 17:35
-
-
Save ErykDarnowski/740e98d644f2ab350f71801f3e970eb1 to your computer and use it in GitHub Desktop.
Automatically download reddit post and all it's comments
This file contains 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
/* Instructions | |
1. Click on a reddit post you're interested in. | |
2. Open the dev tools ('F12') go to the `Console` tab. | |
3. Copy & paste in the code bellow and press 'Enter'. | |
- Wait for the page to fully load | |
- Make sure any comments aren't folded (they shouldn't be if the page just loaded) | |
- Scroll to the bottom of the page to make sure all comments are loaded. | |
- If you've run this script once, you'll need to reload the page. | |
4. Enjoy! | |
*/ | |
// Function that discretely creates a text file and automatically downloads it -> https://ourcodeworld.com/articles/read/189/how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server | |
const downloadFile = (filename, text) => { | |
const el = document.createElement('a'); | |
el.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); | |
el.setAttribute('download', filename); | |
el.style.display = 'none'; | |
document.body.appendChild(el); | |
el.click(); | |
document.body.removeChild(el); | |
}; | |
// 30.09.2023 | |
const [postParent] = document.querySelectorAll('div[data-test-id=post-content]'); | |
const postTitle = postParent.querySelector('div[data-adclicklocation=title]').innerText; | |
const posterUsername = postParent.querySelector('a[data-testid=post_author_link]').textContent; | |
const postText = postParent.querySelector('p').parentElement.textContent; | |
const commentTextEls = [...document.querySelectorAll('div[data-testid=comment]')]; | |
let counter = 1; | |
let final = ''; | |
const padString = ' '; | |
// --- | |
final += posterUsername + ' - ' + postTitle + '\n\n'; | |
final += postText + '\n\n'; | |
final += '=================='; | |
commentTextEls.map(commTextEl => { | |
// 30.09.2023 | |
const commParent = commTextEl.parentElement; | |
const commUsername = commParent.querySelector('a[data-testid=comment_author_link]').textContent; | |
const level = parseFloat(commParent.querySelector('span').textContent.split(' ').pop()) - 1; | |
const commText = commTextEl.textContent; | |
final += '\n\n'; | |
final += padString.repeat(level) + `${counter++}. u/${commUsername}\n`; | |
final += padString.repeat(level) + commText | |
}); | |
downloadFile(`${postTitle}.txt`, final); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment