Parsing HTML in Dart and Generating a Future Image

Parsing HTML in Dart and Generating a Future Image

Working with HTML data is a common task when building web scrapers, data extractors, or even rendering logic in Flutter web apps. In this tutorial, you’ll learn how to parse HTML in Dart using CSS selectors with the html package, and then generate a “future image” — for example, a placeholder or a dynamically resolved image URL.

Prerequisites

  • Dart SDK installed (stable version recommended)

  • Familiarity with Dart syntax

  • Basic understanding of HTML and CSS selectors

You can try this either in a Dart CLI project or in a DartPad with internet access and package support.

Step 1: Add Dependencies

Add the following to your pubspec.yaml:

dependencies:
html: ^0.15.4
http: ^0.13.5

Step 2: Sample HTML Input

Let’s assume you’re working with the following HTML:

<html>
<body>
<div class="gallery">
<img src="https://example.com/image1.jpg" alt="First Image">
<img src="https://example.com/image2.jpg" alt="Second Image">
</div>
</body>
</html>

You want to extract all image URLs and perhaps transform them into preview URLs or placeholder links.

Step 3: Parse HTML in Dart

Here’s how to extract <img> tags and get their src attributes:

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

void main() {
final htmlContent = '''
<html>
<body>
<div class="gallery">
<img src="https://example.com/image1.jpg" alt="First Image">
<img src="https://example.com/image2.jpg" alt="Second Image">
</div>
</body>
</html>
''';

final document = html_parser.parse(htmlContent);
final images = document.querySelectorAll('div.gallery img');

for (var img in images) {
final src = img.attributes['src'];
print('Found image: $src');
}
}

This will output:

Found image: https://example.com/image1.jpg
Found image: https://example.com/image2.jpg

Step 4: Generate Future Image URLs

Now imagine you want to generate a “future image” link. For example, let’s say your server requires a signed URL or token to access images. You can simulate that like this:

Future<String> generateFutureImageUrl(String src) async {
// Simulate some async operation
await Future.delayed(Duration(milliseconds: 500));
final token = 'abc123'; // Imagine this is a real signed token
return '$src?token=$token';
}

Then modify the previous loop:

void main() async {
final document = html_parser.parse(htmlContent);
final images = document.querySelectorAll('div.gallery img');

for (var img in images) {
final src = img.attributes['src'];
if (src != null) {
final futureUrl = await generateFutureImageUrl(src);
print('Future image URL: $futureUrl');
}
}
}

Output:

Future image URL: https://example.com/image1.jpg?token=abc123
Future image URL: https://example.com/image2.jpg?token=abc123

Bonus: Download or Display Future Images

If you’re building a Flutter app, you could use these URLs to load images via Image.network(futureUrl).

If you’re working in a CLI or server environment, you could fetch and save the image using the http package:

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

Future<void> downloadImage(String url, String filename) async {
final response = await http.get(Uri.parse(url));
final file = File(filename);
await file.writeAsBytes(response.bodyBytes);
print('Saved $filename');
}

Conclusion

Parsing HTML in Dart using CSS selectors is straightforward with the html package. You can extract image sources and combine them with your custom logic — such as generating future URLs, adding access tokens, or downloading the files.

This is a powerful approach for writing custom tools, bots, Flutter scrapers, or backend services in Dart.

Useful Packages

  • html: HTML parsing

  • http: Network requests

  • path: For managing file paths

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *