Web scraping

suggest change

Web scraping means downloading web pages and extracting structured data from their HTML. A scraper in Dart has three parts:

  1. Fetching: an HTTP client from package:http with a proper User-Agent, timeouts, retries and rate limiting.
  2. Parsing: package:html turns the markup into a DOM that you query with CSS selectors. The Parsing HTML article covers the DOM API in detail.
  3. Crawling: following pagination and detail links, limiting concurrency and saving the results.

The examples use quotes.toscrape.com and books.toscrape.com, two sandbox sites made for practicing scraping.

Setup

dependencies:
  html: ^0.15.7
  http: ^1.6.0
  pool: ^1.5.1   # concurrency limit
  crypto: ^3.0.6 # only for the disk cache example

Run dart pub get.

Fetching and parsing a page

Write the fetch step as a small function that checks the status code and content type, and passes the raw bytes to the parser. With bytes, the parser detects the encoding from the <meta charset> tag. response.body decodes with the charset from the Content-Type header and falls back to Latin-1 when the header has none, which garbles UTF-8 pages.

import 'dart:io';

import 'package:html/dom.dart';
import 'package:html/parser.dart' as html_parser;
import 'package:http/http.dart' as http;

Future<Document> fetchDocument(http.Client client, Uri url) async {
  final response = await client.get(url);
  if (response.statusCode != 200) {
    throw HttpException('GET $url -> ${response.statusCode}', uri: url);
  }
  final type = response.headers['content-type'] ?? '';
  if (!type.contains('text/html')) {
    throw FormatException('Expected HTML from $url, got "$type"');
  }
  return html_parser.parse(response.bodyBytes, sourceUrl: url.toString());
}

typedef Quote = ({String text, String author, List<String> tags});

List<Quote> parseQuotes(Document doc) => [
      for (final q in doc.querySelectorAll('div.quote'))
        (
          text: q.querySelector('span.text')?.text.trim() ?? '',
          author: q.querySelector('small.author')?.text.trim() ?? '',
          tags: [for (final t in q.querySelectorAll('a.tag')) t.text.trim()],
        ),
    ];

Future<void> main() async {
  final client = http.Client();
  try {
    final doc =
        await fetchDocument(client, Uri.parse('https://quotes.toscrape.com/'));
    final quotes = parseQuotes(doc);
    print('${quotes.length} quotes');
    final first = quotes.first;
    print('${first.author}: ${first.text}');
    print('tags: ${first.tags.join(', ')}');
  } finally {
    client.close();
  }
}
10 quotes
Albert Einstein: “The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”
tags: change, deep-thoughts, thinking, world

Always reuse one http.Client for many requests and call close() at the end. The client keeps connections alive, so later requests to the same host skip the TCP and TLS handshake.

Parsing is a separate function that takes a Document and returns records. This keeps the parsing logic easy to test without the network, as shown in the testing section below.

Use ?. and ?? when you read elements. Sites change their markup, and one missing element shouldn't crash a scrape of thousands of pages.

A polite HTTP client

A well-behaved scraper identifies itself, waits between requests and gives up on hung connections. You can add all of this to every request by wrapping a client in a subclass of http.BaseClient. You only override send(). All the helpers such as get() and post() go through it.

import 'dart:async';

import 'package:http/http.dart' as http;

/// Spaces calls to [wait] at least [interval] apart, even when they
/// are made concurrently.
class Throttle {
  Throttle(this.interval);

  final Duration interval;
  DateTime _next = DateTime.fromMillisecondsSinceEpoch(0);

  Future<void> wait() async {
    final now = DateTime.now();
    final start = _next.isAfter(now) ? _next : now;
    _next = start.add(interval); // reserve the slot synchronously
    final delay = start.difference(now);
    if (delay > Duration.zero) await Future<void>.delayed(delay);
  }
}

class PoliteClient extends http.BaseClient {
  PoliteClient(
    this._inner, {
    required this.userAgent,
    Duration interval = const Duration(seconds: 1),
    this.timeout = const Duration(seconds: 20),
  }) : _throttle = Throttle(interval);

  final http.Client _inner;
  final String userAgent;
  final Duration timeout;
  final Throttle _throttle;

