# -*- coding: utf-8 -*- """ 信息价 / 市场价 HTML 解析器 文件形态:带脚本的 HTML,数据藏在 `const DATA = [...]` 里 结构:DATA = [ {name, columns, sections:[{title, subsections, rows:[...]}]}, ... ] 每个顶层对象 = 一个「块」(如 建材综合价 / 园林苗木 / 横琴 / 万山) 行字段(8 列):材料编码 / 材料名称 / 规格型号 / 单位 / 不含税单价 / 税率 / 含税单价 / 备注 **两个口径(2026-09-28 你定的)**: 1. 目录(Class)= 分类标题,**原封不动**,含序号("一、黑色及有色金属")。不剥"一、"。 2. **一个块 = 一个批次**(2026-10-06 改,原来是「一个文件 = 一个批次」)。 一个 HTML 常含多个市场(建材 / 苗木 / 横琴 / 万山),期次各不相同; 挤进一个批次 → 批次只能有一个期次 → 只能留空 → ym2str('') 抛错 → 信息价列表整页 500。 拆块之后每个批次有自己的期次(块名里认得出就用块自己的,认不出才用导入弹框填的)。 """ import io, os, re, json # 解析器版本(与 import_job.PARSER_VER 同机制,见那里的说明):改了入库口径才升号 # ⚠️ 2026-10-12 价格重设计:只收标准模板 Excel(HTML 导入退役),与 price_xlsx.PARSER_VER 同步升号 PARSER_VER = "2026.10.12-1" # 路径由本文件位置推导(换台电脑直接能跑,不写死绝对路径) _PRJ = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # .../造价审核 def _num(v): if v is None: return None s = str(v).strip().replace(",", "") if not s: return None try: return float(s) except Exception: return None def clean_title(t): """分类标题:**原封不动**(你 2026-09-28 定:'一、黑色及有色金属' 就存 '一、黑色及有色金属')。 只做去首尾空白,不剥序号、不改一个字——目录要跟 HTML 原件对得上。""" return (t or "").strip() # --------------------------------------------------------------------------- # 期次识别(2026-10-06) # --------------------------------------------------------------------------- # 一个价格文件里往往装着**好几个市场**,而且期次各不相同: # 珠海市建材设备市场综合价 → 2026年7月 → 24319 # 珠海市2026年4-6月园林苗木市场信息 → 2026年4~6月 → 24316~24318 # 以前「一个文件 = 一个批次」,批次只能有一个期次,于是只能填空串 —— 这就是 # DB-1(ym2str('') 抛 ValueError → 信息价列表整页 500)的根因。 # 现在一个块 = 一个批次,块名里能认出期次就用块自己的,认不出才回退到导入弹框填的值。 _M_RANGE = re.compile(r"(20\d{2})\s*年\s*(\d{1,2})\s*[~\-—-~至到]\s*(\d{1,2})\s*月") # 跨年:2026年11月~2027年1月(两段各带年份) _M_RANGE_Y = re.compile(r"(20\d{2})\s*年\s*(\d{1,2})\s*月\s*[~\-—-~至到]\s*(20\d{2})\s*年\s*(\d{1,2})\s*月") _M_ONE = re.compile(r"(20\d{2})\s*年\s*(\d{1,2})\s*月") def guess_period(text): """从块名 / sheet 名 / 文件名里认期次。 返回 (start_m, end_m),单位是「月序号」= 年*12+月(与 batches.x_period_*_m 同口径)。 认不出返回 (None, None) —— 调用方再依次回退到「文件名里认的」和「导入弹框填的」。 """ s = str(text or "") m = _M_RANGE_Y.search(s) if m: y1, m1, y2, m2 = (int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))) if 1 <= m1 <= 12 and 1 <= m2 <= 12: a, b = y1 * 12 + m1, y2 * 12 + m2 return (min(a, b), max(a, b)) m = _M_RANGE.search(s) if m: y, a, b = int(m.group(1)), int(m.group(2)), int(m.group(3)) if 1 <= a <= 12 and 1 <= b <= 12: lo, hi = min(a, b), max(a, b) return (y * 12 + lo, y * 12 + hi) m = _M_ONE.search(s) if m: y, a = int(m.group(1)), int(m.group(2)) if 1 <= a <= 12: v = y * 12 + a return (v, v) return (None, None) def parse(path): """返回 [{block, columns, n_sections, rows:[(sec_title, [8列])]}]""" raw = io.open(path, encoding="utf-8", errors="replace").read() key = "const DATA" if key not in raw: raise ValueError("这个文件里没有 DATA 数据块,不是信息价/市场价 HTML") j = raw[raw.index(key) + len(key):].lstrip() j = j[j.index("=") + 1:] data, _ = json.JSONDecoder().raw_decode(j.lstrip()) out = [] for blk in data: rows = [] for sec in blk.get("sections", []): title = clean_title(sec.get("title", "")) for r in sec.get("rows", []): if len(r) < 8: r = list(r) + [""] * (8 - len(r)) rows.append((title, r[:8])) nm = blk.get("name", "") or "" ps, pe = guess_period(nm) # 2026-10-06:块自带期次,供「一个块 = 一个批次」用 out.append({ "block": nm, "columns": blk.get("columns", []), "n_sections": len(blk.get("sections", [])), "rows": rows, "period_start_m": ps, "period_end_m": pe, }) return out def to_records(blocks): """把解析结果转成入库记录:材料编码/名称/规格/单位/不含税单价/税率/含税单价/目录/备注""" recs = [] for b in blocks: blk = (b.get("block") or "").strip() for sec_title, r in b["rows"]: name = (r[1] or "").strip() if not name: continue recs.append({ "Code": (r[0] or "").strip(), "Name": name, "Specification": (r[2] or "").strip(), "Unit": (r[3] or "").strip(), "NoTaxPrice": _num(r[4]), "TaxRate": _num(r[5]), "TaxPrice": _num(r[6]), "Class": sec_title or blk, "Note": (r[7] or "").strip(), "Block": blk, # 块名(三级目录:根=批次 → 块 → 分类) }) return recs if __name__ == "__main__": import sys _sample = os.path.join(os.path.dirname(_PRJ), "珠海信息价_2026年7月.html") p = sys.argv[1] if len(sys.argv) > 1 else (_sample if os.path.exists(_sample) else "") blocks = parse(p) tot = 0 for b in blocks: print("块:%s 分类数=%d 行数=%d" % (b["block"], b["n_sections"], len(b["rows"]))) tot += len(b["rows"]) print("总行数:", tot) recs = to_records(blocks) print("样例:", recs[0]) print("样例:", recs[200] if len(recs) > 200 else "")