943 lines
35 KiB
Python
943 lines
35 KiB
Python
import json
|
||
import random
|
||
import time
|
||
|
||
import requests as task_requests
|
||
from curl_cffi import requests
|
||
|
||
import sys
|
||
sys.path.insert(0, r'C:\Users\mjz\Desktop\python\mjz\6_酒店')
|
||
sys.path.insert(0, r'C:\Users\mjz\Desktop\python\mjz\小程序逆向\AI代码')
|
||
import 酒店详情
|
||
from 小程序mtgsig import get_mtgsig
|
||
from 酒店任务拿交 import get_task, latest_cities
|
||
|
||
tent = 酒店详情.tent # mt_hotel,hotel_suggest_hd 也在这
|
||
tent2 = 酒店详情.tent2 # project_proxy 城市和代理
|
||
|
||
PAGE_LIMIT = 10 # 每页条数。返回里没有 hotelCells 才算这个区域翻完
|
||
PAGE_SKIP = 10 # 同一关键词、同一星级筛选翻满这么多页还没有这家就跳过
|
||
# 列表底稿 hotelStar=2,3 对应高档/四星、豪华/五星。分号后的 0,1 沿用底稿。按文字包含匹配
|
||
STAR_WORDS = (
|
||
('高档', '2;0,1', '["3_高档/四星"]'),
|
||
('豪华', '3;0,1', '["3_豪华/五星"]'),
|
||
('四星', '2;0,1', '["3_高档/四星"]'),
|
||
('五星', '3;0,1', '["3_豪华/五星"]'),
|
||
)
|
||
CITY_NAME = '广州市' # hotel_area_keyword 城市
|
||
PROXY_CITY = '广州' # proxs_list.city
|
||
USER = 'thzn-datagram0001' # 任务接口账号
|
||
PWD = 'thzn-datagram0001' # 任务接口密码
|
||
VENDOR = 'mt-datagram' # 项目标识
|
||
CITY = '广东省:20_广州市' # 只领广州
|
||
CLIENT_PREFIX = 'area' # 每次领任务换一个 clientId
|
||
STOP_CODES = (305, 306, 310, 318, 320, 337, 338) # 没任务或超额就停
|
||
LIST_URL = 'https://ihotel.meituan.com/core/searchapi/hotel/list'
|
||
# 列表请求底。账号/坐标/日期/关键词运行时盖,不读抓包文件
|
||
LIST_PARAMS = {
|
||
'yodaReady': 'wx',
|
||
'csecappid': 'wxde8ac0a21135c07d',
|
||
'csecplatform': '3',
|
||
'csecversionname': '10.47.1',
|
||
'csecversion': '4.0.0',
|
||
'openId': 'oJVP50D-b_jEnTe80yI0J-cvDSFo',
|
||
'antiRepPlatform': 'Android',
|
||
'programName': 'mt',
|
||
'utm_medium': 'WEIXINPROGRAM',
|
||
'openIdCipher': 'AwQAAABJAgAAAAEAAAAyAAAAPLgC95WH3MyqngAoyM/hf1hEoKrGdo0pJ5DI44e1wGF9AT3PH7Wes03actC2n/GVnwfURonD78PewMUppAAAADhx9XRiZddltpeR0DrfC6yJIRpSOzQItDfTSk9o5Tfv9s1bXt+UodWLMoM02+hrhwsLwT7EfzPz8A==',
|
||
'utm_campaign': 'entry%3DMTLive_scene%3D1089',
|
||
'token': 'AgFFJp1-0oN-_Al7zGNkFMgCHyrAUJXVoa9Jh_e4P1i1_9bGfYjYlbERWcy0rwFFmuK-4PJ-WqE4rgAAAADaPgAA-2dXGpIIYh-mIEDXUfSJQj3hOlA5e9vT6LHe83By_r9yyKiu6YOmGkVHhP6cLmja',
|
||
'usertoken': 'AgFFJp1-0oN-_Al7zGNkFMgCHyrAUJXVoa9Jh_e4P1i1_9bGfYjYlbERWcy0rwFFmuK-4PJ-WqE4rgAAAADaPgAA-2dXGpIIYh-mIEDXUfSJQj3hOlA5e9vT6LHe83By_r9yyKiu6YOmGkVHhP6cLmja',
|
||
'userToken': 'AgFFJp1-0oN-_Al7zGNkFMgCHyrAUJXVoa9Jh_e4P1i1_9bGfYjYlbERWcy0rwFFmuK-4PJ-WqE4rgAAAADaPgAA-2dXGpIIYh-mIEDXUfSJQj3hOlA5e9vT6LHe83By_r9yyKiu6YOmGkVHhP6cLmja',
|
||
'userId': '9468263097',
|
||
'userid': '9468263097',
|
||
'uuid': '1a22c23c8e112-a67fd1c5694b60-0-0-1a22c23c8e2c8',
|
||
'locateCityId': '20',
|
||
'locatecityid': '20',
|
||
'appMiniVersion': '10.47.100',
|
||
'lat': '23.122513',
|
||
'lng': '113.285982',
|
||
'sort': 'smart',
|
||
'newLandmarkId': '1634700387',
|
||
'hotelStar': '2,3;0,1',
|
||
'areaName': '广州塔',
|
||
'disablePersonalizedAdvertising': 'false',
|
||
'disablePersonalizedSearch': 'false',
|
||
'attr_28': '129',
|
||
'wifiList': '%5B%5D',
|
||
'q': '广州塔',
|
||
'sourceType': 'hotelSearch',
|
||
'limit': '10',
|
||
'offset': '0',
|
||
'remoteJumpEnabled': 'true',
|
||
'queryRewrite': 'rewrite',
|
||
'remoteCenter': '',
|
||
'category': '5',
|
||
'accommodationType': '1',
|
||
'newcate': '1',
|
||
'flagshipFilter': '1',
|
||
'ste': '',
|
||
'searchKeywordSource': '',
|
||
'inputKeyword': '',
|
||
'propagateData': '',
|
||
'hotel_queryid': '1a22c23c8e112-a67fd1c5694b60-0-0-1a22c23c8e2c81796120092540',
|
||
'tipBoothId': '94001296',
|
||
'userLocationType': '0',
|
||
'citySwitch': '1',
|
||
'designRevisionType': '1',
|
||
'riskLevel': '71',
|
||
'optimusCode': '10',
|
||
'hotelTypeFilter': '1',
|
||
'hotelCustomGpsStatus': '0',
|
||
'pageRealTime': '0',
|
||
'cellTagType': '1',
|
||
'fingerprint': '',
|
||
'abStrategy': '{}',
|
||
'wtt_region_id': '',
|
||
'wtt_region_version': '',
|
||
'wtt_region_type': 'nib',
|
||
'magicMemberCode': '1105,1106',
|
||
'simplifyField': 'false',
|
||
'templateIdVersion': '1:v2',
|
||
'mid': '',
|
||
'landmarkPosition': '',
|
||
'pluginCardShowMap': '{}',
|
||
'bannerSort': '0',
|
||
'selectedFilterItemsReport': '["3_高档/四星","3_豪华/五星"]',
|
||
'page_source': 'hotel_home',
|
||
'appletAppId': 'wxde8ac0a21135c07d',
|
||
'componentActiveStatus': '0',
|
||
'client': 'android',
|
||
'startDay': '20261201',
|
||
'endDay': '20261201',
|
||
'cityId': '20',
|
||
'ci': '20',
|
||
'gps_cityid': '20',
|
||
'latlng': '23.122513,113.285982',
|
||
'cate': '20',
|
||
'cateId': '20',
|
||
'version_name': '9.14.800',
|
||
'platform_business': 'meituan',
|
||
'appletVersionName': '10.47.1',
|
||
'riskPlatform': '13',
|
||
'mypos': '23.122513,113.285982',
|
||
'channelSelectCityId': '20',
|
||
'clientRequestTime': '1796120092549',
|
||
'crossPlatform': '1',
|
||
'utm_fp': 'MINI_PROGRAM',
|
||
'wechatVersion': '8.0.77',
|
||
'SDKVersion': '3.17.6',
|
||
}
|
||
|
||
# 从 suggest 包盖到列表上的账号字段。列表里没有的键不动
|
||
IDENTITY_KEYS = [
|
||
'token', 'usertoken', 'userToken', 'userId', 'userid', 'uuid',
|
||
'openId', 'openIdCipher', 'utm_campaign', 'lat', 'lng',
|
||
'SDKVersion', 'appMiniVersion', 'appletVersionName', 'csecversionname', 'wechatVersion',
|
||
'locateCityId', 'locatecityid',
|
||
]
|
||
def sql_str(value):
|
||
return str(value).replace("'", "''")
|
||
|
||
|
||
def create_tables():
|
||
tent.update_data('''
|
||
CREATE TABLE IF NOT EXISTS hotel_area_keyword (
|
||
id int NOT NULL AUTO_INCREMENT,
|
||
area_name varchar(100) NOT NULL,
|
||
city_name varchar(50) NOT NULL,
|
||
check_in_date date NOT NULL,
|
||
check_out_date date NOT NULL,
|
||
page_count int NOT NULL DEFAULT 0,
|
||
hotel_count int NOT NULL DEFAULT 0,
|
||
is_ok int NULL,
|
||
created_at datetime DEFAULT CURRENT_TIMESTAMP,
|
||
updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||
PRIMARY KEY (id),
|
||
UNIQUE KEY uk_area_date (area_name, check_in_date, check_out_date)
|
||
)
|
||
''')
|
||
tent.update_data('''
|
||
CREATE TABLE IF NOT EXISTS hotel_area_search (
|
||
id int NOT NULL AUTO_INCREMENT,
|
||
parent_id int NOT NULL,
|
||
area_name varchar(100) NOT NULL,
|
||
poi_id varchar(32) NOT NULL,
|
||
poi_name varchar(200) NOT NULL,
|
||
pd mediumtext NOT NULL,
|
||
page_offset int NOT NULL,
|
||
check_in_date date NOT NULL,
|
||
check_out_date date NOT NULL,
|
||
suggest_id int NULL,
|
||
star_filter varchar(200) NULL,
|
||
created_at datetime DEFAULT CURRENT_TIMESTAMP,
|
||
updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||
PRIMARY KEY (id),
|
||
UNIQUE KEY uk_area_poi_date_star (area_name, poi_id, check_in_date, check_out_date, star_filter),
|
||
KEY idx_parent_id (parent_id)
|
||
)
|
||
''')
|
||
print('表已就绪 hotel_area_keyword / hotel_area_search')
|
||
rewrite_pd()
|
||
ensure_star_filter()
|
||
|
||
|
||
def rewrite_pd():
|
||
# 旧表把 pd 拆成了 content_transparent 等列。合成整份后再删掉拆列
|
||
cols = tent.get_shoppingmalls('SHOW COLUMNS FROM hotel_area_search')
|
||
names = set(row[0] for row in cols)
|
||
if 'pd' not in names:
|
||
tent.update_data('ALTER TABLE hotel_area_search ADD COLUMN pd mediumtext NULL')
|
||
if 'content' not in names:
|
||
print('hotel_area_search 已是 pd 列')
|
||
return
|
||
rows = tent.get_shoppingmalls('''
|
||
SELECT id, content, content_transparent, poi_type, mystery_box_cross_activity_id
|
||
FROM hotel_area_search
|
||
''')
|
||
update_sql = 'UPDATE hotel_area_search SET pd=%s WHERE id=%s'
|
||
update_data = []
|
||
for row in rows:
|
||
pd_text = json.dumps({
|
||
'content': row[1],
|
||
'contentTransparent': row[2],
|
||
'poiType': row[3],
|
||
'mysteryBoxCrossActivityId': row[4],
|
||
}, ensure_ascii=False, separators=(',', ':'))
|
||
update_data.append((pd_text, row[0]))
|
||
if update_data:
|
||
tent.update_data_many(update_sql, update_data)
|
||
tent.update_data('''
|
||
ALTER TABLE hotel_area_search
|
||
DROP COLUMN content,
|
||
DROP COLUMN content_transparent,
|
||
DROP COLUMN poi_type,
|
||
DROP COLUMN mystery_box_cross_activity_id
|
||
''')
|
||
print('已把', len(update_data), '行改成 pd')
|
||
|
||
|
||
def ensure_star_filter():
|
||
cols = tent.get_shoppingmalls('SHOW COLUMNS FROM hotel_area_search')
|
||
names = set(row[0] for row in cols)
|
||
if 'star_filter' not in names:
|
||
tent.update_data('ALTER TABLE hotel_area_search ADD COLUMN star_filter varchar(200) NULL')
|
||
print('hotel_area_search 已加 star_filter')
|
||
indexes = tent.get_shoppingmalls('SHOW INDEX FROM hotel_area_search')
|
||
key_cols = {}
|
||
for row in indexes:
|
||
if row[2] not in key_cols:
|
||
key_cols[row[2]] = []
|
||
key_cols[row[2]].append(row[4])
|
||
if 'uk_area_poi_date_star' in key_cols:
|
||
return
|
||
if 'uk_area_poi_date' in key_cols:
|
||
tent.update_data('ALTER TABLE hotel_area_search DROP INDEX uk_area_poi_date')
|
||
tent.update_data('''
|
||
ALTER TABLE hotel_area_search
|
||
ADD UNIQUE KEY uk_area_poi_date_star (area_name, poi_id, check_in_date, check_out_date, star_filter)
|
||
''')
|
||
print('hotel_area_search 唯一键已带 star_filter')
|
||
|
||
|
||
def get_keywords():
|
||
rows = tent.get_shoppingmalls('''
|
||
SELECT area_name, COUNT(*) cnt FROM hotel_task
|
||
WHERE city_name='%s' AND area_name IS NOT NULL AND area_name<>''
|
||
GROUP BY area_name
|
||
ORDER BY cnt DESC, area_name
|
||
''' % sql_str(CITY_NAME))
|
||
done_rows = tent.get_shoppingmalls('''
|
||
SELECT DISTINCT area_name FROM hotel_area_keyword
|
||
WHERE city_name='%s' AND is_ok=1
|
||
''' % sql_str(CITY_NAME))
|
||
done = set(row[0] for row in done_rows)
|
||
keywords = []
|
||
for row in rows:
|
||
if row[0] in done:
|
||
continue
|
||
print('待搜', row[0], row[1])
|
||
keywords.append(row[0])
|
||
return keywords
|
||
|
||
|
||
def get_packets():
|
||
rows = tent.get_shoppingmalls('''
|
||
SELECT id, json_data FROM hotel_suggest_hd
|
||
WHERE title='酒店搜索推荐' AND is_ok IS NULL
|
||
''')
|
||
packets = []
|
||
for row in rows:
|
||
url, headers, data = json.loads(row[1])
|
||
params = 酒店详情.parse_url(url)[1]
|
||
if 'lat' not in params or 'lng' not in params:
|
||
print('包没有坐标,跳过', row[0])
|
||
continue
|
||
packets.append({
|
||
'id': row[0],
|
||
'params': params,
|
||
'headers': headers,
|
||
'mtgsig': headers['mtgsig'],
|
||
})
|
||
random.shuffle(packets)
|
||
print('可用 suggest 包', len(packets))
|
||
return packets
|
||
|
||
|
||
def get_city_row(city_name):
|
||
# project_proxy.citylist,level=2。和酒店详情一样按城市名取 mt_city_id、坐标
|
||
name = str(city_name).replace('市', '')
|
||
rows = tent2.get_shoppingmalls('''
|
||
SELECT lat, lng, mt_city_id FROM project_proxy.citylist
|
||
WHERE level=2 AND name='%s'
|
||
LIMIT 1
|
||
''' % sql_str(name))
|
||
if not rows:
|
||
print('citylist 没有这个城市', city_name)
|
||
return None
|
||
return {'lat': str(rows[0][0]), 'lng': str(rows[0][1]), 'city_id': str(rows[0][2])}
|
||
|
||
|
||
def task_selected_city(city_name):
|
||
# 任务接口的 selectedCity。城市名包含即可,和酒店详情 get_one_task 一样
|
||
cities = latest_cities(VENDOR, USER, PWD)
|
||
name = str(city_name).replace('市', '')
|
||
for selected in cities:
|
||
if name in selected['selectedCity']:
|
||
print('任务城市', selected['selectedCity'])
|
||
return selected['selectedCity']
|
||
print('任务接口没有这个城市', city_name)
|
||
return None
|
||
|
||
|
||
def get_proxies(city_name=None):
|
||
if not city_name:
|
||
city_name = PROXY_CITY
|
||
rows = tent2.get_shoppingmalls('''
|
||
SELECT prox_data, city FROM project_proxy.proxs_list
|
||
WHERE channel AND city='%s'
|
||
''' % sql_str(city_name))
|
||
print(city_name, '代理', len(rows))
|
||
return list(rows)
|
||
name = str(city_name).replace('市', '')
|
||
rows = tent2.get_shoppingmalls('''
|
||
SELECT prox_data, city FROM project_proxy.proxs_list
|
||
WHERE channel AND city IS NOT NULL AND city!=''
|
||
''')
|
||
matched = []
|
||
for row in rows:
|
||
if row[1] and (row[1] in name or name in row[1]):
|
||
matched.append(row)
|
||
print(name, '代理', len(matched))
|
||
return matched
|
||
|
||
|
||
def ensure_keyword(area_name, check_in, check_out, city_name=None):
|
||
if not city_name:
|
||
city_name = CITY_NAME
|
||
rows = tent.get_shoppingmalls('''
|
||
SELECT id, is_ok FROM hotel_area_keyword
|
||
WHERE area_name='%s' AND check_in_date='%s' AND check_out_date='%s'
|
||
''' % (sql_str(area_name), check_in, check_out))
|
||
if rows:
|
||
return rows[0][0]
|
||
tent.write_data('''
|
||
INSERT INTO hotel_area_keyword
|
||
(area_name, city_name, check_in_date, check_out_date, page_count, hotel_count, is_ok)
|
||
VALUES (%s,%s,%s,%s,0,0,NULL)
|
||
''', [(area_name, city_name, check_in, check_out)])
|
||
rows = tent.get_shoppingmalls('''
|
||
SELECT id FROM hotel_area_keyword
|
||
WHERE area_name='%s' AND check_in_date='%s' AND check_out_date='%s'
|
||
''' % (sql_str(area_name), check_in, check_out))
|
||
return rows[0][0]
|
||
|
||
|
||
def finish_keyword(keyword_id, page_count, is_ok):
|
||
count_rows = tent.get_shoppingmalls('''
|
||
SELECT COUNT(*) FROM hotel_area_search WHERE parent_id=%s
|
||
''' % keyword_id)
|
||
hotel_count = count_rows[0][0]
|
||
if is_ok is None:
|
||
is_ok_sql = 'NULL'
|
||
else:
|
||
is_ok_sql = str(is_ok)
|
||
tent.update_data('''
|
||
UPDATE hotel_area_keyword
|
||
SET page_count=%s, hotel_count=%s, is_ok=%s
|
||
WHERE id=%s
|
||
''' % (page_count, hotel_count, is_ok_sql, keyword_id))
|
||
print('关键词收尾 id=%s page_count=%s hotel_count=%s is_ok=%s' % (keyword_id, page_count, hotel_count, is_ok_sql))
|
||
|
||
|
||
def fill_params(suggest_params, area_name, offset, landmark_id, check_in, check_out, hotel_star_param, star_filter, city_row=None):
|
||
params = dict(LIST_PARAMS)
|
||
for key in IDENTITY_KEYS:
|
||
if key in params and key in suggest_params:
|
||
params[key] = suggest_params[key]
|
||
params['mypos'] = suggest_params['lat'] + ',' + suggest_params['lng']
|
||
params['latlng'] = suggest_params['lat'] + ',' + suggest_params['lng']
|
||
q = area_name
|
||
for i, ch in enumerate(area_name):
|
||
if not ch.isalnum():
|
||
q = area_name[:i]
|
||
break
|
||
params['q'] = q
|
||
params['areaName'] = q
|
||
params['limit'] = str(PAGE_LIMIT)
|
||
params['offset'] = str(offset)
|
||
params['startDay'] = check_in.replace('-', '')
|
||
params['endDay'] = check_out.replace('-', '')
|
||
params['hotelStar'] = hotel_star_param
|
||
params['selectedFilterItemsReport'] = star_filter
|
||
now_ms = str(int(time.time() * 1000))
|
||
params['clientRequestTime'] = now_ms
|
||
params['hotel_queryid'] = suggest_params['uuid'] + now_ms
|
||
if landmark_id:
|
||
params['newLandmarkId'] = landmark_id
|
||
else:
|
||
del params['newLandmarkId']
|
||
if city_row:
|
||
city_id = city_row['city_id']
|
||
params['cityId'] = city_id
|
||
params['ci'] = city_id
|
||
params['gps_cityid'] = city_id
|
||
params['channelSelectCityId'] = city_id
|
||
params['locateCityId'] = city_id
|
||
params['locatecityid'] = city_id
|
||
params['lat'] = city_row['lat']
|
||
params['lng'] = city_row['lng']
|
||
params['mypos'] = city_row['lat'] + ',' + city_row['lng']
|
||
params['latlng'] = params['mypos']
|
||
return params
|
||
|
||
|
||
def build_headers(suggest_headers):
|
||
headers = dict(suggest_headers)
|
||
酒店详情.set_m_traceid(headers)
|
||
return headers
|
||
|
||
|
||
def read_landmark_id(res):
|
||
data = res['data']
|
||
if 'keywordOption' not in data:
|
||
return None
|
||
option = data['keywordOption']
|
||
if not isinstance(option, dict):
|
||
return None
|
||
if 'selectKey' not in option or 'selectValue' not in option:
|
||
return None
|
||
if option['selectKey'] != 'newLandmarkId':
|
||
return None
|
||
if not option['selectValue']:
|
||
return None
|
||
return str(option['selectValue'])
|
||
|
||
|
||
def save_hotels(res, keyword_id, area_name, offset, suggest_id, seen, check_in, check_out, star_filter):
|
||
insert_sql = '''
|
||
INSERT INTO hotel_area_search
|
||
(parent_id, area_name, poi_id, poi_name, pd, page_offset, check_in_date, check_out_date, suggest_id, star_filter)
|
||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||
ON DUPLICATE KEY UPDATE
|
||
parent_id=VALUES(parent_id),
|
||
poi_name=VALUES(poi_name),
|
||
pd=VALUES(pd),
|
||
page_offset=VALUES(page_offset),
|
||
suggest_id=VALUES(suggest_id),
|
||
star_filter=VALUES(star_filter)
|
||
'''
|
||
insert_data = []
|
||
cells = res['data']['hotelCells']
|
||
for cell in cells:
|
||
ext = cell['extensionArea']['extension']
|
||
if 'propagateData' not in ext or 'poiId' not in ext:
|
||
continue
|
||
poi_id = str(ext['poiId'])
|
||
if poi_id in seen:
|
||
continue
|
||
seen.add(poi_id)
|
||
propagate = ext['propagateData']
|
||
poi_name = ''
|
||
for title_item in cell['titleArea']['title']:
|
||
if 'text' in title_item:
|
||
poi_name = title_item['text']['content']
|
||
break
|
||
if not poi_name:
|
||
print('没有店名', poi_id)
|
||
seen.remove(poi_id)
|
||
continue
|
||
insert_data.append((
|
||
keyword_id,
|
||
area_name,
|
||
poi_id,
|
||
poi_name,
|
||
json.dumps(propagate, ensure_ascii=False, separators=(',', ':')),
|
||
offset,
|
||
check_in,
|
||
check_out,
|
||
suggest_id,
|
||
star_filter,
|
||
))
|
||
if insert_data:
|
||
tent.write_data(insert_sql, insert_data)
|
||
print('本页入库', len(insert_data), 'offset', offset, '累计', len(seen))
|
||
return len(cells)
|
||
|
||
|
||
def mark_packet(suggest_id, is_ok):
|
||
tent.update_data('UPDATE hotel_suggest_hd SET is_ok=%s WHERE id=%s' % (is_ok, suggest_id))
|
||
print('suggest 包', suggest_id, 'is_ok', is_ok)
|
||
|
||
|
||
def add_packet_count(suggest_id):
|
||
tent.update_data('''
|
||
UPDATE hotel_suggest_hd
|
||
SET current_count=current_count+1, req_count=req_count+1
|
||
WHERE id=%s
|
||
''' % suggest_id)
|
||
print('suggest 请求数 +1', suggest_id)
|
||
|
||
|
||
def ensure_task_client_id():
|
||
# hotel_task 补这次领任务用的 client_id
|
||
cols = tent.get_shoppingmalls('SHOW COLUMNS FROM hotel_task')
|
||
names = set(row[0] for row in cols)
|
||
if 'client_id' in names:
|
||
return
|
||
tent.update_data('ALTER TABLE hotel_task ADD COLUMN client_id varchar(100) NULL')
|
||
print('hotel_task 已加 client_id')
|
||
|
||
|
||
def ensure_task_status():
|
||
# hotel_task 补搜索结果状态
|
||
cols = tent.get_shoppingmalls('SHOW COLUMNS FROM hotel_task')
|
||
names = set(row[0] for row in cols)
|
||
if 'status' in names:
|
||
return
|
||
tent.update_data("ALTER TABLE hotel_task ADD COLUMN status varchar(20) NULL")
|
||
print('hotel_task 已加 status')
|
||
|
||
|
||
def mark_task_missing(unique_id):
|
||
tent.update_data('''
|
||
UPDATE hotel_task SET status='没找到' WHERE unique_id='%s'
|
||
''' % sql_str(unique_id))
|
||
print('没找到', unique_id)
|
||
|
||
|
||
def save_task(data):
|
||
rows = tent.get_shoppingmalls('''
|
||
SELECT id FROM hotel_task WHERE unique_id='%s'
|
||
''' % sql_str(data['uniqueId']))
|
||
if rows:
|
||
print('任务已在库', rows[0][0], data['hotelId'], data['uniqueId'])
|
||
return
|
||
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 (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||
'''
|
||
row = (
|
||
str(data['hotelId']),
|
||
str(data['cityId']),
|
||
data['hotelName'],
|
||
data['hotelAddress'],
|
||
data['cityName'],
|
||
data['checkInDate'],
|
||
data['checkOutDate'],
|
||
data['uniqueId'],
|
||
data['timeLeft'],
|
||
data['hotelStar'],
|
||
data['selectedCity'],
|
||
data['areaType'],
|
||
data['areaName'],
|
||
data['level'],
|
||
)
|
||
tent.write_data(sql, [row])
|
||
print('任务入库', data['hotelId'], data['hotelName'], data['uniqueId'])
|
||
|
||
|
||
def save_task_client(data, client_id):
|
||
# unique_id 已在库就只改 client_id,新任务插入时带上
|
||
rows = tent.get_shoppingmalls('''
|
||
SELECT id FROM hotel_task WHERE unique_id='%s'
|
||
''' % sql_str(data['uniqueId']))
|
||
if rows:
|
||
tent.update_data('''
|
||
UPDATE hotel_task SET client_id='%s' WHERE id=%s
|
||
''' % (sql_str(client_id), rows[0][0]))
|
||
print('重复任务,更新 client_id', rows[0][0], data['hotelId'], data['uniqueId'], client_id)
|
||
return
|
||
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, client_id
|
||
) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||
'''
|
||
row = (
|
||
str(data['hotelId']),
|
||
str(data['cityId']),
|
||
data['hotelName'],
|
||
data['hotelAddress'],
|
||
data['cityName'],
|
||
data['checkInDate'],
|
||
data['checkOutDate'],
|
||
data['uniqueId'],
|
||
data['timeLeft'],
|
||
data['hotelStar'],
|
||
data['selectedCity'],
|
||
data['areaType'],
|
||
data['areaName'],
|
||
data['level'],
|
||
client_id,
|
||
)
|
||
tent.write_data(sql, [row])
|
||
print('任务入库', data['hotelId'], data['hotelName'], data['uniqueId'], client_id)
|
||
|
||
|
||
def request_page(params, packet, proxy):
|
||
url = 酒店详情.build_url(LIST_URL, params)
|
||
headers = build_headers(packet['headers'])
|
||
if 'openId' in headers:
|
||
open_id = headers['openId']
|
||
else:
|
||
open_id = headers['openid']
|
||
headers['mtgsig'] = get_mtgsig(url, '', packet['mtgsig'], open_id, 'GET')
|
||
response = requests.get(url, headers=headers, proxies=proxy, verify=False, http_version='v1', timeout=20)
|
||
return response
|
||
|
||
|
||
def packet_dead(response):
|
||
if response.status_code in (403, 418, 401):
|
||
return response.status_code
|
||
text = response.text
|
||
if '您的网络好像不太给力,请稍后再试' in text:
|
||
return 418
|
||
if 'Unauthorized' in text[:500]:
|
||
return 401
|
||
return None
|
||
|
||
|
||
def hotel_in_search(hotel_id, hotel_name):
|
||
rows = tent.get_shoppingmalls('''
|
||
SELECT poi_id, area_name, poi_name FROM hotel_area_search
|
||
WHERE poi_id='%s'
|
||
LIMIT 1
|
||
''' % sql_str(hotel_id))
|
||
if rows:
|
||
print('已在 hotel_area_search', rows[0][0], rows[0][1], rows[0][2])
|
||
return True
|
||
print('不在 hotel_area_search', hotel_id, hotel_name)
|
||
return False
|
||
|
||
|
||
def get_shelf_hotel(poi_id, area_name, check_in, check_out):
|
||
# shelf 用 poi、整份 propagate、入住离店,再加酒店名称
|
||
rows = tent.get_shoppingmalls('''
|
||
SELECT poi_id, poi_name, pd, check_in_date, check_out_date
|
||
FROM hotel_area_search
|
||
WHERE poi_id='%s' AND area_name='%s' AND check_in_date='%s' AND check_out_date='%s'
|
||
ORDER BY id DESC
|
||
LIMIT 1
|
||
''' % (sql_str(poi_id), sql_str(area_name), check_in, check_out))
|
||
if not rows:
|
||
rows = tent.get_shoppingmalls('''
|
||
SELECT poi_id, poi_name, pd, check_in_date, check_out_date
|
||
FROM hotel_area_search
|
||
WHERE poi_id='%s'
|
||
ORDER BY id DESC
|
||
LIMIT 1
|
||
''' % sql_str(poi_id))
|
||
if not rows:
|
||
print('hotel_area_search 没有这家', poi_id)
|
||
return None
|
||
return str(rows[0][0]), rows[0][1], json.loads(rows[0][2]), str(rows[0][3])[:10], str(rows[0][4])[:10]
|
||
|
||
|
||
def star_filter_of(hotel_star):
|
||
text = str(hotel_star)
|
||
for word, hotel_star_param, star_filter in STAR_WORDS:
|
||
if word in text:
|
||
return hotel_star_param, star_filter
|
||
return None
|
||
|
||
|
||
def latest_batch(area_name, star_filter, check_in, check_out):
|
||
rows = tent.get_shoppingmalls('''
|
||
SELECT id FROM hotel_area_keyword
|
||
WHERE area_name='%s' AND check_in_date='%s' AND check_out_date='%s'
|
||
ORDER BY id DESC
|
||
LIMIT 1
|
||
''' % (sql_str(area_name), check_in, check_out))
|
||
if not rows:
|
||
return None
|
||
keyword_id = rows[0][0]
|
||
page_rows = tent.get_shoppingmalls('''
|
||
SELECT MAX(page_offset) FROM hotel_area_search
|
||
WHERE parent_id=%s AND star_filter='%s'
|
||
AND check_in_date='%s' AND check_out_date='%s'
|
||
''' % (keyword_id, sql_str(star_filter), check_in, check_out))
|
||
max_offset = page_rows[0][0]
|
||
if max_offset is None:
|
||
start_page = 0
|
||
else:
|
||
start_page = int(max_offset) // PAGE_LIMIT + 1
|
||
print('最新一批', keyword_id, area_name, star_filter, '已翻', start_page, '页', check_in, check_out)
|
||
return keyword_id, start_page
|
||
|
||
|
||
def run_one_keyword(area_name, packet, proxies, state, target_poi_id, hotel_name, keyword_id, start_page, check_in, check_out, hotel_star_param, star_filter, city_row=None):
|
||
print('关键词', area_name, 'keyword_id', keyword_id, 'suggest', packet['id'], '日期', check_in, check_out, '目标', target_poi_id, hotel_name, '星级', star_filter, '从第', start_page + 1, '页')
|
||
proxy = json.loads(proxies[state['proxy_index']][0])
|
||
landmark_id = None
|
||
seen = set()
|
||
page_count = start_page
|
||
while True:
|
||
offset = page_count * PAGE_LIMIT
|
||
while True:
|
||
params = fill_params(packet['params'], area_name, offset, landmark_id, check_in, check_out, hotel_star_param, star_filter, city_row)
|
||
print('请求', params['q'], '区域', area_name, 'offset', offset, 'suggest', packet['id'], 'landmark', landmark_id)
|
||
try:
|
||
response = request_page(params, packet, proxy)
|
||
except requests.exceptions.RequestException as e:
|
||
print('代理连接失败', e)
|
||
state['proxy_index'] = (state['proxy_index'] + 1) % len(proxies)
|
||
proxy = json.loads(proxies[state['proxy_index']][0])
|
||
print('换广州 IP', state['proxy_index'])
|
||
continue
|
||
dead = packet_dead(response)
|
||
if dead:
|
||
print('包失效', response.status_code, response.text[:200])
|
||
mark_packet(packet['id'], dead)
|
||
finish_keyword(keyword_id, page_count, None)
|
||
return 'dead'
|
||
if response.status_code != 200:
|
||
print('HTTP 非200', response.status_code, response.text[:200])
|
||
finish_keyword(keyword_id, page_count, 0)
|
||
return 'next'
|
||
res = response.json()
|
||
if res['code'] != 200:
|
||
print('返回 code', res['code'], response.text[:200])
|
||
finish_keyword(keyword_id, page_count, 0)
|
||
return 'next'
|
||
add_packet_count(packet['id'])
|
||
data = res['data']
|
||
if not isinstance(data, dict):
|
||
print('没有data', response.text)
|
||
finish_keyword(keyword_id, page_count, None)
|
||
return 'stop'
|
||
if 'hotelCells' not in data:
|
||
print('没有hotelCells,翻完', area_name, list(data.keys()))
|
||
finish_keyword(keyword_id, page_count, 1)
|
||
print('搜完没有这家', target_poi_id, hotel_name, area_name)
|
||
return 'done'
|
||
save_hotels(res, keyword_id, area_name, offset, packet['id'], seen, check_in, check_out, star_filter)
|
||
page_count += 1
|
||
if landmark_id is None:
|
||
landmark_id = read_landmark_id(res)
|
||
print('newLandmarkId', landmark_id)
|
||
if target_poi_id in seen:
|
||
print('搜到酒店,区域还没翻完', target_poi_id, hotel_name, area_name)
|
||
finish_keyword(keyword_id, page_count, None)
|
||
return 'found'
|
||
if page_count >= PAGE_SKIP:
|
||
print('翻满10页没搜到', target_poi_id, hotel_name, area_name, star_filter)
|
||
finish_keyword(keyword_id, page_count, None)
|
||
return 'skip'
|
||
break
|
||
|
||
|
||
def run():
|
||
create_tables()
|
||
proxies = get_proxies()
|
||
if not proxies:
|
||
print('没有广州代理,停止')
|
||
return
|
||
packets = get_packets()
|
||
if not packets:
|
||
print('没有可用 suggest 包')
|
||
return
|
||
state = {'proxy_index': 0}
|
||
packet_i = 0
|
||
seq = 0
|
||
while packet_i < len(packets):
|
||
seq += 1
|
||
clientid = '%s%05d' % (CLIENT_PREFIX, seq)
|
||
try:
|
||
task = get_task(VENDOR, USER, PWD, clientid, CITY)
|
||
except task_requests.exceptions.RequestException as e:
|
||
print('领任务失败', clientid, e)
|
||
continue
|
||
if task['code'] != 0:
|
||
print('未领到', clientid, task['code'])
|
||
if task['code'] in STOP_CODES:
|
||
print('停止领任务', task['code'])
|
||
return
|
||
continue
|
||
data = task['data']
|
||
save_task(data)
|
||
hotel_id = str(data['hotelId'])
|
||
hotel_name = data['hotelName']
|
||
area_name = data['areaName']
|
||
hotel_star = data['hotelStar']
|
||
print('任务', clientid, hotel_id, hotel_name, area_name, hotel_star, data['checkInDate'], data['checkOutDate'])
|
||
if hotel_in_search(hotel_id, hotel_name):
|
||
continue
|
||
if not area_name:
|
||
print('任务没有区域', hotel_id, hotel_name)
|
||
continue
|
||
star = star_filter_of(hotel_star)
|
||
if star is None:
|
||
print('没有这个星级的筛选', hotel_id, hotel_name, hotel_star)
|
||
continue
|
||
hotel_star_param, star_filter = star
|
||
check_in = str(data['checkInDate'])[:10]
|
||
check_out = str(data['checkOutDate'])[:10]
|
||
batch = latest_batch(area_name, star_filter, check_in, check_out)
|
||
if batch is None:
|
||
keyword_id = ensure_keyword(area_name, check_in, check_out)
|
||
start_page = 0
|
||
else:
|
||
keyword_id, start_page = batch
|
||
if start_page >= PAGE_SKIP:
|
||
print('10页内没搜到,跳过', hotel_id, hotel_name, area_name, star_filter)
|
||
continue
|
||
searched = False
|
||
while packet_i < len(packets):
|
||
packet = packets[packet_i]
|
||
print('包', packet['id'], '搜', area_name, star_filter, hotel_id, hotel_name)
|
||
result = run_one_keyword(area_name, packet, proxies, state, hotel_id, hotel_name, keyword_id, start_page, check_in, check_out, hotel_star_param, star_filter)
|
||
if result == 'stop':
|
||
return
|
||
if result == 'dead':
|
||
packet_i += 1
|
||
again = latest_batch(area_name, star_filter, check_in, check_out)
|
||
if again is None:
|
||
start_page = 0
|
||
else:
|
||
keyword_id, start_page = again
|
||
if start_page >= PAGE_SKIP:
|
||
print('10页内没搜到,跳过', hotel_id, hotel_name, area_name, star_filter)
|
||
searched = True
|
||
break
|
||
continue
|
||
packet_i += 1
|
||
searched = True
|
||
break
|
||
if not searched:
|
||
print('包用完了,停')
|
||
return
|
||
|
||
|
||
def run_client(city='广州'):
|
||
# 随机一个 client_id,领一条这个城市的任务,搜索结果仍进 hotel_area_search
|
||
ensure_task_client_id()
|
||
ensure_task_status()
|
||
create_tables()
|
||
city_row = get_city_row(city)
|
||
if not city_row:
|
||
return 'stop'
|
||
selected_city = task_selected_city(city)
|
||
if not selected_city:
|
||
return 'empty'
|
||
proxies = get_proxies(city)
|
||
if not proxies:
|
||
print('没有代理,停止', city)
|
||
return 'stop'
|
||
packets = get_packets()
|
||
if not packets:
|
||
print('没有可用 suggest 包')
|
||
return 'stop'
|
||
client_id = '%s%s' % (city, random.randint(10000000, 99999999))
|
||
print('client_id', client_id)
|
||
try:
|
||
task = get_task(VENDOR, USER, PWD, client_id, selected_city)
|
||
except task_requests.exceptions.RequestException as e:
|
||
print('领任务失败', client_id, e)
|
||
return 'stop'
|
||
if task['code'] != 0:
|
||
print('未领到', client_id, task['code'])
|
||
if task['code'] == 318:
|
||
return 'empty'
|
||
if task['code'] in STOP_CODES:
|
||
return 'stop'
|
||
return 'next'
|
||
data = task['data']
|
||
unique_id = data['uniqueId']
|
||
save_task_client(data, client_id)
|
||
hotel_id = str(data['hotelId'])
|
||
hotel_name = data['hotelName']
|
||
area_name = data['areaName']
|
||
hotel_star = data['hotelStar']
|
||
check_in = str(data['checkInDate'])[:10]
|
||
check_out = str(data['checkOutDate'])[:10]
|
||
print('任务', client_id, hotel_id, hotel_name, area_name, hotel_star, check_in, check_out)
|
||
if hotel_in_search(hotel_id, hotel_name):
|
||
shelf_hotel = get_shelf_hotel(hotel_id, area_name, check_in, check_out)
|
||
if shelf_hotel is None:
|
||
return 'next'
|
||
poi_id, hotel_name, pd, shelf_check_in, shelf_check_out = shelf_hotel
|
||
print('返回', area_name, client_id, poi_id, hotel_name, check_in, check_out, unique_id)
|
||
return area_name, client_id, poi_id, hotel_name, pd, check_in, check_out, unique_id, data
|
||
if not area_name:
|
||
print('任务没有区域', hotel_id, hotel_name)
|
||
return 'next'
|
||
star = star_filter_of(hotel_star)
|
||
if star is None:
|
||
print('没有这个星级的筛选', hotel_id, hotel_name, hotel_star)
|
||
return 'next'
|
||
hotel_star_param, star_filter = star
|
||
batch = latest_batch(area_name, star_filter, check_in, check_out)
|
||
if batch is None:
|
||
keyword_id = ensure_keyword(area_name, check_in, check_out, city if str(city).endswith('市') else str(city) + '市')
|
||
start_page = 0
|
||
else:
|
||
keyword_id, start_page = batch
|
||
if start_page >= PAGE_SKIP:
|
||
print('10页内没搜到,跳过', hotel_id, hotel_name, area_name, star_filter)
|
||
mark_task_missing(unique_id)
|
||
return 'cancel', client_id, data
|
||
state = {'proxy_index': 0}
|
||
packet_i = 0
|
||
while packet_i < len(packets):
|
||
packet = packets[packet_i]
|
||
print('包', packet['id'], '搜', area_name, star_filter, hotel_id, hotel_name)
|
||
result = run_one_keyword(area_name, packet, proxies, state, hotel_id, hotel_name, keyword_id, start_page, check_in, check_out, hotel_star_param, star_filter, city_row)
|
||
if result == 'stop':
|
||
return 'stop'
|
||
if result == 'dead':
|
||
packet_i += 1
|
||
again = latest_batch(area_name, star_filter, check_in, check_out)
|
||
if again is None:
|
||
start_page = 0
|
||
else:
|
||
keyword_id, start_page = again
|
||
if start_page >= PAGE_SKIP:
|
||
print('10页内没搜到,跳过', hotel_id, hotel_name, area_name, star_filter)
|
||
mark_task_missing(unique_id)
|
||
return 'cancel', client_id, data
|
||
continue
|
||
if result == 'found':
|
||
shelf_hotel = get_shelf_hotel(hotel_id, area_name, check_in, check_out)
|
||
if shelf_hotel is None:
|
||
return 'next'
|
||
poi_id, hotel_name, pd, shelf_check_in, shelf_check_out = shelf_hotel
|
||
print('返回', area_name, client_id, poi_id, hotel_name, check_in, check_out, unique_id)
|
||
return area_name, client_id, poi_id, hotel_name, pd, check_in, check_out, unique_id, data
|
||
if result == 'skip':
|
||
mark_task_missing(unique_id)
|
||
return 'cancel', client_id, data
|
||
if result == 'done':
|
||
mark_task_missing(unique_id)
|
||
return 'next'
|
||
print('包用完了,停')
|
||
return 'stop'
|
||
|
||
|
||
if __name__ == '__main__':
|
||
aa = run_client()
|
||
print(aa) |