Created
May 22, 2017 18:34
-
-
Save gperrin01/9fb1be1b60b97ba6644c7f527cbe3111 to your computer and use it in GitHub Desktop.
Scrape Hacker News first page - Sample code to show async/await coding
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
nick.newTab().then(async (tab) => { | |
await tab.open("news.ycombinator.com") | |
await tab.untilVisible("#hnmain") // We make sure we have loaded the page | |
await tab.inject("../injectables/jquery-3.0.0.min.js") // We're going to use jQuery to scrape | |
const hackerNewsLinks = await tab.evaluate((arg, callback) => { | |
const data = [] | |
$(".athing").each((index, element) => { | |
data.push({ | |
title: $(element).find(".storylink").text(), | |
url: $(element).find(".storylink").attr("href") | |
}) | |
}) | |
callback(null, data) | |
}) | |
console.log(JSON.stringify(hackerNewsLinks, null, 3)) | |
}) | |
.then(() => { | |
console.log("Job done!") | |
nick.exit() | |
}) | |
.catch((err) => { | |
console.log(`Something went wrong: ${err}`) | |
nick.exit(1) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment