Last active
August 29, 2015 14:25
-
-
Save ds0nt/9cccc331b657a15d5e37 to your computer and use it in GitHub Desktop.
reddit scraper
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
#!/bin/babel-node | |
import jsdom from 'jsdom' | |
import fs from 'fs' | |
let subreddit = process.argv.length > 2 | |
? process.argv[2] | |
: 'webware' | |
function grab(url) { | |
console.log('fetching', url) | |
return new Promise((ok, fail) => { | |
jsdom.env({ | |
url, | |
done: (err, window) => { | |
if (err) | |
fail(err) | |
else | |
ok(window) | |
} | |
}) | |
}) | |
} | |
async function reddit(subreddit) { | |
let { document } = await grab(`http://www.reddit.com/r/${subreddit}/`) | |
let posts = [] | |
let html = '' | |
let items = document.querySelectorAll('.thing a.title') | |
for (var i = items.length - 1; i >= 0; i--) { | |
posts.push({ | |
title: items[i].innerHTML, | |
href: items[i].href, | |
}) | |
html = items[i].outerHTML + html | |
} | |
return { posts, html }; | |
} | |
async function run() { | |
let { posts, html } = await reddit(subreddit) | |
console.log(posts) | |
fs.appendFile( | |
'reddit.json', | |
JSON.stringify(posts), | |
() => console.log('appended file reddit.json')) | |
fs.appendFile( | |
'reddit.html', | |
html, | |
() => console.log('appended file reddit.html')) | |
} | |
run() |
Author
ds0nt
commented
Jul 22, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment