This commit is contained in:
upload
2026-11-11 22:25:40 +08:00
commit d87848d502
325 changed files with 3894 additions and 0 deletions
+452
View File
@@ -0,0 +1,452 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
"""拼好饭店铺详情。按本目录 拼好饭目标店铺.xlsx 逐家请求。
mtgsig 调上一级 AI代码 的 H5guard.sign(127.0.0.1:18092)。
先跑:AI代码/启动出签服务.py
每家原始 JSON 写到 原始/{shopId}__{poi_id_str}.json。403 网页不落盘。
本目录 原始 和上两级 app 的 原始 里已有 JSON 的店都跳过。
请求体和 Cookie 用 pinhaofan_item_hd 里 is_ok 为空的抓包,只换 poi_id_str 和 req_time。
一家连续 418/403 就把这条抓包的 is_ok 写成这个状态码,这条线程停,店放回队列给别的包。
写出 JSON 的请求给这条包 req_count(历史)和 current_count(今日,跨天从 1 重计)各加 1。
一个包一个线程。抓包地址里的城市名和 tent1.proxs_list.city 一致,请求走该城市代理。出签仍直连本机。
"""
import json
import queue
import re
import sys
import threading
import time
from pathlib import Path
from urllib.parse import unquote
import requests
import urllib3
from openpyxl import load_workbook
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# ==================== 运行参数(改这里) ====================
TIMEOUT = 30
TASK_FILE = '拼好饭目标店铺.xlsx'
OUT_DIR = '原始'
SLEEP_SEC = 1.2
SKIP_DONE = True
LIMIT = 0 # 0 = 表里全部
RETRY = 3
BACKOFF_SEC = (1, 2, 3)
STOP_AFTER_403 = 5
PACKET_ID = 0 # 单包:0 = 第一条未用抓包,否则填 pinhaofan_item_hd.id
# ============================================================
HERE = Path(__file__).resolve().parent
APP_OUT = HERE.parents[1] / '原始'
DONE_DIRS = (HERE / OUT_DIR, APP_OUT)
AI_DIR = HERE.parent / 'AI代码'
sys.path.insert(0, str(AI_DIR))
from 小程序mtgsig import check_health, get_h5_mtgsig_pure # noqa: E402
import newsetting as ten
tent = ten.All_Setting(host='192.168.5.2', port=3307, db='headers_project')
tent1 = ten.All_Setting(host='192.168.5.2', port=3307, db='project_proxy')
sql = f'''
select * from pinhaofan_item_hd
where is_ok is null
'''
rt = tent.get_shoppingmalls(sql)
def parse_prox(prox_data, ip_address, port, acount, pwd):
if isinstance(prox_data, str) and prox_data.strip():
try:
prox_data = json.loads(prox_data)
except json.JSONDecodeError:
prox_data = None
if isinstance(prox_data, dict) and (prox_data.get('http') or prox_data.get('https')):
http = prox_data.get('http') or prox_data.get('https')
https = prox_data.get('https') or prox_data.get('http')
return {'http': http, 'https': https}
if ip_address and port:
auth = f'{acount}:{pwd}@' if acount else ''
url = f'http://{auth}{ip_address}:{port}'
return {'http': url, 'https': url}
return None
def load_proxs():
rows = tent1.get_shoppingmalls(
'select city, prox_data, ip_address, port, acount, pwd from proxs_list'
)
proxs = {}
for row in rows or []:
city = str(row[0]).strip() if row[0] else ''
prox = parse_prox(row[1], row[2], row[3], row[4], row[5])
if city and prox:
proxs[city] = prox
return proxs
def proxy_host(prox) -> str:
if not prox:
return '直连'
raw = str(prox.get('http') or prox.get('https') or '')
if '@' in raw:
raw = raw.split('@', 1)[-1]
return raw.replace('http://', '').replace('https://', '')
def match_city(addr, proxs) -> str:
name = unquote(str(addr or ''))
hits = [city for city in proxs if city and city in name]
if not hits:
return ''
return max(hits, key=len)
PROXS = load_proxs()
print(f'[ok] proxs_list {len(PROXS)} 城')
def load_packets(rows):
packets = []
for row in rows:
hd_id = row[0]
raw = row[3]
if not raw:
continue
try:
packed = json.loads(raw)
url, headers, data = packed
except (json.JSONDecodeError, TypeError, ValueError):
print(f'[err] id={hd_id} json_data 解析失败')
continue
if not isinstance(headers, dict) or not isinstance(data, dict):
print(f'[err] id={hd_id} json_data 不是 url/headers/body')
continue
headers = dict(headers)
for key in ('Host', 'Connection', 'Content-Length'):
headers.pop(key, None)
mtgsig = headers.pop('mtgsig', '') or ''
city = match_city(data.get('loc_addr_name'), PROXS)
proxies = PROXS.get(city)
print(f'[ok] 抓包 id={hd_id} 城市={city or "未匹配"} 代理={proxy_host(proxies)}')
packets.append({
'id': hd_id,
'url': url,
'headers': headers,
'body': dict(data),
'mtgsig': mtgsig,
'poi': str(data.get('poi_id_str') or ''),
'city': city,
'proxies': proxies,
})
return packets
PACKETS = load_packets(rt)
print(f'[ok] pinhaofan_item_hd 未用抓包 {len(PACKETS)} 条')
def bump_packet(hd_id):
tent.write_data_one(
'''
update pinhaofan_item_hd
set req_count = coalesce(req_count, 0) + 1,
current_count = if(
date(updated_at) = curdate(),
coalesce(current_count, 0) + 1,
1
)
where id = %s
''',
(hd_id,),
)
print(f'[db] pinhaofan_item_hd id={hd_id} req_count+1 current_count 今日+1')
def mark_packet(hd_id, is_ok):
tent.write_data_one(
'update pinhaofan_item_hd set is_ok=%s where id=%s',
(is_ok, hd_id),
)
print(f'[db] pinhaofan_item_hd id={hd_id} is_ok={is_ok}')
_io_lock = threading.Lock()
def _cell(row: tuple, index: dict[str, int], name: str) -> str:
value = row[index[name]]
if value is None:
return ''
return str(value).strip()
def load_tasks() -> list[dict[str, str]]:
path = HERE / TASK_FILE
wb = load_workbook(path, data_only=True, read_only=True)
ws = wb.active
rows = ws.iter_rows(values_only=True)
header = [str(cell).strip() if cell is not None else '' for cell in next(rows)]
index = {name: pos for pos, name in enumerate(header)}
need = ('shopId', 'org_name', 'poi_id_str')
missing = [name for name in need if name not in index]
if missing:
raise RuntimeError(f'{path.name} 缺列: {missing}')
tasks = []
seen = set()
for row in rows:
poi_id_str = _cell(row, index, 'poi_id_str')
shop_id = _cell(row, index, 'shopId')
if not poi_id_str:
continue
key = (shop_id, poi_id_str)
if key in seen:
continue
seen.add(key)
tasks.append({
'shop_id': shop_id,
'org_name': _cell(row, index, 'org_name'),
'poi_id_str': poi_id_str,
})
wb.close()
return tasks
def result_name(task: dict[str, str]) -> str:
poi = re.sub(r'[\\/:*?"<>|]', '_', task['poi_id_str'])
shop_id = task['shop_id'] or 'noid'
return f'{shop_id}__{poi}.json'
def raw_path(task: dict[str, str]) -> Path:
return HERE / OUT_DIR / result_name(task)
def done_path(task: dict[str, str]) -> Path | None:
name = result_name(task)
for folder in DONE_DIRS:
path = folder / name
if _saved_ok(path):
return path
return None
def _parse_body(text: str) -> dict | None:
try:
obj = json.loads(text)
except json.JSONDecodeError:
return None
if isinstance(obj, dict) and 'code' in obj:
return obj
return None
def _saved_ok(path: Path) -> bool:
if not path.exists() or path.stat().st_size < 20:
return False
try:
text = path.read_text(encoding='utf-8')
except OSError:
return False
return _parse_body(text) is not None
def post_shop(task: dict[str, str], packet: dict, session: requests.Session) -> tuple[int, str]:
body_obj = dict(packet['body'])
body_obj['poi_id_str'] = task['poi_id_str']
body_obj['req_time'] = str(int(time.time() * 1000))
body = '&'.join(f'{key}={value}' for key, value in body_obj.items())
headers = dict(packet['headers'])
mtgsig = get_h5_mtgsig_pure(
url=packet['url'],
data=body,
mtgsig=packet['mtgsig'] or '{}',
method='POST',
cookie=headers.get('Cookie', ''),
)
headers['mtgsig'] = mtgsig
origin_poi = packet['poi']
if origin_poi and headers.get('Referer'):
headers['Referer'] = headers['Referer'].replace(
'poi_id_str=' + origin_poi,
'poi_id_str=' + task['poi_id_str'],
1,
)
resp = session.post(
packet['url'],
data=body.encode('utf-8'),
headers=headers,
timeout=TIMEOUT,
verify=False,
)
return resp.status_code, resp.text
def _request_shop(index: int, total: int, task: dict[str, str], packet: dict, session: requests.Session, label: str):
text = ''
status = 0
obj = None
for attempt in range(1, RETRY + 1):
try:
status, text = post_shop(task, packet, session)
except Exception as exc:
print(f'[err] {index}/{total} 第{attempt}次 {label} {exc}')
if attempt < RETRY:
time.sleep(BACKOFF_SEC[min(attempt - 1, len(BACKOFF_SEC) - 1)])
continue
obj = _parse_body(text)
if status == 200 and obj is not None:
return status, text, obj
if attempt >= RETRY:
print(f'[err] {index}/{total} 第{attempt}次 HTTP {status} 不落盘')
break
wait = BACKOFF_SEC[min(attempt - 1, len(BACKOFF_SEC) - 1)]
print(f'[err] {index}/{total} 第{attempt}次 HTTP {status} 不落盘,{wait}s 后重试')
time.sleep(wait)
return status, text, obj
def run_packet(packet: dict, tasks_q: queue.Queue, total: int, stats: dict) -> None:
session = requests.Session()
session.trust_env = False
if packet['proxies']:
session.proxies.update(packet['proxies'])
tag = f'包{packet["id"]}'
streak = 0
while True:
try:
index, task = tasks_q.get_nowait()
except queue.Empty:
print(f'[ok] {tag} 队列空,线程结束')
return
path = raw_path(task)
label = f'{tag} {task["shop_id"]} {task["org_name"]} {task["poi_id_str"]}'
existed = done_path(task) if SKIP_DONE else None
if existed is not None:
with _io_lock:
stats['skip'] += 1
print(f'[skip] {index}/{total} 已有 {existed.name}')
continue
status, text, obj = _request_shop(index, total, task, packet, session, label)
if status == 200 and obj is not None:
with _io_lock:
existed = done_path(task) if SKIP_DONE else None
if existed is not None:
stats['skip'] += 1
print(f'[skip] {index}/{total} 已有 {existed.name}')
continue
path.write_text(text, encoding='utf-8')
bump_packet(packet['id'])
streak = 0
code = obj.get('code')
msg = obj.get('msg') or obj.get('message') or ''
with _io_lock:
if code == 0:
stats['ok'] += 1
print(f'[ok] {index}/{total} {tag} HTTP {status} code={code} 长度={len(text)} -> {path.name}')
else:
stats['fail'] += 1
print(f'[err] {index}/{total} {tag} HTTP {status} code={code} msg={msg} -> {path.name}')
elif status in (403, 418):
tasks_q.put((index, task))
mark_packet(packet['id'], status)
print(f'[db] {tag} HTTP {status} 线程停止,店放回队列')
return
else:
with _io_lock:
stats['fail'] += 1
streak += 1
print(f'[err] {index}/{total} {tag} HTTP {status} 最终失败,未写入 {path.name}')
if streak >= STOP_AFTER_403:
print(f'[err] {tag} 连续 {streak} 家失败,这条线程先停')
return
time.sleep(SLEEP_SEC)
def main() -> None:
if not PACKETS:
print('[err] pinhaofan_item_hd 没有 is_ok 为空的抓包')
return
tasks = load_tasks()
if LIMIT > 0:
tasks = tasks[:LIMIT]
out_dir = HERE / OUT_DIR
out_dir.mkdir(parents=True, exist_ok=True)
stats = {'ok': 0, 'skip': 0, 'fail': 0}
pending = []
for index, task in enumerate(tasks, 1):
existed = done_path(task) if SKIP_DONE else None
if existed is not None:
stats['skip'] += 1
print(f'[skip] {index}/{len(tasks)} 已有 {existed.name}')
continue
pending.append((index, task))
print(f'[step] 任务 {len(tasks)} 家,待请求 {len(pending)},线程 {len(PACKETS)},原始响应 -> {out_dir}')
health = check_health()
print(f'[ok] 出签 {health.get("ok")} port={health.get("port")}')
tasks_q = queue.Queue()
for item in pending:
tasks_q.put(item)
threads = []
for packet in PACKETS:
thread = threading.Thread(
target=run_packet,
args=(packet, tasks_q, len(tasks), stats),
name=f'hd-{packet["id"]}',
)
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
left = tasks_q.qsize()
print(f'[ok] 成功 {stats["ok"]} 跳过 {stats["skip"]} 失败 {stats["fail"]} 未跑 {left} 目录 {out_dir}')
def main_one() -> None:
if not PACKETS:
print('[err] pinhaofan_item_hd 没有 is_ok 为空的抓包')
return
packet = None
if PACKET_ID:
for item in PACKETS:
if item['id'] == PACKET_ID:
packet = item
break
if packet is None:
print(f'[err] 没有 id={PACKET_ID} 的未用抓包')
return
else:
packet = PACKETS[0]
tasks = load_tasks()
if LIMIT > 0:
tasks = tasks[:LIMIT]
out_dir = HERE / OUT_DIR
out_dir.mkdir(parents=True, exist_ok=True)
stats = {'ok': 0, 'skip': 0, 'fail': 0}
pending = []
for index, task in enumerate(tasks, 1):
existed = done_path(task) if SKIP_DONE else None
if existed is not None:
stats['skip'] += 1
print(f'[skip] {index}/{len(tasks)} 已有 {existed.name}')
continue
pending.append((index, task))
print(
f'[step] 单包 id={packet["id"]} 城市={packet["city"] or "未匹配"} '
f'代理={proxy_host(packet["proxies"])} 待请求 {len(pending)},原始响应 -> {out_dir}'
)
health = check_health()
print(f'[ok] 出签 {health.get("ok")} port={health.get("port")}')
tasks_q = queue.Queue()
for item in pending:
tasks_q.put(item)
run_packet(packet, tasks_q, len(tasks), stats)
left = tasks_q.qsize()
print(f'[ok] 单包结束 成功 {stats["ok"]} 跳过 {stats["skip"]} 失败 {stats["fail"]} 未跑 {left} 目录 {out_dir}')
if __name__ == '__main__':
# main()
main_one()