You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter实现URL预览:如何提取网页H1标签文本内容

Solution for Extracting Text from HTML Tags in Flutter

Hey there! I see exactly what's going on here—when you call getElementsByTagName('h1'), it returns a list of matching HTML elements, not the actual text inside those elements. That's why you're seeing [<html h1>] instead of the "HELLO WORLD!" you're after.

Here's how to fix this and get the text content you need:

Step-by-Step Fix

After parsing your HTML document, you need to:

  1. Access the specific element from the returned list (usually the first one for tags like h1 or title)
  2. Use the text property to extract the content inside the tag

Your corrected code would look like this:

var document = parse('''<!doctype html> <html lang="en"> <head> <title>Hello World!</title> </head> <body> <h1>HELLO WORLD!</h1> <p>PAGE HTML!</p> <img src="image.jpg"> </body> </html>''');

// Safely get the first h1 element (avoids errors if no h1 exists)
var h1Element = document.body.getElementsByTagName('h1').firstOrNull;
if (h1Element != null) {
  print("PRINT - " + h1Element.text); // This outputs: PRINT - HELLO WORLD!
} else {
  print("No h1 tag found on the page");
}

Bonus: Extract Other URL Preview Elements

Since you're building a URL preview, you'll probably need the page title and thumbnail image too. Here's how to grab those:

// Extract page title from the <title> tag
var titleElement = document.getElementsByTagName('title').firstOrNull;
String? pageTitle = titleElement?.text;

// Extract the first image's source URL
var imgElement = document.body.getElementsByTagName('img').firstOrNull;
String? thumbnailUrl = imgElement?.attributes['src'];

print("Page Title: $pageTitle"); // Output: Page Title: Hello World!
print("Thumbnail URL: $thumbnailUrl"); // Output: Thumbnail URL: image.jpg

A quick tip: Using firstOrNull (available in Dart 2.12+) is safer than first because it prevents crashes if the tag doesn't exist on the page you're parsing.

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:31:51