Parse the html tree into a string text
(dom_tree: DOMTree)
| 356 | |
| 357 | @staticmethod |
| 358 | def parse_my_html(dom_tree: DOMTree) -> tuple[str, str, dict[str, Any], Any]: |
| 359 | """Parse the html tree into a string text""" |
| 360 | |
| 361 | obs_nodes_info = {} |
| 362 | nodeid_to_cursor = { |
| 363 | node["nodeId"]: idx for idx, node in enumerate(dom_tree) |
| 364 | } |
| 365 | |
| 366 | def dfs(node_cursor: int, depth: int) -> tuple[str, list[str]]: |
| 367 | tree_str, labeled_elems = '', [] |
| 368 | node = dom_tree[node_cursor] |
| 369 | valid_node = True |
| 370 | pure_text = False |
| 371 | try: |
| 372 | if node['nodeName'] == '#text': |
| 373 | node['nodeName'] = 'text' |
| 374 | |
| 375 | node_str = f"<{node['nodeName']}" |
| 376 | if node["attributes"]: |
| 377 | node_str += f" {node['attributes']}" |
| 378 | node_str += f" backend-id=\"bid-{node['backendNodeId']}\"> {node['nodeValue']}" |
| 379 | |
| 380 | # if node['nodeName'] == '#text': |
| 381 | # pure_text = True |
| 382 | # node_str = node['nodeValue'] |
| 383 | |
| 384 | valid_node = bool(node["attributes"] or node["nodeValue"] or pure_text) |
| 385 | |
| 386 | if valid_node: |
| 387 | node_html = lxml.html.fromstring(node_str) |
| 388 | label = node_html.attrib.get('data-testid', '') |
| 389 | if len(label) > 0: |
| 390 | labeled_elems.append(node["backendNodeId"]) |
| 391 | obs_nodes_info[str(node_cursor)] = { |
| 392 | "backend_id": node["backendNodeId"], |
| 393 | "union_bound": node["union_bound"], |
| 394 | "text": node['nodeValue'], |
| 395 | "label": label, |
| 396 | } |
| 397 | tree_str += f"{node_str}" |
| 398 | |
| 399 | except Exception as e: |
| 400 | valid_node = False |
| 401 | |
| 402 | for child_ids in node["childIds"]: |
| 403 | child_cursor = nodeid_to_cursor[child_ids] |
| 404 | child_depth = depth + 1 if valid_node else depth |
| 405 | child_str, elems = dfs(child_cursor, child_depth) |
| 406 | tree_str += child_str |
| 407 | labeled_elems.extend(elems) |
| 408 | |
| 409 | if valid_node and not pure_text: |
| 410 | tree_str += f"</{node['nodeName']}>" |
| 411 | |
| 412 | return tree_str, labeled_elems |
| 413 | |
| 414 | html, labeled_elems = dfs(0, 0) |
| 415 |
no test coverage detected