76 lines
3.0 KiB
Python
76 lines
3.0 KiB
Python
import time
|
|
|
|
# Service history table: header cells plus the cell texts of every row.
|
|
# innerText (not .text) so cells rendered off-screen still return their text.
|
|
_TABLE_JS = """
|
|
for (const table of document.querySelectorAll('table')) {
|
|
const headers = Array.from(table.querySelectorAll('thead th, thead td'))
|
|
.map(th => (th.innerText || th.textContent || '').toLowerCase().replace(/[^a-z]/g, ''));
|
|
if (!headers.some(h => h.includes('procedurecode')) || !headers.some(h => h.includes('servicedate'))) continue;
|
|
const rows = Array.from(table.querySelectorAll('tbody tr'))
|
|
.map(tr => Array.from(tr.querySelectorAll('td'))
|
|
.map(td => (td.innerText || td.textContent || '').replace(/\\s+/g, ' ').trim()));
|
|
return {headers, rows, paged: !!document.querySelector('.pagination, [class*="paginat"]')};
|
|
}
|
|
return null;
|
|
"""
|
|
|
|
|
|
def _column_indexes(headers):
|
|
def find(match):
|
|
return next((i for i, h in enumerate(headers) if match(h)), None)
|
|
|
|
return {
|
|
"procedureCode": find(lambda h: "procedurecode" in h and "description" not in h),
|
|
"description": find(lambda h: "description" in h),
|
|
"toothQuadArchSurface": find(lambda h: "tooth" in h),
|
|
"placeOfService": find(lambda h: "placeofservice" in h),
|
|
"serviceDate": find(lambda h: "servicedate" in h),
|
|
}
|
|
|
|
|
|
def parse_service_history(headers, rows):
|
|
"""Map raw table cells to row dicts, dropping placeholder rows (e.g. a
|
|
single "no records" cell) and rows without a procedure code."""
|
|
columns = _column_indexes(headers)
|
|
result = []
|
|
for cells in rows:
|
|
if len(cells) < len(headers):
|
|
continue
|
|
row = {
|
|
key: cells[i] if i is not None and i < len(cells) else ""
|
|
for key, i in columns.items()
|
|
}
|
|
if row["procedureCode"]:
|
|
result.append(row)
|
|
return result
|
|
|
|
|
|
def extract_service_history(driver, timeout=15):
|
|
"""Read the MassHealth Service History table.
|
|
|
|
AngularJS adds the rows after the page loads, so keep polling until every
|
|
row has its procedure code. A member with no history waits the full
|
|
timeout. 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:
|
|
table = driver.execute_script(_TABLE_JS)
|
|
if table:
|
|
history = parse_service_history(table["headers"], table["rows"])
|
|
if history and len(history) == len(table["rows"]):
|
|
if table["paged"]:
|
|
print("[extract_service_history] pagination found — only the current page was read")
|
|
break
|
|
except Exception as e:
|
|
print(f"[extract_service_history] reading table failed: {e}")
|
|
if time.time() >= deadline:
|
|
break
|
|
time.sleep(1)
|
|
|
|
print(f"[extract_service_history] {len(history)} row(s)")
|
|
return history
|