Flutter实现URL预览:如何提取网页H1标签文本内容
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:
- Access the specific element from the returned list (usually the first one for tags like
h1ortitle) - Use the
textproperty 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

