"""Plan name, remaining annual benefit and phone from the MassHealth Dental (providers.masshealth-dental.org) member details page.""" import re import time from selenium.webdriver.common.by import By # "Plan:" (not "Plan/Group number:" or "Plan year:"); value on the same line or the next _PLAN_RE = re.compile(r"^[ \t]*Plan:[ \t]*(?:\n[ \t]*)?([^\n\t]+)", re.M) # "$1,638.00 before Individual annual maximum (All Networks) is met" _REMAINING_RE = re.compile(r"(\$\s?[\d,]+(?:\.\d{2})?)\s*before\s+[^\n]*?maximum", re.I) # Coverage status in the "Employee & family information" table (the member's own row) _FAMILY_SECTION_RE = re.compile(r"Employee\s*&\s*family information(.*?)(?:Dental plan information|$)", re.S | re.I) _PHONE_RE = re.compile(r"Phone number:\s*\(?(\d{3})\)?[\s.-]*(\d{3})[\s.-]*(\d{4})") def parse_mh_plan_details(text): result = {} m = _PLAN_RE.search(text or "") if m and m.group(1).strip(): result["planName"] = m.group(1).strip() m = _REMAINING_RE.search(text or "") if m: result["remainingBenefit"] = re.sub(r"\s", "", m.group(1)) sec = _FAMILY_SECTION_RE.search(text or "") if sec: # Case-sensitive whole word, so "Inactive" never counts as "Active" if re.search(r"\bActive\b", sec.group(1)): result["coverageStatus"] = "active" elif re.search(r"\b(Inactive|Terminated)\b", sec.group(1)): result["coverageStatus"] = "inactive" m = _PHONE_RE.search(text or "") if m: result["phone"] = "-".join(m.groups()) return result def extract_mh_plan_details(driver, timeout=10): """Poll because "Deductibles & maximums" fills in after the rest of the page.""" result = {} try: deadline = time.time() + timeout while True: text = driver.find_element(By.TAG_NAME, "body").get_attribute("innerText") or "" result = parse_mh_plan_details(text) if ("planName" in result and "remainingBenefit" in result) or time.time() >= deadline: break time.sleep(1) print(f"[extract_mh_plan_details] {result}") except Exception as e: print(f"[extract_mh_plan_details] failed: {e}") return result