import re import time from selenium.webdriver.common.by import By # Procedure history on the DentaQuest member page, columns in this order: # Date of service | Procedure code | Procedure code description | Tooth / arch / quad / surface | Place of service # The column headers are rendered apart from the data rows, so rows are found by their # content (a date cell and a "D####" code cell) rather than by header names. The claims # table above has a date but no procedure code cell, so it is skipped. _ROWS_JS = """ const cellText = (el) => (el.innerText || el.textContent || '').replace(/\\s+/g, ' ').trim(); const out = []; for (const row of document.querySelectorAll('tr, [role="row"]')) { let cells = Array.from(row.querySelectorAll('td, th, [role="cell"], [role="gridcell"]')); if (cells.length === 0) cells = Array.from(row.children); const texts = cells.map(cellText); if (texts.some(t => /^D\\d{4}$/.test(t))) out.push(texts); } return out; """ _DATE_RE = re.compile(r"^\d{1,2}/\d{1,2}/\d{4}$") _CODE_RE = re.compile(r"^D\d{4}$") # Fallback for one line of page text, e.g. # 02/12/2026 D0220 intraoral - periapical first radiographic image 27 / -- / -- / -- Office _LINE_RE = re.compile( r"^(\d{1,2}/\d{1,2}/\d{4})\s+(D\d{4})\s+(.+?)\s+(\S+\s*/\s*\S+\s*/\s*\S+\s*/\s*\S+)\s+(\S.*)$" ) def parse_row_cells(rows): """Map row cell texts to service history dicts.""" result = [] for cells in rows: code_i = next((i for i, c in enumerate(cells) if _CODE_RE.match(c)), None) if code_i is None: continue date = next((c for c in cells if _DATE_RE.match(c)), "") rest = cells[code_i + 1:] + ["", "", ""] result.append({ "procedureCode": cells[code_i], "description": rest[0], "toothQuadArchSurface": rest[1], "placeOfService": rest[2], "serviceDate": date, }) return result def parse_page_text(text): """Service history rows from the page's text, one row per line.""" result = [] for line in text.splitlines(): line = re.sub(r"\s+", " ", line).strip() m = _LINE_RE.match(line) if m: result.append({ "procedureCode": m.group(2), "description": m.group(3), "toothQuadArchSurface": m.group(4), "placeOfService": m.group(5), "serviceDate": m.group(1), }) return result def extract_service_history(driver, timeout=10): """Read the procedure history from the DentaQuest member details page. Returns [] when nothing was found — this can't tell "no history" from "the page was too slow", so callers must not treat it as "no history". """ deadline = time.time() + timeout history = [] while True: try: history = parse_row_cells(driver.execute_script(_ROWS_JS) or []) if not history: text = driver.find_element(By.TAG_NAME, "body").get_attribute("innerText") or "" history = parse_page_text(text) if history: break except Exception as e: print(f"[dentaquest extract_service_history] reading page failed: {e}") if time.time() >= deadline: break time.sleep(1) print(f"[dentaquest extract_service_history] {len(history)} row(s)") return history