"""从坐标 CSV 批量查询楼宇 WFS,汇总 properties 为 CSV。独立运行,无第三方依赖。""" import csv from decimal import Decimal, InvalidOperation import gzip from itertools import islice import json from pathlib import Path import tempfile import time from urllib.error import HTTPError, URLError from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit, quote from urllib.request import HTTPRedirectHandler, Request, build_opener import xml.etree.ElementTree as ET # 填完整 WFS URL(包含 ak、sig 等参数);原 CQL_FILTER 会自动替换。 # 请粘贴纯 URL,不含 curl、CMD 的 ^ 转义或 Markdown 链接外壳。 URL = "" # 填完整 Cookie 头内容,例如 CASTGC=...;不要加 Cookie: 前缀。 COOKIES = "" REFERER = "https://nqi.gmcc.net:20443/pro-problem-warehouse-web/" INPUT_CSV = Path(__file__).resolve().parent / "source" / "NRBuildingsPoint.csv" OUTPUT_CSV = Path(__file__).resolve().parent / "output" / "NRBuildingsData.csv" INPUT_ENCODING = "gb18030" # 当前源文件为 GBK;UTF-8 文件可改为 utf-8-sig。 OUTPUT_ENCODING = "utf-8-sig" # 带 BOM,方便 Excel 识别中文。 ID_COLUMN = "序号" LONGITUDE_COLUMN = "经度" LATITUDE_COLUMN = "维度" # 源文件实际写的是“维度”。 GEOMETRY_FIELD = "the_geom" START_ROW = 1 # 从第几条数据开始,不计表头。 LIMIT = 10 # 初次只查 10 条;确认结果后改成 None 处理剩余全部。 TIMEOUT = 30 # 每次请求超时秒数。 MAX_RETRIES = 2 # 网络异常、429 或 5xx 的重试次数;空结果不重试。 REQUEST_INTERVAL = 0.2 # 两个坐标之间的等待秒数。 PROGRESS_EVERY = 100 QUERY_COLUMNS = ["查询序号", "查询经度", "查询纬度", "查询状态", "命中数量", "要素ID", "错误信息"] class QueryError(Exception): pass class AuthenticationError(QueryError): pass class NoRedirect(HTTPRedirectHandler): def redirect_request(self, request, file_pointer, code, message, headers, new_url): return None def coordinate(value, lower, upper): try: number = Decimal(str(value).strip()) except InvalidOperation: raise ValueError("经纬度不是有效数字") from None if not number.is_finite() or not lower <= number <= upper: raise ValueError("经纬度超出有效范围") return format(number, "f") def query_url(longitude, latitude): parts = urlsplit(URL.strip()) params = [(key, value) for key, value in parse_qsl(parts.query, keep_blank_values=True) if key.upper() != "CQL_FILTER"] params.append(("CQL_FILTER", f"INTERSECTS({GEOMETRY_FIELD},SRID=4326;POINT({longitude} {latitude}))")) return urlunsplit((parts.scheme, parts.netloc, parts.path, urlencode(params, quote_via=quote), "")) def fetch_features(opener, longitude, latitude): request = Request(query_url(longitude, latitude), headers={ "Cookie": COOKIES.strip(), "Referer": REFERER, "Accept": "application/json", "Accept-Encoding": "gzip", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Firefox/155.0", }) for attempt in range(MAX_RETRIES + 1): try: with opener.open(request, timeout=TIMEOUT) as response: content = response.read() if response.headers.get("Content-Encoding", "").lower() == "gzip": content = gzip.decompress(content) break except HTTPError as exc: status = exc.code exc.close() if status in (301, 302, 303, 307, 308, 401, 403): raise AuthenticationError(f"HTTP {status},请检查 URL、Cookies 或登录是否过期") from None if attempt < MAX_RETRIES and (status == 429 or status >= 500): time.sleep(attempt + 1) continue raise QueryError(f"HTTP {status}") from None except (URLError, TimeoutError, OSError): if attempt < MAX_RETRIES: time.sleep(attempt + 1) continue raise QueryError("网络连接失败或超时,请检查网络、证书及服务状态") from None try: payload = json.loads(content) except (ValueError, UnicodeError): try: xml = ET.fromstring(content) if any(element.tag.split("}")[-1] == "ExceptionText" for element in xml.iter()): raise QueryError("服务返回 WFS 异常,请检查 URL 中的图层参数和 CQL 配置") except ET.ParseError: pass raise AuthenticationError("服务返回非 JSON 页面,请检查 Cookies 或登录状态") from None if not isinstance(payload, dict) or payload.get("type") != "FeatureCollection": if isinstance(payload, dict) and str(payload.get("code")) in ("401", "403"): raise AuthenticationError("服务提示认证失败,请更新 Cookies") raise QueryError("响应不是有效的 FeatureCollection") features = payload.get("features") if not isinstance(features, list) or not all( isinstance(feature, dict) and isinstance(feature.get("properties"), dict) for feature in features ): raise QueryError("响应缺少有效的 features/properties") total = payload.get("numberMatched", payload.get("totalFeatures")) if str(total).isdigit() and int(total) > len(features): raise QueryError("单个坐标的结果被截断,请提高 URL 的 maxFeatures 后重查") return features def csv_value(value): if isinstance(value, (dict, list)): return json.dumps(value, ensure_ascii=False, separators=(",", ":")) return value def main(): parts = urlsplit(URL.strip()) if parts.scheme not in ("http", "https") or not parts.netloc or not COOKIES.strip(): raise ValueError("请先在脚本顶部填写完整 URL 和 COOKIES") if START_ROW < 1 or (LIMIT is not None and LIMIT < 1): raise ValueError("START_ROW、LIMIT 必须大于 0;LIMIT 可设为 None") if TIMEOUT <= 0 or MAX_RETRIES < 0 or REQUEST_INTERVAL < 0 or PROGRESS_EVERY < 1: raise ValueError("超时和进度间隔须大于0,重试次数和请求间隔须非负") input_path, output_path = Path(INPUT_CSV), Path(OUTPUT_CSV) if input_path.resolve() == output_path.resolve(): raise ValueError("输出文件不能覆盖输入坐标文件") output_path.parent.mkdir(parents=True, exist_ok=True) opener = build_opener(NoRedirect()) property_fields = [] property_seen = set() counts = {"查询坐标": 0, "命中坐标": 0, "未命中坐标": 0, "失败坐标": 0, "楼宇结果行": 0} interrupted = False stop_reason = "" with input_path.open("r", encoding=INPUT_ENCODING, newline="") as source, \ tempfile.TemporaryFile(mode="w+", encoding="utf-8", newline="") as spool: reader = csv.DictReader(source) required = {ID_COLUMN, LONGITUDE_COLUMN, LATITUDE_COLUMN} if not required.issubset(reader.fieldnames or []): raise ValueError(f"输入 CSV 必须包含列:{', '.join(sorted(required))}") selected = islice(reader, START_ROW - 1, None if LIMIT is None else START_ROW - 1 + LIMIT) try: for point in selected: metadata = {"查询序号": point.get(ID_COLUMN), "查询经度": point.get(LONGITUDE_COLUMN), "查询纬度": point.get(LATITUDE_COLUMN), "命中数量": 0, "要素ID": "", "错误信息": ""} features = [] try: lon = coordinate(point.get(LONGITUDE_COLUMN), -180, 180) lat = coordinate(point.get(LATITUDE_COLUMN), -90, 90) features = fetch_features(opener, lon, lat) metadata["查询状态"] = "成功" if features else "未命中" metadata["命中数量"] = len(features) counts["命中坐标" if features else "未命中坐标"] += 1 except ValueError as exc: metadata.update(查询状态="坐标无效", 错误信息=str(exc)) counts["失败坐标"] += 1 except QueryError as exc: metadata.update(查询状态="请求失败", 错误信息=str(exc)) counts["失败坐标"] += 1 if isinstance(exc, AuthenticationError): stop_reason = str(exc) counts["查询坐标"] += 1 if features: for feature in features: properties = feature["properties"] for key in properties: if key in QUERY_COLUMNS: raise ValueError(f"properties 字段 {key} 与查询信息列重名,请调整 QUERY_COLUMNS") if key not in property_seen: property_seen.add(key) property_fields.append(key) row = {**metadata, "要素ID": feature.get("id", ""), **properties} spool.write(json.dumps(row, ensure_ascii=False) + "\n") counts["楼宇结果行"] += 1 else: spool.write(json.dumps(metadata, ensure_ascii=False) + "\n") if counts["查询坐标"] == 1 or counts["查询坐标"] % PROGRESS_EVERY == 0 or stop_reason: print(f"已查询 {counts['查询坐标']} 个坐标,命中 {counts['命中坐标']},未命中 {counts['未命中坐标']},失败 {counts['失败坐标']}", flush=True) if stop_reason: break if REQUEST_INTERVAL: time.sleep(REQUEST_INTERVAL) except KeyboardInterrupt: interrupted = True finally: # 先收集所有 properties 字段,再流式生成统一表头,避免全量结果驻留内存。 spool.seek(0) with output_path.open("w", encoding=OUTPUT_ENCODING, newline="") as destination: writer = csv.DictWriter(destination, fieldnames=QUERY_COLUMNS + property_fields) writer.writeheader() for line in spool: writer.writerow({key: csv_value(value) for key, value in json.loads(line).items()}) print(";".join(f"{key}:{value}" for key, value in counts.items())) print(f"输出:{output_path}") if interrupted: print("用户中断,已保存完成的查询结果。") if stop_reason: print(f"已停止后续请求:{stop_reason}") return 1 if interrupted or stop_reason or counts["失败坐标"] else 0 if __name__ == "__main__": try: raise SystemExit(main()) except (OSError, ValueError) as error: print(f"运行失败:{error}") raise SystemExit(1)