# shelf 组包+发送,逻辑从 酒店详情.py run_shelf 复制;不含领任务、suggest、入库 import copy import json import os import random import sys import time from datetime import datetime, timedelta from urllib.parse import parse_qs, quote, urlencode, urlparse from curl_cffi import requests import newsetting as ten # ============ 配置区:改这里 ============ HD_ID = 20584 # hotel_hd 详情包 id AREA_NAME = '天河客运站' # hotel_area_search 里这次搜索的区域 POI_ID = '193415547' # 酒店 poiId CHECK_IN_DATE = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d') # 入住,明天 CHECK_OUT_DATE = (datetime.now() + timedelta(days=2)).strftime('%Y-%m-%d') # 离店,后天 CHECK_IN_DATE = (datetime.now()).strftime('%Y-%m-%d') # 入住,今天 CHECK_OUT_DATE = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d') # 入住,明天 PROPAGATE_DATA = None # 整份 propagate dict;与 PROPAGATE_JSON 二选一 PROPAGATE_JSON = r'C:\Users\mjz\Desktop\python\mjz\6_酒店\酒店详情_测试_grok4.7_关键词propagate.json' # 文件里取与 POI_ID 匹配项的 propagateData CITY_ID = '20' # 改城市时填写,三个都配齐才改包内城市/坐标;任一为 None 则留抓包原值 LAT = '23.1148' LNG = '113.267874' PROXY = {"http": "http://qqol:qqol@122.246.5.147:21552", "https": "http://qqol:qqol@122.246.5.147:21552"} PACKET_REQ_NUM = 20 # 这个详情包累计最多成功次数,以 hotel_hd.current_count 为准 USER = 'thzn-datagram0001' # 交任务账号 PWD = 'thzn-datagram0001' # 交任务密码 VENDOR = 'mt-datagram' # 项目标识 # ============ 配置区结束 ============ tent = ten.All_Setting(host='192.168.5.5', port=3306, db='mt_hotel') tent2 = ten.All_Setting(host='192.168.5.5', port=3306, db='mt_hotel') # hotel_hd 已迁到 mt_hotel sys.path.insert(0, r'C:\Users\mjz\Desktop\python\mjz\6_酒店') sys.path.insert(0, r'C:\Users\mjz\Desktop\python\mjz\小程序逆向\AI代码') from 小程序mtgsig import get_mtgsig from 酒店任务拿交 import upload_task_datagram, cancel_task, latest_cities import 区域搜索列表 # owl-wxapp util.traceid:uuid_v1 两半倒序异或 → 有符号 int64;node/clockseq 进程内固定 _trace_node = None _trace_clockseq = None _trace_last_msecs = 0 _trace_last_nsecs = 0 def gen_m_traceid(): # 对齐小程序 @dp/owl-wxapp,每次请求重新生成 M-TRACEID global _trace_node, _trace_clockseq, _trace_last_msecs, _trace_last_nsecs if _trace_node is None or _trace_clockseq is None: seed = [0] * 16 r = 0 for t in range(16): if (t & 3) == 0: r = int(random.random() * 4294967296) & 0xffffffff seed[t] = (r >> ((t & 3) << 3)) & 255 if _trace_node is None: _trace_node = [1 | seed[0], seed[1], seed[2], seed[3], seed[4], seed[5]] if _trace_clockseq is None: _trace_clockseq = 16383 & ((seed[6] << 8) | seed[7]) msecs = int(time.time() * 1000) nsecs = _trace_last_nsecs + 1 dt = msecs - _trace_last_msecs + (nsecs - _trace_last_nsecs) / 10000.0 clockseq = _trace_clockseq if dt < 0: clockseq = (clockseq + 1) & 16383 if dt < 0 or msecs > _trace_last_msecs: nsecs = 0 _trace_last_msecs = msecs _trace_last_nsecs = nsecs _trace_clockseq = clockseq msecs2 = msecs + 12219292800000 tl = int((1e4 * (msecs2 & 0x0fffffff) + nsecs) % 4294967296) tmh = int(msecs2 / 4294967296 * 1e4) & 0x0fffffff b = [0] * 16 b[0] = (tl >> 24) & 255 b[1] = (tl >> 16) & 255 b[2] = (tl >> 8) & 255 b[3] = tl & 255 b[4] = (tmh >> 8) & 255 b[5] = tmh & 255 b[6] = ((tmh >> 24) & 15) | 16 b[7] = (tmh >> 16) & 255 b[8] = (clockseq >> 8) | 128 b[9] = clockseq & 255 for j in range(6): b[10 + j] = _trace_node[j] e = ''.join(format(x, '02x') for x in b) left, right = e[:16], e[16:] xor_hex = ''.join( format(int(left[15 - t], 16) ^ int(right[15 - t], 16), 'x') for t in range(16) ) val = int(xor_hex, 16) if len(xor_hex) > 15 and int(xor_hex[0], 16) >= 8: return str(val - (1 << 64)) return str(val) def set_m_traceid(headers): # 只改抓包里本来就有的 key(大小写原样保留);没有就不写;多个就都更新成同一个新值 keys = [k for k in headers.keys() if k.lower() == 'm-traceid'] if not keys: return None tid = gen_m_traceid() for k in keys: headers[k] = tid return tid def parse_url(url: str) -> dict: """ 解析URL,返回基础URL和参数字典 Args: url: 完整的URL字符串 Returns: dict: 包含 'url' 和 'params' 的字典 """ parsed = urlparse(url) # 基础URL(不含查询参数) base_url = f"{parsed.scheme}://{parsed.netloc}{parsed.path}" # 解析查询参数 # parse_qs 返回的值是列表,这里转换为单值(如果只有一个值) params_raw = parse_qs(parsed.query, keep_blank_values=True) params = {} for key, value in params_raw.items(): # 如果列表只有一个元素,直接取值;否则保留列表 params[key] = value[0] if len(value) == 1 else value # return { # "url": base_url, # "params": params # } return (base_url, params) def build_url(base_url, params): """ 将基础URL和参数字典拼接成完整的URL """ # doseq=True 会将列表展开为多个同名参数 query_string = urlencode(params, doseq=True) full_url = f"{base_url}?{query_string}" return full_url def same_type(old, value): # 跟抓包里原来的 JSON 类型保持一致 if isinstance(old, bool): return str(value) if isinstance(old, int): return int(value) if isinstance(old, float): return float(value) return str(value) def put_city(obj, key, city_id): # 包里没有、或是 -1/0,就保持原样;正常城市 id 才跟着当前城市变 if key not in obj: return if str(obj[key]) in ('-1', '0'): return obj[key] = same_type(obj[key], city_id) def put_coord(obj, key, value): # 包里没有、或是 0,就保持原样;原来是正常坐标才跟着绑定城市变 if key not in obj: return if str(obj[key]) in ('0', '0.0'): return obj[key] = same_type(obj[key], value) def get_hd_packet(hd_id): # 从 hotel_hd 取指定 id 的详情包,只拿这一条;M-TRACEID 不发请求时写库值,走 set_m_traceid 自生成 sql = f''' SELECT json_data FROM hotel_hd WHERE id={hd_id} and current_count<20 ''' rows = list(tent2.get_shoppingmalls(sql)) if not rows: print('hotel_hd 没有这个 id 的包:', hd_id) return None, None, None hd = rows[0][0] url, headers, data = json.loads(hd) return url, headers, data def update_hd(hd_id, code, area_name): # 成功累计请求数;418/403/401 写 is_ok。关键词整段重写,最多 3 个 rows = list(tent2.get_shoppingmalls('SELECT keywords FROM hotel_hd WHERE id=%s' % hd_id)) if not rows: print('hotel_hd 没有这个 id 的包:', hd_id) return names = [] if rows[0][0]: for name in str(rows[0][0]).split(','): if name and name not in names: names.append(name) if area_name not in names: if len(names) >= 3: print('关键词已有3个,不新增', hd_id, names, area_name) else: names.append(area_name) keyword_text = ','.join(names).replace("'", "''") if code == 200: sql = f''' UPDATE hotel_hd SET current_count=IFNULL(current_count,0)+1,req_count=IFNULL(req_count,0)+1,keywords='{keyword_text}' WHERE id={hd_id} ''' elif code in (418, 403, 401): sql = f''' UPDATE hotel_hd SET is_ok={code},req_count=IFNULL(req_count,0)+1,keywords='{keyword_text}' WHERE id={hd_id} ''' else: sql = f''' UPDATE hotel_hd SET req_count=IFNULL(req_count,0)+1,keywords='{keyword_text}' WHERE id={hd_id} ''' tent2.update_data(sql) print('回写', hd_id, code, keyword_text) def find_shelf_packet(area_name): # 已跑过这个关键词、成功次数还没到 20 的包排前面,其余随机。一次取出,本地找 shelf keyword = str(area_name).replace("'", "''") rows = list(tent2.get_shoppingmalls(''' SELECT id, json_data, keywords FROM hotel_hd WHERE title LIKE '%%美团酒店详情%%' AND is_ok IS NULL AND IFNULL(current_count,0)<20 ORDER BY FIND_IN_SET('%s', IFNULL(keywords,''))>0 DESC, RAND() LIMIT 30 ''' % keyword)) for row in rows: url, headers, data = json.loads(row[1]) if '/hotel/core/router/shelf' not in url: continue if isinstance(data, str) and '{' in data: data = json.loads(data) names = [] if row[2]: for name in str(row[2]).split(','): if name and name not in names: names.append(name) if area_name in names: print('用详情包', row[0], '已跑过', area_name) else: print('用详情包', row[0]) return row[0], url, headers, data print('没有可用 shelf 包') return None, None, None, None def run_shelf_hotel(area_name, poi_id, hotel_name, pd, check_in, check_out, city='广州'): # 传入关键词、poi、店名、整份 propagate、入住、离店、城市。找一个 shelf 包打一发,再回写 hotel_hd hd_id, url, headers, data = find_shelf_packet(area_name) if not url: return base_url, params = parse_url(url) city_row = 区域搜索列表.get_city_row(city) if not city_row: return proxies = 区域搜索列表.get_proxies(city) if proxies: proxy = json.loads(proxies[random.randint(0, len(proxies) - 1)][0]) else: proxy = PROXY print('shelf', hd_id, area_name, poi_id, hotel_name, check_in, check_out, city) code, body = run_shelf_request( base_url, params, headers, data, pd, str(poi_id), check_in, check_out, proxy, city_row, ) update_hd(hd_id, code, area_name) print('结束 code=%s' % code, hd_id, poi_id, hotel_name) return code, body def submit_task(clientid, task_data, data_json): # 用领任务时的 clientId、整份任务、shelf 返回交任务。成功后 status 写成已提交 resp = upload_task_datagram( VENDOR, task_data['uniqueId'], VENDOR, task_data['selectedCity'], clientid, USER, PWD, data_json, ) print('交完', clientid, resp) if resp['code'] != 0: print('交失败', clientid, resp['code']) return resp unique_id = str(task_data['uniqueId']).replace("'", "''") tent.update_data(''' UPDATE hotel_task SET status='已提交' WHERE unique_id='%s' ''' % unique_id) print('已提交', task_data['uniqueId']) return resp def save_hotel_json(body, task_data): # shelf 成功后的报文写入 hotel_json,字段和酒店详情一致 sql = ''' INSERT INTO `hotel_json` (json_data, poi_id, city_id, hotel_name, city_name, check_in_date, check_out_date) VALUES (%s, %s, %s, %s, %s, %s, %s) ''' tent.write_data(sql, (( json.dumps(body), task_data['hotelId'], task_data['cityId'], task_data['hotelName'], task_data['cityName'], task_data['checkInDate'], task_data['checkOutDate']),)) print('酒店入库', task_data['hotelId'], task_data['hotelName']) def run_chain(city): # 没找到就再领下一条。搜到并打完 shelf、交完任务就停 while True: result = 区域搜索列表.run_client(city) if result == 'empty': return 'empty' if result == 'stop' or result is None: print('停止') return 'stop' if result == 'next': continue if result[0] == 'cancel': client_id = result[1] task_data = result[2] resp = cancel_task( task_data['uniqueId'], 30, VENDOR, task_data['selectedCity'], client_id, USER, PWD, ) print('取消', client_id, task_data['uniqueId'], resp) if resp['code'] != 0: print('取消失败,停止', client_id, resp['code']) return 'stop' continue area_name, client_id, poi_id, hotel_name, pd, check_in, check_out, unique_id, task_data = result shelf = run_shelf_hotel(area_name, poi_id, hotel_name, pd, check_in, check_out, city) if shelf is None: print('没有 shelf 包,停止') return 'stop' code, body = shelf if code != 200: print('shelf 未成功,停止', code, poi_id, hotel_name) return 'stop' submit_task(client_id, task_data, body) save_hotel_json(body, task_data) return 'done' def run_cities(): # latest_cities 一次返回当前有任务的城市。按顺序用第一个还在里面的。做完一条再从广州看 cities = ['广州', '深圳', '北京', '上海', '杭州', '成都', '苏州', '南京', '青岛'] while True: rows = latest_cities(VENDOR, USER, PWD) city = None for name in cities: short = str(name).replace('市', '') selected_city = None for selected in rows: if short in selected['selectedCity']: selected_city = selected['selectedCity'] break if selected_city: print('任务城市', selected_city) city = name break print(name, '没任务') if not city: print('这些城市都没任务') return print('跑', city) result = run_chain(city) if result == 'done' or result == 'empty': continue return def load_area_hotels(area_name): # 广州东站搜索结果,pd 是整份 propagateData sql = f''' SELECT poi_id, poi_name, pd FROM hotel_area_search WHERE area_name='{area_name}' ''' rows = tent.get_shoppingmalls(sql) hotels = [] for row in rows: hotels.append({ 'poi_id': str(row[0]), 'poi_name': row[1], 'pd': json.loads(row[2]), }) print(area_name, '酒店', len(hotels), '入住', CHECK_IN_DATE, '离店', CHECK_OUT_DATE) return hotels def load_propagate(): if PROPAGATE_DATA: return PROPAGATE_DATA if not PROPAGATE_JSON or not os.path.isfile(PROPAGATE_JSON): print('请配置 PROPAGATE_DATA 或有效的 PROPAGATE_JSON') return None with open(PROPAGATE_JSON, encoding='utf-8') as f: rows = json.load(f) for row in rows: if str(row.get('poiId')) == str(POI_ID): return row['propagateData'] print('JSON 里没有 POI_ID=%s 的 propagateData' % POI_ID) return None def run_shelf_request(url, params, headers, data, suggest_propagate, poi_id, check_in, check_out, proxy, city_row=None): data = copy.deepcopy(data) params = copy.deepcopy(params) headers = copy.deepcopy(headers) # 有 citylist 就改城市 id 和坐标。入住离店按任务日期,0 点 business = data['requestParams'][0]['businessParams'] data['poiId'] = poi_id business['poiId'] = poi_id start = int(datetime.strptime(check_in, '%Y-%m-%d').timestamp() * 1000) end = int(datetime.strptime(check_out, '%Y-%m-%d').timestamp() * 1000) business['start'] = start business['end'] = end business['hourRoomStart'] = start business['hourRoomEnd'] = start if city_row: suggest_city_id = city_row['city_id'] put_city(business, 'cityId', suggest_city_id) put_city(business, 'channelCityId', suggest_city_id) put_city(business, 'userCityId', suggest_city_id) put_city(business, 'appCityId', suggest_city_id) # put_city(business, 'gps_cityid', suggest_city_id) # put_city(business, 'gpsCityid', suggest_city_id) # put_city(business, 'locateCityId', suggest_city_id) # put_city(business, 'locatecityid', suggest_city_id) put_coord(business, 'lat', city_row['lat']) put_coord(business, 'lng', city_row['lng']) put_coord(data, 'lat', float(city_row['lat'])) put_coord(data, 'lng', float(city_row['lng'])) # put_city(data, 'locateCityId', suggest_city_id) # put_city(data, 'locatecityid', suggest_city_id) put_city(params, 'ci', suggest_city_id) data['clientRequestTime'] = int(time.time() * 1000) if 'poiType' in business and suggest_propagate['poiType'] not in (None, ''): business['poiType'] = same_type(business['poiType'], suggest_propagate['poiType']) propagate_json = json.dumps(suggest_propagate, separators=(',', ':'), ensure_ascii=False) data['propagateData'] = quote(propagate_json, safe='') params['propagateData'] = propagate_json data2 = json.dumps(data, separators=(',', ':'), ensure_ascii=False) new_url = build_url(url, params) if 'openId' in headers: openId = headers['openId'] else: openId = headers['openid'] # shelf 先本地出签,解不开再走云端;出签用抓包里的原始 mtgsig 字符串 signed = get_mtgsig(new_url, data2, headers['mtgsig'], openId, 'POST') # signed = get_mtgsig(new_url, data2, headers['mtgsig'], openId, 'POST') # mtg_origin = eval(headers['mtgsig']) # dfpid = mtg_origin['a3'] # signed = get_sign_new1(new_url, data2, dfpid, mtg_origin, openId) headers['mtgsig'] = signed set_m_traceid(headers) headers.pop('Content-Length', None) # body 已重建,长度让 curl_cffi 按实际重算 response = requests.post(new_url, headers=headers, data=data2, proxies=proxy, verify=False, http_version='v1') print("response.text", '-' * 50, response.text[:]) if '您的网络好像不太给力,请稍后再试' in response.text: print('shelf 418') return 418, response.text if "Unauthorized" in response.text[:500]: print('shelf 401') return 401, response.text if response.status_code != 200 or (response.text or '')[:1] != '{': print('shelf 失败 http=%s' % response.status_code) return response.status_code, response.text res = response.json() if res['code'] != 0: print('shelf code=%s' % res['code']) return 403, res return 200, res if __name__ == '__main__': for i in range(100): run_cities() # aa = [ # # 20788, # # 20784, # # 19817, # # 20776, # # 20773, # # 20659, # # 21273, # # 20623, # # 20620, # # 20632, # # 20638, # # 20641, # # 20644, # # 20647, # # 20602, # # 20605, # # 20599, # # 20593, # # 20587, # # 20584, # # 20693, # # 20688, # 20960, # # 20678, # ] # # 广州东站 9 家 + 天河北/广州东站 13 家,共 22 条。两边都有的酒店各请求一次 # keyword_hotels = { # "同德围": ["1012062896156277", "1256250978", "1529413963", "1548521880", "1691338433", "1965680891", "5616327", "625983", "625985", "758670205"] # } # for i in range(len(aa)): # url, headers, data = get_hd_packet(aa[i]) # if not url: # sys.exit(1) # if '/hotel/core/router/shelf' not in url: # print('详情包不是 shelf:', url[:120]) # sys.exit(1) # if isinstance(data, str) and '{' in data: # data = json.loads(data) # base_url, params = parse_url(url) # city_row = None # if CITY_ID not in (None, '') and LAT not in (None, '') and LNG not in (None, ''): # city_row = {'city_id': str(CITY_ID), 'lat': str(LAT), 'lng': str(LNG)} # count_rows = list(tent2.get_shoppingmalls('SELECT current_count FROM hotel_hd WHERE id=%s' % aa[i])) # current_count = count_rows[0][0] # if current_count is None: # current_count = 0 # if current_count >= PACKET_REQ_NUM: # print('这个包 current_count 已有%s,停止' % current_count, aa[i]) # continue # stop_packet = False # 401/418/403 或 current_count 满 20 后停掉这个包 # for area_name, poi_ids in keyword_hotels.items(): # all_hotels = load_area_hotels(area_name) # by_id = {} # for hotel in all_hotels: # by_id[hotel['poi_id']] = hotel # hotels = [] # for poi_id in poi_ids: # hotels.append(by_id[poi_id]) # print('详情包 id:', aa[i], '关键词:', area_name, '酒店数:', len(hotels), 'proxy:', PROXY) # for hotel in hotels: # if current_count >= PACKET_REQ_NUM: # print('这个包 current_count 已有%s,停止' % current_count, aa[i]) # stop_packet = True # break # print('第%s次' % (current_count + 1), hotel['poi_id'], hotel['poi_name']) # code, body = run_shelf_request( # base_url, params, headers, data, hotel['pd'], hotel['poi_id'], # CHECK_IN_DATE, CHECK_OUT_DATE, PROXY, city_row, # ) # update_hd(aa[i], code, area_name) # if code == 200: # insert_sql = ''' # INSERT INTO hotel_json # (json_data, poi_id, city_id, hotel_name, city_name, check_in_date, check_out_date) # VALUES (%s, %s, %s, %s, %s, %s, %s) # ''' # tent.write_data(insert_sql, (( # json.dumps(body, ensure_ascii=False), # hotel['poi_id'], # CITY_ID, # hotel['poi_name'], # None, # CHECK_IN_DATE, # CHECK_OUT_DATE, # ),)) # print('已入库', hotel['poi_id'], hotel['poi_name']) # current_count += 1 # print('结束 code=%s current_count=%s, 用的HD_ID是%s, 搜索关键词是%s' % (code, current_count, aa[i], area_name)) # if code in (401, 418, 403): # print('错误响应,停止这个包', aa[i], code) # stop_packet = True # break # if current_count >= PACKET_REQ_NUM: # print('这个包 current_count 已有%s,停止' % current_count, aa[i]) # stop_packet = True # break # if stop_packet: # break # print('这个包 current_count=%s' % current_count, aa[i])