How to scrape data based on class tag and attribute name in Dart/Flutter

Issue

I tried to find the alternative way to scrape data in this html. The value I tried to get is the ‘e4s1’ value.

<section class="row btn-row">
        <input type="hidden" name="execution" value="e4s1"/>

Basically I have found a way to get this value using the following code. But this is dependent on the tag location in the html code. Which in this case at ‘input'[2].

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

.....
Future getLoginAuth() async {
    var response = await http.get(Uri.parse(url), headers: header);

    if (response.statusCode == 200) {
      dom.Document document = parse(response.body);
      final elements =
          document.getElementsByTagName('input')[2].attributes['value'];
      print(elements);
    }
......

So, is there a way to find the value ‘e4s1’ using tag and also the name attribute? For example, using tag:input and attribute: name=’execution’. I am trying to find a way to do this in Dart like using BeautifulSoup package in python as shown in the code below:

soup.find('input', attrs={'name':'execution'})['value']

Solution

You can parse the HTML using the xml package. Something like this:

final html = 
'''<section class="row btn-row">
        <input type="hidden" name="execution" value="e4s1"/>
</section>''';

final document = XmlDocument.parse(html);
final inputs = document.findAllElements('input');

inputs.forEach((node) => print(node.attributes));

attributes is a list of all the attributes in the current node.

Answered By – user2233706

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

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