upload hotel shelf and area search
This commit is contained in:
@@ -0,0 +1,184 @@
|
||||
import re
|
||||
import pymysql
|
||||
|
||||
class All_Setting():
|
||||
def __init__(self,host,port,db):
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.db = db
|
||||
|
||||
def remove_symbols(self,text):
|
||||
pattern = re.compile(r'[^\w\s]')
|
||||
return pattern.sub('', text)
|
||||
|
||||
def get_chinese(self,text,printTxt=False):
|
||||
# text = "海王星辰(广州智慧城店)"
|
||||
pattern = r'[^\w\s]'
|
||||
result = re.sub(pattern, '', text)
|
||||
if printTxt:
|
||||
print(result)
|
||||
return result
|
||||
|
||||
def get_shoppingmalls(self,sql):
|
||||
res_list = []
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
if conn:
|
||||
print('ok')
|
||||
cursor = conn.cursor()
|
||||
res = cursor.execute(sql)
|
||||
c2 = cursor.fetchall()
|
||||
return c2
|
||||
|
||||
def write_data(self,sql,data):
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
# 拿到游标
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.executemany(sql,data)
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
conn.close() # 添加连接关闭
|
||||
|
||||
|
||||
def update_data(self,sql):
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
# 拿到游标
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(sql)
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
conn.close() # 添加连接关闭
|
||||
|
||||
def update_data_many(self,sql, values):
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
# 拿到游标
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.executemany(sql, values)
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
conn.close() # 添加连接关闭
|
||||
|
||||
def write_data_one(self,sql,data):
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
# 拿到游标
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(sql,data)
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
conn.close() # 添加连接关闭
|
||||
|
||||
def get(self,sql):
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
# 拿到游标
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(sql)
|
||||
result = cursor.fetchall()
|
||||
cursor.close()
|
||||
conn.close() # 添加连接关闭
|
||||
return result
|
||||
|
||||
import json
|
||||
import time,requests
|
||||
|
||||
|
||||
def get_sign_meituan(url, dfpid, data):
|
||||
url_mtg = "http://118.89.119.254:18003/mt_jym_1_2"
|
||||
payload = json.dumps({
|
||||
"url": url,
|
||||
"data": data,
|
||||
"dfpid": dfpid,
|
||||
"method": "POST",
|
||||
"ua_type": "android"
|
||||
})
|
||||
headers = {
|
||||
'token': 'j760kynsopjfm0sa9ghjwsd',
|
||||
'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
response1 = requests.request("POST", url_mtg, headers=headers, data=payload)
|
||||
print(response1.text)
|
||||
mtgsig1 = response1.json()
|
||||
return str(mtgsig1)
|
||||
|
||||
def get_sign_waimai(url, dfpid, data):
|
||||
print('我是外卖mtg')
|
||||
|
||||
url_mtg = "http://118.89.119.254:18003/get_mt_tg_0507_jym"
|
||||
payload = json.dumps({
|
||||
"url": url,
|
||||
"data": data,
|
||||
"dfpid": dfpid,
|
||||
"method": "POST",
|
||||
# "ua_type": "android"
|
||||
})
|
||||
headers = {
|
||||
'token': 'j760kynsopjfm0sa9ghjwsd',
|
||||
'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
response = requests.request("POST", url_mtg, headers=headers, data=payload)
|
||||
mtgsig = response.json()
|
||||
print(mtgsig)
|
||||
return str(mtgsig)
|
||||
|
||||
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
|
||||
|
||||
|
||||
@@ -0,0 +1,591 @@
|
||||
# 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])
|
||||
@@ -0,0 +1,184 @@
|
||||
import re
|
||||
import pymysql
|
||||
|
||||
class All_Setting():
|
||||
def __init__(self,host,port,db):
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.db = db
|
||||
|
||||
def remove_symbols(self,text):
|
||||
pattern = re.compile(r'[^\w\s]')
|
||||
return pattern.sub('', text)
|
||||
|
||||
def get_chinese(self,text,printTxt=False):
|
||||
# text = "海王星辰(广州智慧城店)"
|
||||
pattern = r'[^\w\s]'
|
||||
result = re.sub(pattern, '', text)
|
||||
if printTxt:
|
||||
print(result)
|
||||
return result
|
||||
|
||||
def get_shoppingmalls(self,sql):
|
||||
res_list = []
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
if conn:
|
||||
print('ok')
|
||||
cursor = conn.cursor()
|
||||
res = cursor.execute(sql)
|
||||
c2 = cursor.fetchall()
|
||||
return c2
|
||||
|
||||
def write_data(self,sql,data):
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
# 拿到游标
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.executemany(sql,data)
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
conn.close() # 添加连接关闭
|
||||
|
||||
|
||||
def update_data(self,sql):
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
# 拿到游标
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(sql)
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
conn.close() # 添加连接关闭
|
||||
|
||||
def update_data_many(self,sql, values):
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
# 拿到游标
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.executemany(sql, values)
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
conn.close() # 添加连接关闭
|
||||
|
||||
def write_data_one(self,sql,data):
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
# 拿到游标
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(sql,data)
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
conn.close() # 添加连接关闭
|
||||
|
||||
def get(self,sql):
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
# 拿到游标
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(sql)
|
||||
result = cursor.fetchall()
|
||||
cursor.close()
|
||||
conn.close() # 添加连接关闭
|
||||
return result
|
||||
|
||||
import json
|
||||
import time,requests
|
||||
|
||||
|
||||
def get_sign_meituan(url, dfpid, data):
|
||||
url_mtg = "http://118.89.119.254:18003/mt_jym_1_2"
|
||||
payload = json.dumps({
|
||||
"url": url,
|
||||
"data": data,
|
||||
"dfpid": dfpid,
|
||||
"method": "POST",
|
||||
"ua_type": "android"
|
||||
})
|
||||
headers = {
|
||||
'token': 'j760kynsopjfm0sa9ghjwsd',
|
||||
'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
response1 = requests.request("POST", url_mtg, headers=headers, data=payload)
|
||||
print(response1.text)
|
||||
mtgsig1 = response1.json()
|
||||
return str(mtgsig1)
|
||||
|
||||
def get_sign_waimai(url, dfpid, data):
|
||||
print('我是外卖mtg')
|
||||
|
||||
url_mtg = "http://118.89.119.254:18003/get_mt_tg_0507_jym"
|
||||
payload = json.dumps({
|
||||
"url": url,
|
||||
"data": data,
|
||||
"dfpid": dfpid,
|
||||
"method": "POST",
|
||||
# "ua_type": "android"
|
||||
})
|
||||
headers = {
|
||||
'token': 'j760kynsopjfm0sa9ghjwsd',
|
||||
'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
response = requests.request("POST", url_mtg, headers=headers, data=payload)
|
||||
mtgsig = response.json()
|
||||
print(mtgsig)
|
||||
return str(mtgsig)
|
||||
|
||||
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
|
||||
|
||||
|
||||
+943
@@ -0,0 +1,943 @@
|
||||
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)
|
||||
+292
@@ -0,0 +1,292 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
|
||||
import requests
|
||||
from datetime import date
|
||||
from typing import Optional, Dict, Any, List
|
||||
from colorama import init, Fore, Style
|
||||
|
||||
init(autoreset=True)
|
||||
BASE_URL = "http://ktl-001.dsfdl-henan.xyz/openApi"
|
||||
TIMEOUT = 15
|
||||
# 任务接口直连,不走系统代理(本机 VPN):None 会被 requests 过滤掉,用空字符串才是真直连
|
||||
DIRECT_PROXIES = {'http': '', 'https': ''}
|
||||
LOG_DIR = "logs"
|
||||
os.makedirs(LOG_DIR, exist_ok=True)
|
||||
CODE_MSG = {
|
||||
0: ("success", "请求成功"),
|
||||
-1: ("server error", "服务本身错误"),
|
||||
-2: ("Authorization failed", "账号密码错误或认证方式错误"),
|
||||
305: ("现在没有任务了", "请稍后再试"),
|
||||
306: ("您今日没有任务了", "明天再来吧"),
|
||||
309: ("任务:开始", ""),
|
||||
310: ("任务:已经结束", ""),
|
||||
311: ("日期错误", "统计接口日期格式需严格 yyyy-MM-dd"),
|
||||
312: ("网络通信出错", "上传/取消时可重试"),
|
||||
313: ("任务还在处理中", "请勿重复提交"),
|
||||
314: ("任务正在获取中", "请稍后重试"),
|
||||
317: ("为了账号安全", "休息一会儿再做吧"),
|
||||
318: ("当前城市没任务啦", "换个城市试试"),
|
||||
319: ("服务维护中", "休息一会再做吧"),
|
||||
324: ("提交和获取的任务不一致", "uniqueId 需保持一致"),
|
||||
325: ("封号", ""),
|
||||
326: ("上传文本格式有错", "需 JSON 格式"),
|
||||
327: ("当前已领取任务", "请先完成再领新任务"),
|
||||
328: ("重复取消任务", ""),
|
||||
336: ("为了您的账号安全", "休息一下再来吧"),
|
||||
337: ("正在做的任务数量超过限额", ""),
|
||||
338: ("不在指定领取任务时间区间内", ""),
|
||||
339: ("网络通信失败", "请重试"),
|
||||
}
|
||||
|
||||
|
||||
def _color_code(code: int) -> str:
|
||||
if code == 0:
|
||||
return f"{Fore.GREEN}{code}"
|
||||
if code in CODE_MSG:
|
||||
return f"{Fore.YELLOW}{code}"
|
||||
return f"{Fore.RED}{code}"
|
||||
|
||||
|
||||
def _log_response(api_name: str, resp: Dict[str, Any]):
|
||||
code = resp.get("code", -1)
|
||||
msg_en, msg_zh = CODE_MSG.get(code, (resp.get("message", ""), "未知错误"))
|
||||
print(f"[{api_name}] 返回码: {_color_code(code)} {msg_en} | {msg_zh}")
|
||||
|
||||
|
||||
def _auth(username: str, password: str) -> Dict[str, str]:
|
||||
token = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
return {"Authorization": f"Basic {token}"}
|
||||
|
||||
|
||||
def _get(url: str, username: str, password: str, params: Optional[dict] = None) -> Dict[str, Any]:
|
||||
resp = requests.get(url, headers=_auth(username, password), params=params or {}, timeout=TIMEOUT, proxies=DIRECT_PROXIES)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
def _post(url: str, username: str, password: str, params: Optional[dict] = None, json_data: Any = None) -> Dict[
|
||||
str, Any]:
|
||||
resp = requests.post(url, headers=_auth(username, password), params=params or {}, json=json_data, timeout=TIMEOUT, proxies=DIRECT_PROXIES)
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
|
||||
def realtime_city_list(vendor_name: str,
|
||||
username: str,
|
||||
password: str,
|
||||
checkin_date: Optional[str] = None,
|
||||
checkout_date: Optional[str] = None) -> List[Dict[str, Any]]:
|
||||
url = f"{BASE_URL}/realtimeCityList"
|
||||
params = {"vendorName": vendor_name}
|
||||
if checkin_date:
|
||||
params["checkInDate"] = checkin_date
|
||||
if checkout_date:
|
||||
params["checkOutDate"] = checkout_date
|
||||
resp = _get(url, username, password, params)
|
||||
_log_response("realtime_city_list", resp)
|
||||
return resp.get("data", [])
|
||||
|
||||
|
||||
def realtime_checkinout_dates(vendor_name: str,
|
||||
username: str,
|
||||
password: str) -> List[Dict[str, str]]:
|
||||
url = f"{BASE_URL}/realtimeCheckInOutDateList"
|
||||
params = {"vendorName": vendor_name}
|
||||
resp = _get(url, username, password, params)
|
||||
_log_response("realtime_checkinout_dates", resp)
|
||||
return resp.get("data", [])
|
||||
|
||||
|
||||
def latest_cities(vendor_name: str, username: str, password: str) -> List[Dict[str, Any]]:
|
||||
dates = realtime_checkinout_dates(vendor_name, username, password)
|
||||
if not dates:
|
||||
return []
|
||||
latest = dates[0]
|
||||
return realtime_city_list(vendor_name, username, password,
|
||||
latest["checkInDate"], latest["checkOutDate"])
|
||||
|
||||
|
||||
def get_task(vendor_name: str,
|
||||
username: str,
|
||||
password: str,
|
||||
client_id: str,
|
||||
selected_city: str,
|
||||
checkin_date: Optional[str] = None,
|
||||
checkout_date: Optional[str] = None) -> Dict[str, Any]:
|
||||
url = f"{BASE_URL}/getTask"
|
||||
params = {"vendorName": vendor_name, "clientId": client_id, "selectedCity": selected_city}
|
||||
if checkin_date:
|
||||
params["checkInDate"] = checkin_date
|
||||
if checkout_date:
|
||||
params["checkOutDate"] = checkout_date
|
||||
resp = _get(url, username, password, params)
|
||||
_log_response("get_task", resp)
|
||||
return resp
|
||||
|
||||
|
||||
# 交任务
|
||||
def upload_task_datagram(original_vendor: str,
|
||||
unique_id: str,
|
||||
target_vendor: str,
|
||||
selected_city: str,
|
||||
client_id: str,
|
||||
username: str,
|
||||
password: str,
|
||||
datagram_json: dict,
|
||||
channel: Optional[str] = None) -> Dict[str, Any]:
|
||||
url = f"{BASE_URL}/uploadTaskDatagram"
|
||||
params = {"originalVendorName": original_vendor,
|
||||
"targetVendorName": target_vendor,
|
||||
"uniqueId": unique_id,
|
||||
"selectedCity": selected_city,
|
||||
"clientId": client_id}
|
||||
if channel:
|
||||
params["channel"] = channel
|
||||
print(datagram_json)
|
||||
print('==============')
|
||||
print((params))
|
||||
# 提交超时/连接失败重试,最多 3 次(含首次)
|
||||
for i in range(30):
|
||||
try:
|
||||
resp = _post(url, username, password, params, json_data=datagram_json)
|
||||
break
|
||||
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) as e:
|
||||
print(f"交任务失败,第{i + 1}次: {e}")
|
||||
if i == 2:
|
||||
raise
|
||||
_log_response("upload_task_datagram", resp)
|
||||
return resp
|
||||
|
||||
|
||||
# 取消任务
|
||||
def cancel_task(unique_id: str,
|
||||
cancel_status: int,
|
||||
vendor_name: str,
|
||||
selected_city: str,
|
||||
client_id: str,
|
||||
username: str,
|
||||
password: str) -> Dict[str, Any]:
|
||||
url = f"{BASE_URL}/cancelTask"
|
||||
params = {"uniqueId": unique_id,
|
||||
"cancelStatus": cancel_status,
|
||||
"vendorName": vendor_name,
|
||||
"selectedCity": selected_city,
|
||||
"clientId": client_id}
|
||||
resp = _post(url, username, password, params)
|
||||
_log_response("cancel_task", resp)
|
||||
return resp
|
||||
|
||||
|
||||
def get_one_task(VENDOR, USER, PWD, clientid, city_name):
|
||||
cities = latest_cities(VENDOR, USER, PWD)
|
||||
print(cities)
|
||||
city = None
|
||||
if city_name:
|
||||
for selected in cities:
|
||||
if city_name in selected['selectedCity']:
|
||||
city = selected['selectedCity']
|
||||
break
|
||||
if not city:
|
||||
return False
|
||||
else:
|
||||
city = cities[0]["selectedCity"]
|
||||
print(f"实际获取任务城市: ",city)
|
||||
# city = '上海市:10_上海市'
|
||||
task = get_task(VENDOR, USER, PWD, clientid, city)
|
||||
return task
|
||||
|
||||
|
||||
def upload_one_task(VENDOR, USER, PWD, clientid, task_data, data_json):
|
||||
upload_task_datagram(VENDOR, task_data.get('data').get('uniqueId'), VENDOR,
|
||||
task_data.get('data').get('selectedCity'), clientid, USER, PWD,
|
||||
data_json)
|
||||
|
||||
|
||||
def cancel_one_task(VENDOR, USER, PWD, clientid, task_data, cancel_status):
|
||||
return cancel_task(task_data.get('data').get('uniqueId'), cancel_status, VENDOR,
|
||||
task_data.get('data').get('selectedCity'), clientid, USER, PWD)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
'''
|
||||
使用实例
|
||||
'''
|
||||
USER = "thzn-datagram0001"
|
||||
PWD = "thzn-datagram0001"
|
||||
VENDOR = "mt-datagram"
|
||||
clientid = 'area85092537'
|
||||
|
||||
|
||||
'''
|
||||
VENDOR 可写死 项目标识
|
||||
USER 可写死 账号
|
||||
PWD 可写死 密码
|
||||
clientid 单人可写死(多线程需修改) 客户端id
|
||||
city 修改拿取城市的id 根据其他接口返回
|
||||
'''
|
||||
|
||||
# 一、实时获取任务酒店入离日期列表
|
||||
date_list = realtime_checkinout_dates(VENDOR, USER, PWD)
|
||||
print(date_list)
|
||||
|
||||
# 取其中一组入离日期查询有任务的城市列表,不传日期默认取最近一组
|
||||
# date_list[0] 即 {"checkInDate": "2023-05-15", "checkOutDate": "2023-05-16"}
|
||||
# city_list = realtime_city_list(VENDOR, USER, PWD, date_list[0]['checkInDate'], date_list[0]['checkOutDate'])
|
||||
# print(city_list)
|
||||
|
||||
# 任务获取
|
||||
task = get_one_task(VENDOR, USER, PWD, clientid,'广州')
|
||||
print(task)
|
||||
|
||||
'''
|
||||
VENDOR 可写死 项目标识
|
||||
USER 可写死 账号
|
||||
PWD 可写死 密码
|
||||
clientid 单人可写死(多线程需修改) 客户端id
|
||||
city 修改拿取城市的id 根据其他接口返回
|
||||
|
||||
|
||||
task_data为任务返回的数据json
|
||||
task_data={
|
||||
"code": 0,
|
||||
"message": "success",
|
||||
"data": {
|
||||
"hotelId": "938833723",
|
||||
"cityId": "50",
|
||||
"hotelName": "杭州拱墅大运河轻居酒店",
|
||||
"hotelAddress": "拱墅区湖州街555号顺网运河国际4号楼1层",
|
||||
"cityName": "杭州市",
|
||||
"checkInDate": "2025-12-01",
|
||||
"checkOutDate": "2025-12-02",
|
||||
"uniqueId": "20251130205014-32-32-3000001-443-411",
|
||||
"timeLeft": 1046,
|
||||
"hotelStar": "高档型",
|
||||
"selectedCity": "浙江省:50_杭州市",
|
||||
"areaType": "行政区/商圈",
|
||||
"areaName": "汽车北站、国际会展中心",
|
||||
"level": 0
|
||||
}
|
||||
}
|
||||
|
||||
data_json为采集获取到的json即上交数据
|
||||
'''
|
||||
|
||||
# 任务提交
|
||||
# task_data = json.loads(task)
|
||||
# data_json = {}#返回原始报文即可
|
||||
# upload_one_task(VENDOR, USER, PWD, clientid, task_data, data_json)
|
||||
|
||||
'''
|
||||
任务取消示例
|
||||
cancel_status 取消码:
|
||||
30 搜不到酒店(任务会移出队列,后续不会再领取到)
|
||||
31 满房(任务会移出队列,后续不会再领取到)
|
||||
task_data 为任务返回的数据json,唯一码与领取任务时保持一致
|
||||
'''
|
||||
# task_data = task
|
||||
# cancel_resp = cancel_one_task(VENDOR, USER, PWD, clientid, task_data, 30)
|
||||
# print(cancel_resp)
|
||||
+1057
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user