Get full html div text

1,573

Solution 1

The https://pub.dartlang.org/packages/html package allows you to query elements similar to what you can do in the browser (for example querySelectorAll()).

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

main() {
  var document = parse(
      '<body>Hello world! <a href="www.html5rocks.com">HTML5 rocks!');
  print(document.outerHtml);
}

Solution 2

We are writing at the same time me and Gunter ^^

As Gunter pointed out you can use the Dart package html.

In your pubspec.yaml you sould import it:

html: ^0.13.3+3

Imports should look like that if you have errors in duplication of Text in dom.dart and widgets.dart.

import 'package:html/parser.dart' show parse;
import 'package:html/dom.dart' hide Text;

and then you can givin it a try like this:

void _printing() async {
    http.Response response =
        await http.get('https://stackoverflow.com/'); // example

    Document document = parse(response.body);

    var element = document.getElementById('content');

    debugPrint(element.querySelectorAll('div').toString());
  }

with querySelectorAll you get all selectors of the page:

enter image description here

And then you can loop through all of them:

element.querySelectorAll('div').forEach((value) {
      debugPrint(value.outerHtml);
    });
Share:
1,573
Fatima TT
Author by

Fatima TT

Updated on December 08, 2022

Comments

  • Fatima TT
    Fatima TT over 1 year

    I'm trying to parse an Html page and i need to get the full div:

    void printing() async {
       http.Response response = await http.get('https://stackoverflow.com/');// example
    
       Document document = parser.parse(response.body);
    
       var elent = document.getElementById('content') ;
    
       print(elent);
    
    }
    

    the result is:

    I/flutter ( 2336): <html div>
    

    how can i print all html elements inside div ?

    thank you.

  • Fatima TT
    Fatima TT over 5 years
    Thank you 'outerHtml' is the one i'm looking for
  • Fatima TT
    Fatima TT over 5 years
    debugPrint(element.outerHtml);
  • shadowsheep
    shadowsheep over 5 years
    @FatimaTiwTiwSubscribe Said that becouse you have written "how can i print all div elements ?". I've misunderstood it. Did you mean all elements inside the outer div one? Anyway hope you have found it helpful, also for the imports section highlight. And if you need to loop or have a more deep query on selectors you need to use querySelectorAll.
  • shadowsheep
    shadowsheep over 5 years
    Doesn't mind. You're welcome ;-]. No hard feelings for that of course. Enjoy coding!