getElementAttribute method

List<String?> getElementAttribute(
  1. String address,
  2. String attrib
)

Returns List of elements' attributes found at specified address respecting the provided attribute requirement.

Example address: "div.item > a.title" where item and title are class names of div and a tag respectively. For ease of access, when using Chrome inspection tool, right click the item you want to copy, then click "Inspect" and at the console, right click the highlighted item, right click and then click "Copy > Copy selector" and provide as String parameter to this method. Attributes are the bits of information between the HTML tags. For example in

The element would be "div.strong.and.bold" and the possible attributes to fetch would be EIHER "style" OR "title" returning with EITHER of the values "width: 100%;" OR "Fierce!" respectively. To retrieve multiple attributes at once from a single element, please use getElement() instead.

Implementation

List<String?> getElementAttribute(String address, String attrib) {
  // Attribs are the list of attributes required to extract from the html tag(s) ex. ['href', 'title'].
  if (_document == null) {
    throw WebScraperException(
        'getElement cannot be called before loadWebPage');
  }
  // Using query selector to get a list of particular element.
  var elements = _document!.querySelectorAll(address);
  // ignore: omit_local_variable_types
  List<String?> elementData = [];

  for (var element in elements) {
    var attribData = <String, dynamic>{};
    attribData[attrib] = element.attributes[attrib];
    // Checks if the element's attribute is null before adding it to the list.
    if (attribData[attrib] != null) {
      elementData.add(attribData[attrib]);
    }
  }
  return elementData;
}