  @override
  Future<http.StreamedResponse> send(http.BaseRequest request) async {
    await _throttle.wait();
    request.headers['user-agent'] = userAgent;
    request.headers['accept'] ??= 'text/html,application/xhtml+xml';
    // Fails with TimeoutException if the response headers don't arrive in time.
    return _inner.send(request).timeout(timeout);
  }

  @override
  void close() => _inner.close();
}

Throttle.wait() computes and stores the next free time slot before it awaits. If ten requests start at once, they get slots 0s, 1s, 2s and so on, instead of all waking up after one second.

Retrying failed requests

Servers sometimes return 503 Service Unavailable or 429 Too Many Requests, and connections sometimes drop. package:http includes RetryClient, which retries with exponential backoff:

import 'dart:async';
import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:http/retry.dart';

http.Client createScraperClient() {
  return RetryClient(
    PoliteClient(
      http.Client(),
      userAgent: 'quotes-scraper/1.0 (+mailto:you@example.com)',
    ),
    retries: 3,
    when: (response) =>
        response.statusCode == 429 || response.statusCode >= 500,
    whenError: (error, stackTrace) =>
        error is SocketException ||
        error is TimeoutException ||
        error is http.ClientException,
    onRetry: (request, response, retryCount) => print(
        'retry #${retryCount + 1} ${request.url} (${response?.statusCode})'),
  );
}

RetryClient wraps PoliteClient, so each retry also goes through the throttle. The default delay is 500 ms, multiplied by 1.5 for each further retry. Pass delay: (retryCount) => ... to change it. RetryClient doesn't read the Retry-After header. If a site sends it, wait at least that long before you continue.

Put contact information in the User-Agent. It lets site owners reach you instead of blocking you.

Respecting robots.txt

robots.txt lists the paths that crawlers should not visit. The following parser is simplified. It handles User-agent, Allow and Disallow with prefix matching, but not * and $ wildcards. For full support, use a package such as robots_txt from pub.dev.

import 'dart:convert';
import 'dart:math';

class RobotsRules {
  RobotsRules._(this._allow, this._disallow);

  final List<String> _allow;
  final List<String> _disallow;

  /// Collects the rules from groups for `*` and for [agent].
  factory RobotsRules.parse(String text, {required String agent}) {
    final allow = <String>[];
    final disallow = <String>[];
    var groupApplies = false;
    var previousWasAgent = false;

    for (var line in const LineSplitter().convert(text)) {
      line = line.split('#').first.trim();
      final colon = line.indexOf(':');
      if (colon < 0) continue;
      final key = line.substring(0, colon).trim().toLowerCase();
      final value = line.substring(colon + 1).trim();

      if (key == 'user-agent') {
        // Consecutive User-agent lines share one group.
        if (!previousWasAgent) groupApplies = false;
        if (value == '*' || value.toLowerCase() == agent.toLowerCase()) {
          groupApplies = true;
        }
        previousWasAgent = true;
        continue;
      }
      previousWasAgent = false;
      if (!groupApplies || value.isEmpty) continue;
      if (key == 'allow') allow.add(value);
      if (key == 'disallow') disallow.add(value);
    }
    return RobotsRules._(allow, disallow);
  }

  /// The longest matching rule wins; on a tie, Allow wins.
  bool isAllowed(Uri url) {
    var path = url.path.isEmpty ? '/' : url.path;
    if (url.hasQuery) path = '$path?${url.query}';
    int longest(List<String> rules) =>
        rules.where(path.startsWith).fold<int>(-1, (m, r) => max(m, r.length));
    return longest(_allow) >= longest(_disallow);
  }
}

void main() {
  const robotsTxt = '''
User-agent: *
Disallow: /admin/
Disallow: /search
Allow: /search/help

User-agent: BadBot
Disallow: /
''';

  final rules = RobotsRules.parse(robotsTxt, agent: 'quotes-scraper');
  for (final path in ['/products', '/admin/users', '/search?q=dart', '/search/help']) {
    print('$path: ${rules.isAllowed(Uri.parse('https://example.com$path'))}');
  }
}
/products: true
/admin/users: false
/search?q=dart: false
/search/help: true

The Disallow: / rule for BadBot doesn't apply to quotes-scraper. In a real scraper, download https://host/robots.txt once per host. If it returns 404, everything is allowed.

Following pagination

Most listings are split into pages with a "Next" link. Follow it until it disappears, and resolve each href against the current page URL with Uri.resolve(). Keep a set of visited URLs so that a site with a loop can't keep you crawling forever:

Future<List<Quote>> scrapeAllQuotes(http.Client client, Uri start) async {
  final quotes = <Quote>[];
  final visited = <Uri>{};
  Uri? next = start;

  while (next != null && visited.add(next)) {
    final url = next;
    final doc = await fetchDocument(client, url);
    final pageQuotes = parseQuotes(doc);
    quotes.addAll(pageQuotes);
    print('${url.path}: ${pageQuotes.length} quotes');

    final href = doc.querySelector('li.next > a')?.attributes['href'];
    next = href == null ? null : url.resolve(href);
  }
  return quotes;
}

Future<void> main() async {
  final client = createScraperClient();
  try {
    final quotes =
        await scrapeAllQuotes(client, Uri.parse('https://quotes.toscrape.com/'));
    print('Total: ${quotes.length}');

    final byAuthor = <String, int>{};
    for (final q in quotes) {
      byAuthor.update(q.author, (n) => n + 1, ifAbsent: () => 1);
    }
    final top = byAuthor.entries.toList()
      ..sort((a, b) => b.value.compareTo(a.value));
    for (final e in top.take(3)) {
      print('${e.key}: ${e.value}');
    }
  } finally {
    client.close();
  }
}
/: 10 quotes
/page/2/: 10 quotes
...
/page/10/: 10 quotes
Total: 100
Albert Einstein: 10
J.K. Rowling: 9
Marilyn Monroe: 7

Uri.resolve() handles every kind of link. On books.toscrape.com, the "next" link on /catalogue/page-2.html is just page-3.html, and url.resolve('page-3.html') correctly returns https://books.toscrape.com/catalogue/page-3.html.

Scraping detail pages concurrently

A listing page usually links to detail pages that contain more data. Fetching them one at a time is slow. Firing all requests at once overloads the server. Use Pool from package:pool to run a fixed number of requests at a time:

import 'package:html/dom.dart';
import 'package:http/http.dart' as http;
import 'package:pool/pool.dart';

typedef Book = ({
  String title,
  double price,
  int rating,
  String upc,
  int inStock,
});

const _ratings = {'One': 1, 'Two': 2, 'Three': 3, 'Four': 4, 'Five': 5};

Book parseBook(Document doc) {
  final main = doc.querySelector('div.product_main')!;

  // The product information table: <tr><th>UPC</th><td>a897fe39b1053632</td></tr>
  final info = {
    for (final row in doc.querySelectorAll('table.table-striped tr'))
      (row.querySelector('th')?.text.trim() ?? ''):
          (row.querySelector('td')?.text.trim() ?? ''),
  };

  final priceText = main.querySelector('p.price_color')?.text ?? '';
  final ratingClass = main
      .querySelector('p.star-rating')
      ?.classes
      .firstWhere(_ratings.containsKey, orElse: () => '');
  final stock = RegExp(r'\d+').firstMatch(info['Availability'] ?? '');

  return (
    title: main.querySelector('h1')?.text.trim() ?? '',
    price: double.tryParse(priceText.replaceAll(RegExp(r'[^\d.]'), '')) ?? 0,
    rating: _ratings[ratingClass] ?? 0,
    upc: info['UPC'] ?? '',
    inStock: int.tryParse(stock?.group(0) ?? '') ?? 0,
  );
}

Future<void> main() async {
  final client = createScraperClient();
  final pool = Pool(4); // at most 4 requests in flight
  try {
    final listUrl = Uri.parse('https://books.toscrape.com/catalogue/page-1.html');
    final listing = await fetchDocument(client, listUrl);
    final bookUrls = [
      for (final a in listing.querySelectorAll('article.product_pod h3 a'))
        listUrl.resolve(a.attributes['href']!),
    ];

    final failures = <Uri, Object>{};
    final results = await Future.wait([
      for (final url in bookUrls)
        pool.withResource(() async {
          try {
            return parseBook(await fetchDocument(client, url));
          } catch (e) {
            failures[url] = e; // one bad page must not stop the rest
            return null;
          }
        }),
    ]);

    final books = results.nonNulls.toList();
    print('Scraped ${books.length} books, ${failures.length} failures');
    for (final b in books.take(3)) {
      print('${b.title} | £${b.price} | ${b.rating}★ | ${b.inStock} in stock');
    }
  } finally {
    await pool.close();
    client.close();
  }
}
Scraped 20 books, 0 failures
A Light in the Attic | £51.77 | 3★ | 22 in stock
Tipping the Velvet | £53.74 | 1★ | 20 in stock
Soumission | £50.1 | 1★ | 20 in stock

Future.wait keeps the results in the same order as bookUrls, even though the requests finish in any order. The pool limits how many requests are open at once, and the throttle in PoliteClient sets the overall request rate. Lower the throttle interval only if the site allows it.

Structured data: JSON-LD and embedded JSON

Before you write selectors, view the page source and look for data that is already structured. Many sites embed schema.org metadata as JSON-LD for search engines, and single-page apps often embed their initial state as JSON. Reading that JSON is much more robust than scraping the visible markup:

import 'dart:convert';

import 'package:html/parser.dart';

void main() {
  final doc = parse('''
<html><head>
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "Product",
  "name": "Mechanical Keyboard",
  "sku": "KB-104",
  "offers": {"@type": "Offer", "price": "89.90", "priceCurrency": "EUR"}
}
</script>
</head><body><h1>Mechanical Keyboard</h1></body></html>''');

  for (final script
      in doc.querySelectorAll('script[type="application/ld+json"]')) {
    final data = jsonDecode(script.text);
    if (data
        case {
          '@type': 'Product',
          'name': String name,
          'offers': {'price': String price, 'priceCurrency': String currency},
        }) {
      print('$name: $price $currency');
    }
  }
}
Mechanical Keyboard: 89.90 EUR

The map pattern in the if case checks the shape and extracts the values in one step. JSON-LD that doesn't match is skipped. See Pattern matching and JSON.

If the page loads its data with JavaScript, open the browser's developer tools, go to the Network tab, and find the request that returns JSON. Calling that endpoint directly with http.get and jsonDecode is usually simpler and faster than parsing HTML at all. See REST APIs.

Logging in: forms and cookies

Some data is only visible after you log in. To log in, fetch the login form, copy its hidden fields (often a CSRF token), post the form, and send the session cookie with later requests. package:http doesn't store cookies, so keep them yourself:

import 'dart:io' show Cookie;

import 'package:html/parser.dart';
import 'package:http/http.dart' as http;

class CookieJar {
  final _cookies = <String, String>{};

  void update(http.BaseResponse response) {
    // headersSplitValues keeps multiple Set-Cookie headers separate.
    for (final value in response.headersSplitValues['set-cookie'] ?? const []) {
      final cookie = Cookie.fromSetCookieValue(value);
      _cookies[cookie.name] = cookie.value;
    }
  }

  Map<String, String> get headers => _cookies.isEmpty
      ? {}
      : {'cookie': _cookies.entries.map((e) => '${e.key}=${e.value}').join('; ')};
}

Future<void> main() async {
  final client = http.Client();
  final jar = CookieJar();
  final loginUrl = Uri.parse('https://quotes.toscrape.com/login');
  try {
    // 1. Load the form and collect all its fields, including hidden ones.
    final formPage = await client.get(loginUrl);
    jar.update(formPage);
    final form = parse(formPage.bodyBytes).querySelector('form')!;
    final fields = {
      for (final input in form.querySelectorAll('input[name]'))
        input.attributes['name']!: input.attributes['value'] ?? '',
    };
    fields['username'] = 'demo';
    fields['password'] = 'demo';

    // 2. Post it. A Map body is sent as application/x-www-form-urlencoded.
    final action = loginUrl.resolve(form.attributes['action'] ?? '');
    final result = await client.post(action, headers: jar.headers, body: fields);
    jar.update(result);
    print('POST status: ${result.statusCode}'); // 302: redirect after login

    // 3. Requests that send the session cookie are now logged in.
    final home = await client.get(
        Uri.parse('https://quotes.toscrape.com/'), headers: jar.headers);
    final loggedIn = parse(home.bodyBytes).querySelector('a[href="/logout"]') != null;
    print('Logged in: $loggedIn');
  } finally {
    client.close();
  }
}
POST status: 302
Logged in: true

The client doesn't follow redirects for a POST, so you get the 302 response and its Set-Cookie header directly. response.headers['set-cookie'] joins multiple cookies with commas, and cookie values and expiry dates can contain commas too. That's why the code uses headersSplitValues. The Cookies article covers cookie attributes in more detail.

Only scrape behind a login with an account you own, and check the site's terms of service first.

Caching pages during development

While you work on selectors, you run the scraper many times. Caching downloaded pages on disk avoids repeated requests to the site and makes each run instant:

import 'dart:convert';
import 'dart:io';

import 'package:crypto/crypto.dart';
import 'package:html/dom.dart';
import 'package:html/parser.dart' as html_parser;
import 'package:http/http.dart' as http;

Future<Document> fetchCached(http.Client client, Uri url,
    {Directory? cacheDir}) async {
  final dir = cacheDir ?? Directory('.scrape-cache');
  final name = sha1.convert(utf8.encode(url.toString())).toString();
  final file = File('${dir.path}/$name.html');

  if (await file.exists()) {
    return html_parser.parse(await file.readAsBytes());
  }
  final response = await client.get(url);
  if (response.statusCode != 200) {
    throw HttpException('GET $url -> ${response.statusCode}', uri: url);
  }
  await dir.create(recursive: true);
  await file.writeAsBytes(response.bodyBytes);
  return html_parser.parse(response.bodyBytes);
}

Delete the directory when you want fresh data. Caching the raw HTML also lets you re-run your parser with new selectors later without downloading anything again.

Testing scrapers without the network

Pass the http.Client into your code instead of creating it inside. Then tests can use MockClient from package:http/testing.dart, which returns canned responses. Add test to dev_dependencies and run the test with dart test:

import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:test/test.dart';

const page1 = '''
<div class="quote"><span class="text">“Quote one”</span>
  <small class="author">Ada</small><a class="tag">math</a></div>
<ul class="pager"><li class="next"><a href="/page/2/">Next</a></li></ul>''';

const page2 = '''
<div class="quote"><span class="text">“Quote two”</span>
  <small class="author">Linus</small></div>''';

void main() {
  test('follows pagination and parses quotes', () async {
    final requested = <String>[];
    final client = MockClient((request) async {
      requested.add(request.url.path);
      final body = switch (request.url.path) {
        '/' => page1,
        '/page/2/' => page2,
        _ => null,
      };
      return body == null
          ? http.Response('Not found', 404)
          : http.Response(body, 200,
              headers: {'content-type': 'text/html; charset=utf-8'});
    });

    final quotes =
        await scrapeAllQuotes(client, Uri.parse('https://quotes.test/'));

    expect(requested, ['/', '/page/2/']);
    expect(quotes.map((q) => q.author), ['Ada', 'Linus']);
    expect(quotes.first.tags, ['math']);
    expect(quotes.last.tags, isEmpty);
  });
}

Save a few real pages as fixture files too, and run your parser on them in tests. When the site changes its markup, a failing test tells you quickly.

Saving the results

Write the records as JSON for other programs, or as CSV for spreadsheets (see CSV):

import 'dart:convert';
import 'dart:io';

Future<void> saveQuotes(List<Quote> quotes, String path) async {
  final json = const JsonEncoder.withIndent('  ').convert([
    for (final q in quotes) {'text': q.text, 'author': q.author, 'tags': q.tags},
  ]);
  await File(path).writeAsString(json);
}

For long crawls, write each record as soon as you have it, for example one JSON object per line with IOSink.writeln, so that a crash halfway through doesn't lose everything.

Pages rendered with JavaScript

package:html only sees the HTML that the server sends. If the content is built in the browser (for example, https://quotes.toscrape.com/js/ shows no quotes in its raw HTML), first look for the JSON API as described above. If there isn't one, control a headless Chrome with the puppeteer package and parse the rendered HTML:

import 'package:html/parser.dart';
import 'package:puppeteer/puppeteer.dart';

Future<void> main() async {
  final browser = await puppeteer.launch(); // downloads Chromium on first run
  try {
    final page = await browser.newPage();
    await page.goto('https://quotes.toscrape.com/js/', wait: Until.networkIdle);
    final html = await page.content;
    final doc = parse(html ?? '');
    print(doc.querySelectorAll('div.quote').length); // 10
  } finally {
    await browser.close();
  }
}

A headless browser is much slower and uses a lot more memory than plain HTTP requests, so use it only when nothing else works.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents