Parsing HTML

suggest change

Real-world HTML is rarely well-formed: tags are left unclosed, elements are nested incorrectly, and attributes lack quotes. An XML parser (see the XML article) rejects such input, and regular expressions break on it in subtle ways. In Dart, use the html package, a pure-Dart implementation of the HTML5 parsing algorithm. It builds the same DOM tree a browser would and works everywhere: command-line tools, servers and Flutter apps.

Installing the html package

dependencies:
  html: ^0.15.7
  http: ^1.6.0 # only needed to download pages

Run dart pub get. The package has three main libraries:

Parsing a document and querying with CSS selectors

parse() returns a Document. Find elements with querySelector(), which returns the first match or null, and querySelectorAll(), which returns a list of matches:

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

void main() {
  const source = '''
<!DOCTYPE html>
<html>
<head><title>Dart News</title></head>
<body>
  <ul id="articles">
    <li class="article featured"><a href="/posts/records">Records in Dart 3</a></li>
    <li class="article"><a href="/posts/patterns">Pattern matching</a></li>
    <li class="article"><a href="https://example.com/isolates">Isolates</a></li>
  </ul>
  <p>Unclosed paragraph
  <p>Another one <b>bold
</body>
</html>''';

  final Document document = html_parser.parse(source);

  print(document.head?.querySelector('title')?.text); // Dart News

  for (final link in document.querySelectorAll('#articles li.article > a')) {
    print('${link.text.trim()} -> ${link.attributes['href']}');
  }
  // Records in Dart 3 -> /posts/records
  // Pattern matching -> /posts/patterns
  // Isolates -> https://example.com/isolates

  final featured = document.querySelector('li.featured a');
  print('Featured: ${featured?.text}'); // Featured: Records in Dart 3

  // The broken markup was repaired the same way a browser repairs it.
  print(document.querySelectorAll('p').length); // 2
}

The parser never throws on malformed input. It closes the open <p> and <b> tags and produces a valid tree.

Supported selectors include type (a), class (.article), id (#articles), attributes ([href], [data-id="42"], [href^="https"]), the descendant and child combinators, :not(), :first-child and :last-child. Avoid :nth-child(): in version 0.15.7 it accepts only a plain number and counts all child nodes from 0, including whitespace text, so li:nth-child(1) can match the second <li>. Some pseudo-classes, such as :nth-of-type() and :nth-child(2n+1), are not implemented and throw UnimplementedError, so test unusual selectors before you rely on them.

Reading elements

An Element exposes its tag name, attributes, text and its position in the tree:

import 'package:html/parser.dart';

void main() {
  final document = parse('''
<div class="card primary" data-id="42" hidden>
  <h2>Title &amp; more</h2>
  <p>First <em>para</em>.</p>
  <img src="a.png" alt="A">
</div>''');

  final card = document.querySelector('div.card')!;

  print(card.localName); // div
  print(card.classes.contains('primary')); // true
  print(card.attributes['data-id']); // 42
  print(card.attributes.containsKey('hidden')); // true (value is '')
  print(card.attributes['missing']); // null

  final h2 = card.querySelector('h2')!;
  print(h2.text); // Title & more     (entities decoded)
  print(h2.innerHtml); // Title &amp; more (serialized HTML)
  print(card.querySelector('p')!.outerHtml); // <p>First <em>para</em>.</p>

  // Navigation
  print(card.children.map((e) => e.localName).toList()); // [h2, p, img]
  print(card.parent?.localName); // body
  print(h2.nextElementSibling?.localName); // p
}

Remember the difference between children and nodes. children contains only Element objects. nodes also contains Text and Comment nodes, including the whitespace between tags.

text returns the concatenated text of all descendants, including the contents of <script> and <style> tags. If you want only the visible text, walk the tree yourself (see below).

href and src attributes are often relative. Resolve them against the page URL with Uri.resolve():

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

Future<Set<Uri>> extractLinks(Uri pageUrl) async {
  final response = await http.get(
    pageUrl,
    headers: {'User-Agent': 'dart-link-extractor/1.0'},
  );
  if (response.statusCode != 200) {
    throw Exception('GET $pageUrl failed: ${response.statusCode}');
  }

  // Pass bytes, not response.body: the parser detects the encoding from
  // the <meta charset> tag, while response.body assumes the header charset.
  final document = parse(response.bodyBytes);

  final links = <Uri>{};
  for (final a in document.querySelectorAll('a[href]')) {
    final href = a.attributes['href']!.trim();
    if (href.isEmpty || href.startsWith('#') || href.startsWith('mailto:')) {
      continue;
    }
    links.add(pageUrl.resolve(href));
  }
  return links;
}

void main() async {
  final links = await extractLinks(Uri.parse('https://dart.dev/'));
  links.take(5).forEach(print);
}

Uri.parse('https://example.com/blog/post/').resolve('../about') yields https://example.com/blog/about, so both relative and root-relative links are handled.

Extracting a table into records

Scraping tabular data is a common task. Combine querySelectorAll with a list pattern to check the shape of each row:

import 'package:html/parser.dart';

typedef Release = ({String version, DateTime date, bool stable});

List<Release> parseReleases(String html) {
  final document = parse(html);
  return [
    for (final row in document.querySelectorAll('table#releases tbody tr'))
      if (row.querySelectorAll('td') case [final v, final d, final s])
        (
          version: v.text.trim(),
          date: DateTime.parse(d.text.trim()),
          stable: s.text.trim().toLowerCase() == 'yes',
        ),
  ];
}

void main() {
  const html = '''
<table id="releases">
  <thead><tr><th>Version</th><th>Date</th><th>Stable</th></tr></thead>
  <tbody>
    <tr><td>3.5.0</td><td>2024-08-06</td><td>yes</td></tr>
    <tr><td>3.6.0-dev</td><td>2024-09-01</td><td>no</td></tr>
    <tr><td colspan="3">Malformed row</td></tr>
  </tbody>
</table>''';

  for (final r in parseReleases(html)) {
    print('${r.version} ${r.date.year} stable=${r.stable}');
  }
  // 3.5.0 2024 stable=true
  // 3.6.0-dev 2024 stable=false
}

Rows that don't have exactly three cells are skipped. Like a browser, the parser inserts a <tbody> element even when the source omits it, so tbody tr works in both cases.

Walking the tree with TreeVisitor

To get readable text without scripts and styles, subclass TreeVisitor and override the callbacks for the node types you care about:

import 'package:html/dom.dart';
import 'package:html/dom_parsing.dart';
import 'package:html/parser.dart';

class TextExtractor extends TreeVisitor {
  final buffer = StringBuffer();

  static const _skip = {'script', 'style', 'noscript', 'template'};
  static const _block = {'p', 'div', 'li', 'h1', 'h2', 'h3', 'br', 'tr'};

  @override
  void visitElement(Element node) {
    if (_skip.contains(node.localName)) return; // don't descend
    if (_block.contains(node.localName)) buffer.writeln();
    visitChildren(node);
  }

  @override
  void visitText(Text node) {
    final text = node.data.replaceAll(RegExp(r'\s+'), ' ');
    if (text.trim().isNotEmpty) buffer.write(text);
  }
}

void main() {
  final document = parse('''
<h2>Title &amp; more</h2>
<script>var tracking = true;</script>
<p>First <em>paragraph</em>.</p>''');

  final extractor = TextExtractor()..visit(document.body!);
  print(extractor.buffer.toString().trim());
  // Title & more
  // First paragraph.
}

Modifying and serializing

The DOM can be changed and written back out with outerHtml. Text you assign through text or Text(...) is escaped automatically:

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

void main() {
  final document = parse('''
<div class="card" data-id="42" hidden>
  <h2>Old title</h2>
  <script>alert(1)</script>
  <p>Hello <em>world</em></p>
</div>''');

  final card = document.querySelector('.card')!;

  card.querySelector('script')!.remove();
  card.classes.add('seen');
  card.attributes['data-id'] = '43';
  card.attributes.remove('hidden');

  card.querySelector('h2')!.replaceWith(Element.html('<h1>New title</h1>'));
  card.querySelector('em')!.replaceWith(Text('Dart'));
  card.append(Element.tag('footer')..text = 'Price < 10 & more');

  print(card.outerHtml);
  // <div class="card seen" data-id="43">
  //   <h1>New title</h1>
  //   ...
  //   <p>Hello Dart</p>
  // <footer>Price &lt; 10 &amp; more</footer></div>
}

Removing <script> tags like this is not a safe HTML sanitizer: event handler attributes such as onclick and javascript: URLs remain. To display untrusted HTML safely, use an allow-list sanitizer, or escape the text with HtmlEscape from dart:convert.

Parsing fragments

For a snippet that isn't a full page, such as a comment body or a CMS field, use parseFragment(). It returns a DocumentFragment and doesn't add <html>, <head> and <body>:

import 'package:html/parser.dart';

void main() {
  final fragment = parseFragment('<b>bold</b> and <i>italic</i>');
  print(fragment.children.map((e) => e.localName).toList()); // [b, i]
  print(fragment.text); // bold and italic
}

Reporting parse errors

By default, errors are recovered silently. To see them, create an HtmlParser and inspect errors after parsing. Pass generateSpans: true to get line and column information. To reject invalid input instead, pass strict: true, which throws a ParseError on the first problem:

import 'package:html/parser.dart';

void main() {
  const input = '<p>One<p>Two</div><b>x';

  final parser = HtmlParser(input, generateSpans: true, sourceUrl: 'input.html');
  final document = parser.parse();
  print(document.body!.innerHtml); // <p>One</p><p>Two<b>x</b></p>

  for (final error in parser.errors) {
    final line = error.span!.start.line + 1; // 0-based
    print('line $line: ${error.message}');
  }
  // line 1: Unexpected start tag (p). Expected DOCTYPE.
  // line 1: End tag (div) seen too early. Expected other end tag.
  // line 1: Expected closing tag. Unexpected end of file.

  try {
    HtmlParser(input, strict: true).parse();
  } on ParseError catch (e) {
    print('Rejected: ${e.message}');
  }
}

Tips

Feedback about page:

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



Table Of Contents