Files
hotel-datagram-boar/酒店详情.py
T
2026-10-24 19:23:03 +08:00

780 lines
32 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import os.path
import random
import time
import uuid
import requests
import traceback
import json
from urllib.parse import urlencode, urlparse, parse_qs, unquote
from 酒店任务拿交 import get_one_task, upload_one_task
import newsetting as ten
tent = ten.All_Setting(host='183.6.7.91', port=33016, db='mt_hotel')
tent2 = ten.All_Setting(host='192.168.5.2', port=3307, db='headers_project')
# proxy = {"http": None, "https": None}
import pymysql
from datetime import datetime
from typing import Dict, Any, Optional
from 小程序mtgsig import get_mtgsig,get_h5_mtgsig_pure
import hotel_insight as insight # 埋点:只写本地 JSONL,不影响主流程
# 代理出口城市 -> (lat, lng),1位小数,向真机抓包精度看齐(真机广州=23.1,113.3 已验证)
# 用途:get_prox 返回代理出口城市后,按城市名取对应坐标,让 lat/lng 与 IP 出口地同源
CITY_GPS = {
"苏州": ("31.3", "120.6"),
"佛山": ("23.0", "113.1"),
"长沙": ("28.2", "112.9"),
"武汉": ("30.594940", "114.302634"),
"杭州": ("30.231471", "120.018594"),
"太原": ("37.9", "112.5"),
"乌鲁木齐": ("43.8", "87.6"),
"上海": ("30.948869", "121.303506"),
"重庆": ("29.6", "106.5"),
"成都": ("30.6", "104.1"),
"南通": ("32.0", "120.9"),
"深圳": ("22.545482", "114.055597"),
"兰州": ("36.1", "103.8"),
"海口": ("20.0", "110.3"),
"济南": ("36.7", "117.0"),
"南京": ("32.1", "118.8"),
"郑州": ("34.7", "113.6"),
"福州": ("26.1", "119.3"),
"拉萨": ("29.7", "91.1"),
"沈阳": ("41.8", "123.4"),
"广州": ("23.437968", "113.554650"),
"昆明": ("25.0", "102.7"),
"北京": ("39.9", "116.4"),
"天津": ("39.1", "117.2"),
"长春": ("43.9", "125.3"),
"西安": ("34.3", "108.9"),
"哈尔滨": ("45.8", "126.5"),
"贵阳": ("26.6", "106.7"),
"银川": ("38.5", "106.2"),
"西宁": ("36.616448", "101.775687"),
"南昌": ("28.7", "115.9"),
"呼和浩特": ("40.8", "111.7"),
"石家庄": ("38.0", "114.5"),
"南宁": ("22.8", "108.4"),
"合肥": ("31.8", "117.2"),
"青岛": ("36.1", "120.4"),
"东莞": ("23.0", "113.8"),
"厦门": ("24.5", "118.1"),
"无锡": ("31.5", "120.3"),
"大连": ("38.9", "121.6"),
}
def clean_and_insert_hotel_booking(
raw_data: Dict[str, Any],
) -> Dict[str, Any]:
"""
清洗酒店预订数据并插入数据库
Args:
raw_data: API返回的原始数据
Returns:
{'success': bool, 'message': str, 'id': int or None}
"""
# 1. 检查响应状态
if raw_data.get('code') != 0:
return {
'success': False,
'message': f"API返回错误: {raw_data.get('message', '未知错误')}",
'id': None
}
data = raw_data.get('data', {})
if not data:
return {
'success': False,
'message': '数据为空',
'id': None
}
# 2. 数据清洗
def clean_string(value: Any, max_length: int = None) -> Optional[str]:
"""清洗字符串字段"""
if value is None:
return None
result = str(value).strip()
if max_length and len(result) > max_length:
result = result[:max_length]
return result if result else None
def clean_int(value: Any, default: int = None) -> Optional[int]:
"""清洗整数字段"""
if value is None:
return default
try:
return int(value)
except (ValueError, TypeError):
return default
def clean_date(value: Any) -> Optional[str]:
"""清洗日期字段"""
if value is None:
return None
try:
# 验证日期格式
datetime.strptime(str(value), '%Y-%m-%d')
return str(value)
except ValueError:
return None
# 3. 清洗后的数据
cleaned_data = {
'hotel_id': clean_string(data.get('hotelId'), 20),
'city_id': clean_string(data.get('cityId'), 10),
'hotel_name': clean_string(data.get('hotelName'), 100),
'hotel_address': clean_string(data.get('hotelAddress'), 200),
'city_name': clean_string(data.get('cityName'), 50),
'check_in_date': clean_date(data.get('checkInDate')),
'check_out_date': clean_date(data.get('checkOutDate')),
'unique_id': clean_string(data.get('uniqueId'), 100),
'time_left': clean_int(data.get('timeLeft')),
'hotel_star': clean_string(data.get('hotelStar'), 20),
'selected_city': clean_string(data.get('selectedCity'), 50),
'area_type': clean_string(data.get('areaType'), 50),
'area_name': clean_string(data.get('areaName'), 100),
'level': clean_int(data.get('level'), 0)
}
# 4. 验证必填字段
required_fields = ['hotel_id', 'city_id', 'hotel_name', 'check_in_date', 'check_out_date']
for field in required_fields:
if not cleaned_data.get(field):
return {
'success': False,
'message': f'必填字段缺失: {field}',
'id': None
}
try:
# 使用 INSERT ... ON DUPLICATE KEY UPDATE 处理重复
sql = """
INSERT INTO hotel_task (
hotel_id, city_id, hotel_name, hotel_address, city_name,
check_in_date, check_out_date, unique_id, time_left,
hotel_star, selected_city, area_type, area_name, level
) VALUES (
%(hotel_id)s, %(city_id)s, %(hotel_name)s, %(hotel_address)s, %(city_name)s,
%(check_in_date)s, %(check_out_date)s, %(unique_id)s, %(time_left)s,
%(hotel_star)s, %(selected_city)s, %(area_type)s, %(area_name)s, %(level)s
)
ON DUPLICATE KEY UPDATE
city_id = VALUES(city_id),
hotel_name = VALUES(hotel_name),
hotel_address = VALUES(hotel_address),
city_name = VALUES(city_name),
check_in_date = VALUES(check_in_date),
check_out_date = VALUES(check_out_date),
unique_id = VALUES(unique_id),
time_left = VALUES(time_left),
hotel_star = VALUES(hotel_star),
selected_city = VALUES(selected_city),
area_type = VALUES(area_type),
area_name = VALUES(area_name),
level = VALUES(level)
"""
tent.write_data(sql, (cleaned_data,))
return {
'success': True,
'message': '插入成功',
'id': None,
}
except pymysql.IntegrityError as e:
return {
'success': False,
'message': f'数据完整性错误: {str(e)}',
'id': None
}
except pymysql.Error as e:
return {
'success': False,
'message': f'数据库错误: {str(e)}',
'id': None
}
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)
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 get_sign_new(url, data, dfpid, mtg_origin):
headers = {"content-type": "application/json", "token": "jksdfhiownefopwef902fsdf"}
body = {
"mtg_origin": mtg_origin,
"url": url,
"data": data,
"dfpid": dfpid,
"method": "POST"}
# url = "http://124.222.120.219:18003/hz_wm_jym_1008"
url = 'http://8.138.127.139:10063/newmtgsig'
req = requests.post(url, headers=headers, json=body, proxies={'http': None, 'https': None}, verify=False).text
return req
def get_sign_new1(url, data, dfpid, mtg_origin,openId):
headers = {"content-type": "application/json", "token": "test_sdfio23923ojbedfojgbouqgew4r32dds"}
body = {
"mtg_origin":mtg_origin,
"url": url,
"data": data,
"dfpid": dfpid,
"method": "POST",
"open_id": openId,# 微信的open_id
}
# url = "http://124.222.120.219:18003/hz_wm_jym_1008"
url = 'http://129.211.12.35:18003/minipro_mt_0206'
req = requests.post(url, headers=headers, json=body, proxies={'http': None, 'https': None}, verify=False).text
print(req)
return req
def get_sign_new_get(url, data, dfpid, mtg_origin):
headers = {"content-type": "application/json", "token": "jksdfhiownefopwef902fsdf"}
body = {
"mtg_origin": mtg_origin,
"url": url,
"data": data,
"dfpid": dfpid,
"method": "GET"}
# url = "http://124.222.120.219:18003/hz_wm_jym_1008"
url = 'http://8.138.127.139:10063/newmtgsig'
req = requests.post(url, headers=headers, json=body, proxies={'http': None, 'https': None}, verify=False).text
return req
def get_sign_new1_get(url, data, dfpid, mtg_origin,openId):
headers = {"content-type": "application/json", "token": "test_sdfio23923ojbedfojgbouqgew4r32dds"}
body = {
"mtg_origin":mtg_origin,
"url": url,
"data": data,
"dfpid": dfpid,
"method": "GET",
"open_id": openId,# 微信的open_id
}
# url = "http://124.222.120.219:18003/hz_wm_jym_1008"
url = 'http://129.211.12.35:18003/minipro_mt_0206'
req = requests.post(url, headers=headers, json=body, proxies={'http': None, 'https': None}, verify=False).text
print(req)
return req
def get_Datatext(dataq):
str1 = ''
for i in dataq:
key, value = i, dataq[i]
str2 = f'{key}={value}&'
str1 = str1 + str2
data = str1[0:-1]
return data
class hotel_run:
USER = "thzn-datagram0001"
PWD = "thzn-datagram0001"
VENDOR = "mt-datagram"
# clientid = uuid.uuid4().int
clientid = "666"
costSourceChannel = "1"
input = ""
keyword = ""
mtShareId = ""
fromOffline = "false"
flagshipFilter = "1"
needShowNewDiscInfo = "false"
lat = "31.820953"
lng = "117.222201"
ci = "20"
channelCityId = "20"
hotelCustomGpsStatus = "0"
specialDealHotelScene = "true"
riskPlatform = "13"
channelSelectCityId = "20"
appletVersionName = "9.51.4"
appletAppId = "wxde8ac0a21135c07d"
specAttributionChannel = ""
magicMemberCode = "1102,1103"
# proxy = {"http": None,"https": None}
def __init__(self):
self.proxy_list = self.get_prox()
print(self.proxy_list)
def run_shelf(self, url, params, headers, data, prox, task):
clientid = task['data']['cityName'].replace('市', '')
if prox:
self.proxy = json.loads(prox)
# 查绑定城市对应的美团cityId(用于gps_cityid/locateCityId等定位字段)
gps_city_id = self.get_city_id(self.bound_city)
if not gps_city_id:
print(f"城市 {self.bound_city} 在 area_info 查不到 cityId,跳过")
return -1
# 绑定城市坐标,businessParams里是字符串("23.1"),顶层data是数字(23.1)
city_gps = CITY_GPS.get(self.bound_city)
if not city_gps:
print(f"城市 {self.bound_city} 在 CITY_GPS 无坐标,跳过")
return -1
result = clean_and_insert_hotel_booking(task)
hotel_info = task["data"]
print(result)
print(task)
print(type(task['data']))
data['poiId'] = task['data']['hotelId']
data['requestParams'][0]['businessParams']['poiId'] = task['data']['hotelId']
start = int(datetime.strptime(task['data']['checkInDate'], '%Y-%m-%d').timestamp() * 1000)
end = int(datetime.strptime(task['data']['checkOutDate'], '%Y-%m-%d').timestamp() * 1000)
data['requestParams'][0]['businessParams']['start'] = start
data['requestParams'][0]['businessParams']['end'] = end
data['requestParams'][0]['businessParams']['cityId'] = task["data"]["cityId"] # 酒店城市组,跟任务走,真机=2332,OK
data['requestParams'][0]['businessParams']['channelCityId'] = task["data"]["cityId"] # 酒店城市组,跟任务走,OK
data['requestParams'][0]['businessParams']['userCityId'] = task["data"]["cityId"] # 酒店城市组,跟任务走,OK
data['requestParams'][0]['businessParams']['appCityId'] = task["data"]["cityId"] # 酒店城市组,跟任务走,OK
data['requestParams'][0]['businessParams']['gps_cityid'] = gps_city_id # 用户定位城市组,跟绑定城市走
data['requestParams'][0]['businessParams']['gpsCityid'] = gps_city_id # 用户定位城市组,跟绑定城市走
data['requestParams'][0]['businessParams']['locateCityId'] = gps_city_id # 用户定位城市组,跟绑定城市走
data['requestParams'][0]['businessParams']['locatecityid'] = gps_city_id # 用户定位城市组,跟绑定城市走
data['requestParams'][0]['businessParams']['lat'] = city_gps[0] # businessParams里lat是字符串
data['requestParams'][0]['businessParams']['lng'] = city_gps[1] # businessParams里lng是字符串
# data顶层定位字段:真机里 lat/lng 是数字类型,locateCityId 跟绑定城市走
data['lat'] = float(city_gps[0]) # 顶层lat是数字,真机=23.1
data['lng'] = float(city_gps[1]) # 顶层lng是数字,真机=113.3
data['locateCityId'] = gps_city_id # 顶层定位城市ID,跟绑定城市走
data['locatecityid'] = gps_city_id # 顶层定位城市ID小写版,跟绑定城市走
data['clientRequestTime'] = int(time.time() * 1000) # 请求级实时时间戳,真机每次变
# poi = '1743020617'
# data['poiId'] = poi
# data['requestParams'][0]['businessParams']['poiId'] = poi
data2 = json.dumps(data, separators=(',', ':'))
new_url = build_url(url, params)
mtg_origin = eval(headers['mtgsig'])
dfpid = mtg_origin['a3']
# headers['mtgsig'] = get_mtgsig(new_url, data2, dfpid, mtg_origin,openId)
if 'openId' in headers:
openId = headers['openId']
else:
openId = headers['openid']
headers['mtgsig'] = get_sign_new1(new_url, data2, dfpid, mtg_origin, openId)
# response = requests.post(url, headers=headers, data=data,params=params)
response = requests.post(new_url, headers=headers, data=data2, proxies=self.proxy)
print("response.text", '-' * 50, response.text[:])
if '您的网络好像不太给力,请稍后再试' in response.text:
# 埋点:418 也要落一条 exception(与 prepayList 分支对齐)
insight.log_exception(getattr(self, 'cur_hd_id', None), getattr(self, 'cur_dfpid', None),
getattr(self, 'cur_target_city', None), '网络不给力(418)', code=418)
return 418
if "Unauthorized" in response.text[:500]:
insight.log_exception(getattr(self, 'cur_hd_id', None), getattr(self, 'cur_dfpid', None),
getattr(self, 'cur_target_city', None), 'Unauthorized(401)', code=401)
return 401
res = response.json()
_upload_resp = upload_one_task(self.VENDOR, self.USER, self.PWD, clientid, task, res)
# 埋点:交任务结果(code=0 为成功)——shelf 分支原来漏了这条,看板“交回成功”会少算
insight.log_upload(getattr(self, 'cur_hd_id', None), getattr(self, 'cur_dfpid', None),
getattr(self, 'cur_target_city', None), _upload_resp,
unique_id=hotel_info.get('uniqueId'), city_name=hotel_info.get('cityName'))
# 从响应里提取 traceId,存到 self 供外部回写 hotel_hd
self.last_trace_id = self._find_trace_id(res)
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(res), hotel_info.get('hotelId'), hotel_info.get('cityId'),
hotel_info.get('hotelName'),
hotel_info.get('cityName'), hotel_info.get('checkInDate'),
hotel_info.get('checkOutDate')),))
return 1
def run_prepayList(self, url, params, headers, prox, task):
clientid = task['data']['cityName'].replace('市', '')
if prox:
self.proxy = json.loads(prox)
gps_city_id = self.get_city_id(self.bound_city)
if not gps_city_id:
print(f"城市 {self.bound_city} 在 area_info 查不到 cityId,跳过")
return -1
city_gps = CITY_GPS.get(self.bound_city)
if not city_gps:
print(f"城市 {self.bound_city} 在 CITY_GPS 无坐标,跳过")
return -1
result = clean_and_insert_hotel_booking(task)
hotel_info = task["data"]
print(result)
params['poiId'] = task['data']['hotelId']
start = str(int(datetime.strptime(task['data']['checkInDate'], '%Y-%m-%d').timestamp() * 1000))
end = str(int(datetime.strptime(task['data']['checkOutDate'], '%Y-%m-%d').timestamp() * 1000))
params['start'] = start
params['end'] = end
params['gps_cityid'] = gps_city_id
params['locateCityId'] = gps_city_id
params['locatecityid'] = gps_city_id
params['cityId'] = task["data"]["cityId"]
params['ci'] = task["data"]["cityId"]
params['channelCityId'] = task["data"]["cityId"]
params['channelSelectCityId'] = task["data"]["cityId"]
params['gps_cityid'] = task["data"]["cityId"]
params['lat'] = city_gps[0]
params['lng'] = city_gps[1]
new_url = build_url(url, params)
mtg_origin = eval(headers['mtgsig'])
dfpid = mtg_origin['a3']
# headers['mtgsig'] = get_sign_new_get(new_url, '', dfpid, mtg_origin)
if 'openId' in headers:
openId = headers['openId']
else:
openId = headers['openid']
headers['mtgsig'] = get_sign_new1_get(new_url, '', dfpid, mtg_origin,openId)
response = requests.get(new_url, headers=headers, proxies=self.proxy)
# print("response.text[:]", '-' * 50, response.text[:])
if '您的网络好像不太给力,请稍后再试' in response.text:
insight.log_exception(getattr(self, 'cur_hd_id', None), getattr(self, 'cur_dfpid', None),
getattr(self, 'cur_target_city', None), '网络不给力(418)', code=418)
return 418
if "Unauthorized" in response.text[:500]:
print(response.text[:500])
insight.log_exception(getattr(self, 'cur_hd_id', None), getattr(self, 'cur_dfpid', None),
getattr(self, 'cur_target_city', None), 'Unauthorized(401)', code=401)
return 401
res = response.json()
_upload_resp = upload_one_task(self.VENDOR, self.USER, self.PWD, clientid, task, res)
# 埋点:交任务结果(code=0 为成功)
insight.log_upload(getattr(self, 'cur_hd_id', None), getattr(self, 'cur_dfpid', None),
getattr(self, 'cur_target_city', None), _upload_resp,
unique_id=hotel_info.get('uniqueId'), city_name=hotel_info.get('cityName'))
self.last_trace_id = self._find_trace_id(res)
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(res), hotel_info.get('hotelId'), hotel_info.get('cityId'), hotel_info.get('hotelName'),
hotel_info.get('cityName'), hotel_info.get('checkInDate'), hotel_info.get('checkOutDate')),))
return 1
def get_headers(self):
# 取一批可用抓包 headers,主循环随机挑一条跑
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;
'''
# 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
def run_one(self, items):
items = list(items)
# 埋点兜底:拿任务失败时还没走 item 选择,先用首条记录账号身份(不影响主流程)
_fallback = items[0] if items else None
_fallback_id = _fallback[0] if _fallback else None
_fallback_dfpid = _fallback[5] if _fallback and len(_fallback) > 5 else None
prox_cities = []
for prox_city in self.proxy_list:
if prox_city[1]:
prox_cities.append(prox_city[1])
headers_cities = []
for headers_city in items:
if headers_city[3]:
headers_cities.append(headers_city[3])
if headers_cities:
task_city = headers_cities[random.randint(0, len(headers_cities) - 1)]
else:
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)
if not task:
# 埋点:拿任务失败(前端“空任务”告警来源)
insight.log_fetch_empty(_fallback_id, _fallback_dfpid, None, task_city, task)
# 拿任务失败:把该城市下所有可用包(is_ok IS NULL)标记为 0,看板上一眼能看出该城包不可用
self.mark_city_failed(task_city)
print(task_city)
return -1
cityName = task['data']['cityName']
none_city_item_list = []
items = list(items)
random.shuffle(items)
item = None
for j in items:
if j[3] is None:
none_city_item_list.append(j)
elif j[3] in cityName:
item = j
break
if not item:
if none_city_item_list:
item = none_city_item_list[0]
else:
# 城市不匹配:任务城市在可用包里找不到对应账号 → 这轮跑不了,标记后跳过
print(f"没有与任务城市 {cityName} 匹配的包,跳过")
self.mark_city_mismatch(task_city, _fallback_id, _fallback_dfpid,
f"任务城市 {cityName} 没有匹配的包")
return -1
# 跑单条抓包:解析 headers -> 绑定城市/IP -> 分接口请求 -> 回写状态
ind, hd, prox, city, mt_traceid, dfpid = item
# 埋点:领到任务(账号 + 绑定城市 + 目标城市)
self.cur_hd_id = ind
self.cur_dfpid = dfpid
self.cur_target_city = task_city
insight.log_fetch(ind, dfpid, city, task_city, task)
url, headers, data = json.loads(hd)
if isinstance(data, str) and '{' in data:
data = json.loads(data)
new_url, params = parse_url(url)
# 上次响应有 traceId 时,带回请求头继续跑
if mt_traceid:
headers['M-TRACEID'] = mt_traceid
self.last_trace_id = mt_traceid
# city/prox 只要已有绑定就优先沿用,避免城市和 IP 来回跳
if city and prox:
self.proxy = json.loads(prox)
self.bound_city = city
elif city and not prox:
# 有城市没IP:从代理池里补同城 IP
matched = [p for p in self.proxy_list if p[1] == city]
if not matched:
print(f"城市 {city} 在代理池无IP,跳过")
self.mark_city_mismatch(city, ind, dfpid, f"城市 {city} 在代理池没有可用 IP")
return
self.proxy = json.loads(matched[0][0])
self.bound_city = city
elif not city and prox:
# 有IP没城市:反查这个 IP 属于哪个城市
matched = [p for p in self.proxy_list if p[0] == prox]
if not matched:
print(f"ID={ind} 有IP但反查不到城市,跳过")
self.mark_city_mismatch(city or getattr(self, "bound_city", None), ind, dfpid,
"代理 IP 反查不到城市")
return
self.bound_city = matched[0][1]
self.proxy = json.loads(prox)
city = self.bound_city
else:
# 全新包:随机拿一个 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"本次使用: 城市={self.bound_city}, proxy={self.proxy}")
try:
# 根据抓包 URL 分发到对应请求函数
if '/hotel/core/router/shelf' in new_url:
result = self.run_shelf(new_url, params, headers, data, None, task)
if result == -1:
# 绑定城市查不到 cityId / 没有坐标 → 城市不匹配,这包跑不了
_c = getattr(self, "bound_city", None) or city
self.mark_city_mismatch(_c, ind, dfpid, f"城市 {_c} 缺少 cityId/坐标")
return -1
elif '/productapi/v3/prepayList' in new_url:
result = self.run_prepayList(new_url, params, headers, None, task)
if result == -1:
_c = getattr(self, "bound_city", None) or city
self.mark_city_mismatch(_c, ind, dfpid, f"城市 {_c} 缺少 cityId/坐标")
return -1
else:
print(f"未知接口,跳过: {new_url}")
return
self.update_headers(result, ind, city, self.last_trace_id)
except Exception as e:
error_msg = f"""
{'=' * 50}
时间: {time.strftime('%Y-%m-%d %H:%M:%S')}
ID: {ind}
错误类型: {type(e).__name__}
错误信息: {str(e)}
详细堆栈:
{traceback.format_exc()}
{'=' * 50}
"""
print(error_msg)
if 'Expecting value: line 1 column 1 (char 0)' in str(e):
is_ok = 403
else:
is_ok = 0
# 埋点:请求异常(403 解析失败 / 0 其它),不影响原有的 is_ok 回写
insight.log_exception(ind, dfpid, task_city, e, code=is_ok)
self.update_headers(is_ok, ind, city, None)
def mark_package_failed(self, hd_id, reason=""):
"""把单个包标记为 is_ok=0(城市不匹配 / 这包跑不了)。失败只打印,不影响主流程。"""
if not hd_id:
return
try:
tent2.update_data(f"UPDATE hotel_hd SET is_ok=0 WHERE `id`={int(hd_id)}")
print(f"包 #{hd_id} {reason} → is_ok=0")
except Exception as e:
print(f"标记包失败(不影响主流程): {type(e).__name__}: {e}")
def mark_city_mismatch(self, city, hd_id=None, dfpid=None, reason="城市不匹配"):
"""城市不匹配导致这轮跑不了:①记一次拿任务失败(看板“拿任务失败城市”)②该包 is_ok=0。
两个动作各自兜底,任何异常都不能影响采集主流程。
"""
if city:
try:
insight.log_fetch_empty(hd_id, dfpid, city, city, None, note=reason)
except Exception:
pass
self.mark_package_failed(hd_id, f"{reason}(城市 {city or '未知'})")
def mark_city_failed(self, city):
"""拿任务失败时,把该城市下所有可用包(is_ok IS NULL)标记为 0。
只影响“该城市 + 可用”的行;任何异常都只能打印,不能影响采集主流程。
"""
if not city:
return
try:
safe = str(city).replace("'", "")
sql = f'''
UPDATE hotel_hd SET is_ok=0 WHERE city='{safe}' AND is_ok IS NULL AND title LIKE '%美团酒店详情%'
'''
tent2.update_data(sql)
print(f"城市 {city} 拿任务失败 → 该城市可用包已标记 is_ok=0")
except Exception as e:
print(f"标记城市失败(不影响主流程): {type(e).__name__}: {e}")
def update_headers(self, is_ok, ind, city, mt_traceid):
# 成功只累计次数,失败写 is_ok 状态,proxy/city/traceId 都回填
if is_ok == 1:
sql = f'''
UPDATE hotel_hd SET current_count=current_count+1,req_count=req_count+1,prox='{json.dumps(self.proxy)}',city='{city}',mt_traceid='{mt_traceid}' WHERE `id`={ind}
'''
else:
sql = f'''
UPDATE hotel_hd SET is_ok={is_ok},prox='{json.dumps(self.proxy)}',city='{city}',mt_traceid='{mt_traceid}' WHERE `id`={ind}
'''
tent2.update_data(sql)
def _find_trace_id(self, obj):
"""递归找响应里第一个 traceId 值"""
if isinstance(obj, dict):
if 'traceId' in obj:
return str(obj['traceId'])
for v in obj.values():
r = self._find_trace_id(v)
if r:
return r
elif isinstance(obj, list):
for item in obj:
r = self._find_trace_id(item)
if r:
return r
return None
def get_city_id(self, city_name):
"""从 area_info 查美团 cityId,查不到返回 None"""
sql = f"SELECT cityId FROM area_crood.area_info WHERE cityName='{city_name}' and title like '%美团%' LIMIT 1"
rows = tent.get_shoppingmalls(sql)
if rows:
return rows[0][0]
return None
def get_prox(self):
sql = '''
SELECT prox_data,city FROM project_proxy.proxs_list WHERE channel ORDER BY RAND()
'''
prox_list = tent2.get_shoppingmalls(sql)
return prox_list
PID_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logs', 'collector.pid')
def _write_pidfile():
"""写 pid 文件:看板据此判断采集是否已经在跑,避免重复启动两个进程。"""
try:
os.makedirs(os.path.dirname(PID_FILE), exist_ok=True)
with open(PID_FILE, 'w', encoding='utf-8') as f:
f.write(str(os.getpid()))
except Exception:
pass
def _remove_pidfile():
try:
with open(PID_FILE, encoding='utf-8') as f:
pid = f.read().strip()
if pid == str(os.getpid()):
os.remove(PID_FILE)
except Exception:
pass
if __name__ == '__main__':
_write_pidfile()
try:
for i in range(1000):
ht = hotel_run()
items = ht.get_headers()
ht.run_one(items)
time.sleep(random.randint(2, 5))
# run2()
except KeyboardInterrupt:
print('收到 Ctrl+C,退出采集')
finally:
_remove_pidfile()