Created
December 17, 2018 12:17
-
-
Save graphicbeacon/bad5a13babe358a5867e70d90aa05011 to your computer and use it in GitHub Desktop.
Code snippet for "Write your first Web Scraper in Dart" Medium post
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
// lib/hacker_news_scraper.dart | |
import 'dart:convert'; | |
import 'package:http/http.dart'; | |
import 'package:html/parser.dart'; | |
import 'package:html/dom.dart'; | |
Future initiate() async { | |
// Make API call to Hackernews homepage | |
var client = Client(); | |
Response response = await client.get('https://news.ycombinator.com'); | |
// Use html parser | |
var document = parse(response.body); | |
List<Element> links = document.querySelectorAll('td.title > a.storylink'); | |
List<Map<String, dynamic>> linkMap = []; | |
for (var link in links) { | |
linkMap.add({ | |
'title': link.text, | |
'href': link.attributes['href'], | |
}); | |
} | |
return json.encode(linkMap); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment