textParser function
Extracts text content from HTML elements Returns Data object with text content or null if not found
Implementation
Data? textParser({
required Parser parser,
required Data parentData,
required Map<String, Object> allData,
required bool debug,
}) {
printLog("----------------------------------", debug, color: LogColor.yellow);
printLog("ID: ${parser.id} Parser: Text", debug, color: LogColor.cyan);
// Get parent element(s) to search within
List<Element>? element = getElementObject(parentData);
if (element == null || element.isEmpty) {
printLog(
"Text Parser: Element not found!",
debug,
color: LogColor.red,
);
return null;
}
// Handle single element (multiple elements not supported)
Element document;
if (element.length == 1) {
document = element[0];
} else {
throw UnimplementedError("Multiple elements not supported");
}
// Try each selector until text is found
for (final sel in parser.selectors) {
if (sel == '_self') {
return Data(parentData.url, document.text);
}
printLog("Text Selector: $sel", debug, color: LogColor.cyan);
String selector;
// Handle dynamic selectors with slot injection
if (sel.contains("<slot>")) {
selector = inject("slot", allData, sel);
printLog(
"Text Selector Modified: $selector",
debug,
color: LogColor.green,
);
} else {
selector = sel;
}
// Extract text using the handler
Object? data = textHandler(parser, document, selectr: selector);
if (data != null && data != [] && data != "") {
return Data(parentData.url, data);
}
}
printLog(
"Text Parser: No data found!",
debug,
color: LogColor.orange,
);
return null;
}