更新文件说明

This commit is contained in:
upload
2026-10-28 14:12:32 +08:00
parent 29681b80ee
commit 3ed6098213
14 changed files with 10951 additions and 10 deletions
+109 -4
View File
@@ -508,15 +508,27 @@ VALUES (%s, %s, %s, %s, %s, %s, %s)
def get_headers(self):
# 取一批可用抓包 headers,主循环随机挑一条跑
#
# ⚠️ 约定:改 SQL 时只改「当前」那条,旧的注释掉、不要删 —— 方便随时回退。
# ── 历史版本(按时间顺序,保留备查)──
# 最早:每包最多 10 条
# sql = '''
# SELECT `id`,json_data,prox,city,mt_traceid FROM `hotel_hd` WHERE title LIKE '%美团酒店详情%' and is_ok is NULL and current_count<10;
# '''
# 不限条数
# sql = '''
# SELECT `id`,json_data,prox,city,mt_traceid,dfpid FROM `hotel_hd` WHERE title LIKE '%美团酒店详情%' and is_ok is NULL;
# '''
# '''
# 每包最多 40 条(current_count < 40)
sql = '''
SELECT `id`,json_data,prox,city,mt_traceid FROM `hotel_hd` WHERE title LIKE '%美团酒店详情%' and is_ok is NULL and current_count<10;
'''
sql = '''
SELECT `id`,json_data,prox,city,mt_traceid,dfpid FROM `hotel_hd` WHERE title LIKE '%美团酒店详情%' and is_ok is NULL and city is not null;
SELECT `id`,json_data,prox,city,mt_traceid,dfpid FROM `hotel_hd` WHERE title LIKE '%美团酒店详情%' and is_ok is NULL and city is not null and current_count<40;
'''
# 单条调试(按 id 只跑一个包)
# sql = '''
# SELECT `id`,json_data,prox,city,mt_traceid FROM `hotel_hd` WHERE title LIKE '%美团酒店详情%' and ((is_ok != 403 and is_ok != 418 and is_ok != 401) or is_ok is null) and id=12635
# '''
headers = tent2.get_shoppingmalls(sql)
return headers
@@ -526,6 +538,8 @@ VALUES (%s, %s, %s, %s, %s, %s, %s)
# 空池保护:没有可跑的包就不要去随机城市要任务(避免刷“拿任务失败”)
print('没有可用包,跳过本轮')
return
# 供异常退出时写诊断(哪个城市 / 手上有哪些城市的包)
self.cur_package_cities = sorted({j[3] for j in items if len(j) > 3 and j[3]})
# 埋点兜底:拿任务失败时还没走 item 选择,先用首条记录账号身份(不影响主流程)
_fallback = items[0] if items else None
_fallback_id = _fallback[0] if _fallback else None
@@ -544,6 +558,9 @@ VALUES (%s, %s, %s, %s, %s, %s, %s)
task_city = prox_cities[random.randint(0, len(prox_cities) - 1)]
task = get_one_task(self.VENDOR, self.USER, self.PWD, task_city, task_city)
print(task)
# 记录上下文:脚本异常退出时,看板要知道是哪个城市、平台返回了什么
self.cur_task_city = task_city
self.cur_task_raw = task if isinstance(task, dict) else None
if not task:
# 埋点:拿任务失败(前端“空任务”告警来源)
insight.log_fetch_empty(_fallback_id, _fallback_dfpid, None, task_city, task)
@@ -552,6 +569,7 @@ VALUES (%s, %s, %s, %s, %s, %s, %s)
print(task_city)
return -1
cityName = task['data']['cityName']
self.cur_city_name = cityName
none_city_item_list = []
items = list(items)
random.shuffle(items)
@@ -595,6 +613,25 @@ VALUES (%s, %s, %s, %s, %s, %s, %s)
else:
# 没有城市的包(新包 / 只有代理没城市):不再自动绑定城市,
# 一律等看板「添加城市」之后再跑
#
# ⚠️ 约定:以下是 2026-10-24 按需求关闭的原逻辑,保留成注释,要恢复直接取消注释。
# # 分支一:有 IP 没城市 → 反查该代理属于哪个城市
# elif not city and prox:
# matched = [p for p in self.proxy_list if p[0] == prox]
# if not matched:
# print(f"ID={ind} 有IP但反查不到城市,跳过")
# return
# self.bound_city = matched[0][1]
# self.proxy = json.loads(prox)
# city = self.bound_city
# # 分支二:全新包 → 随机拿一个同城 IP,并把城市绑定回 hotel_hd
# # pick = self.proxy_list[random.randint(0, len(self.proxy_list) - 1)]
# for pick in self.proxy_list:
# if pick[1] == cityName.replace('市',''):
# self.proxy = json.loads(pick[0])
# self.bound_city = pick[1]
# break
# city = self.bound_city
print(f"ID={ind} 还没有绑定城市,跳过:请先在看看板里添加城市")
return
@@ -696,6 +733,7 @@ VALUES (%s, %s, %s, %s, %s, %s, %s)
PID_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logs', 'collector.pid')
STATE_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logs', 'collector_state.json')
def _write_pidfile():
@@ -718,8 +756,64 @@ def _remove_pidfile():
pass
def _write_state(**fields):
"""写采集状态(logs/collector_state.json),看板据此显示“为什么停了、哪个城市”。
任何异常都吞掉:诊断信息不能影响采集本身。
"""
try:
data = {}
if os.path.exists(STATE_FILE):
try:
with open(STATE_FILE, encoding='utf-8') as f:
data = json.load(f) or {}
except Exception:
data = {}
data.update(fields)
data['pid'] = os.getpid()
data['updated_at'] = time.strftime('%Y-%m-%dT%H:%M:%S')
os.makedirs(os.path.dirname(STATE_FILE), exist_ok=True)
with open(STATE_FILE, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False)
except Exception:
pass
def _exit_report(ht, exc=None, reason='exception'):
"""组装“为什么退出”的信息:城市 / 包 / 错误 / 平台原始返回 / 可用包城市。"""
city = getattr(ht, 'cur_task_city', None) or getattr(ht, 'cur_city_name', None)
raw = getattr(ht, 'cur_task_raw', None)
try:
raw_text = json.dumps(raw, ensure_ascii=False)[:4000] if raw is not None else None
except Exception:
raw_text = str(raw)[:4000]
if exc is not None:
if isinstance(exc, IndexError) and 'list index out of range' in str(exc):
reason = 'no_matching_package'
elif isinstance(exc, KeyError) and 'data' in getattr(exc, 'args', ()):
reason = 'platform_returned_error'
error_text = '%s: %s' % (type(exc).__name__, exc)
tb = traceback.format_exc()[-2000:]
else:
error_text = None
tb = None
return {
'at': time.strftime('%Y-%m-%dT%H:%M:%S'),
'reason': reason,
'city': city,
'city_name': getattr(ht, 'cur_city_name', None),
'hd_id': getattr(ht, 'cur_hd_id', None),
'package_cities': getattr(ht, 'cur_package_cities', None),
'error': error_text,
'platform_response': raw_text,
'traceback': tb,
}
if __name__ == '__main__':
_write_pidfile()
_write_state(started_at=time.strftime('%Y-%m-%dT%H:%M:%S'), last_exit=None)
ht = None
try:
for i in range(1000):
ht = hotel_run()
@@ -735,5 +829,16 @@ if __name__ == '__main__':
# run2()
except KeyboardInterrupt:
print('收到 Ctrl+C,退出采集')
_write_state(last_exit=_exit_report(ht, reason='stopped_by_user'))
except Exception as e: # 自动暂停:把“哪个城市 + 平台返回”写下来,看板直接能看到
report = _exit_report(ht, exc=e)
_write_state(last_exit=report)
print('=' * 60)
print('采集已自动停止:%s' % (report.get('error') or ''))
print(' 城市: %s(任务城市 %s)' % (report.get('city'), report.get('city_name')))
print(' 包: %s 手上包的城市: %s' % (report.get('hd_id'), report.get('package_cities')))
if report.get('platform_response'):
print(' 平台返回: %s' % report['platform_response'][:800])
print('=' * 60)
finally:
_remove_pidfile()