Skip to content

Instantly share code, notes, and snippets.

@graphicbeacon
Created December 17, 2018 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save graphicbeacon/bad5a13babe358a5867e70d90aa05011 to your computer and use it in GitHub Desktop.
Save graphicbeacon/bad5a13babe358a5867e70d90aa05011 to your computer and use it in GitHub Desktop.
Code snippet for "Write your first Web Scraper in Dart" Medium post
// 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