Files
caputure_packet/58.py
T
2026-10-28 14:32:10 +08:00

1276 lines
59 KiB
Python

import datetime
import re
import time
import json
import re
from urllib.parse import urlparse, parse_qs, unquote
from jsonpath_ng import parse
import requests
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker
from urllib.parse import quote_plus
import jsonpath
from mitmproxy.tools.main import mitmdump
import json, socket, os
from winproxy import ProxySetting
import newsetting
# ==================== 运行参数(改这里) ====================
USER = 'tk' # 区分不同抓包人,写入 market_*_tk_test / medince_item_hd 的 user 字段
# ============================================================
pwd = quote_plus("@7646!")
DB_URL = f"mysql+pymysql://root:Aliyun{pwd}@183.6.7.91:23016/headers_project?charset=utf8mb4"
engine = create_engine(
DB_URL,
pool_size=10,
max_overflow=20,
pool_recycle=3600,
echo=False
)
SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
tent = newsetting.All_Setting('192.168.5.2', 3307, 'headers_project')
tent1 = newsetting.All_Setting('183.6.7.91', 23016, 'tc_hotel')
tent3 = newsetting.All_Setting('183.6.7.91', 33016, 'xc_hotel')
tent2 = newsetting.All_Setting('183.6.7.91', 23016, 'tk_hotel')
tent4 = newsetting.All_Setting('192.168.5.5', 3306, 'headers_project')
menu_buffer = {}
# 已加 user 字段的表,写入时自动带上顶部 USER
USER_TABLES = {
'market_products_headers_tk_test',
'market_render_headers_tk_test',
'medince_item_hd',
}
# with open('H5guard.js','r',encoding='utf-8') as f:
# con = f.read()
def lat_lng_address(lat, lng):
lat_str = re.sub(r'^(..)', r'\1.', lat)
lng_str = re.sub(r'^(...)', r'\1.', lng)
headers = {
"Accept": "*/*",
"Accept-Language": "zh-CN,zh;q=0.9",
"Connection": "keep-alive",
"Referer": "https://lbs.qq.com/",
"Sec-Fetch-Dest": "script",
"Sec-Fetch-Mode": "no-cors",
"Sec-Fetch-Site": "same-site",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36",
"sec-ch-ua": "\"Not;A=Brand\";v=\"99\", \"Google Chrome\";v=\"139\", \"Chromium\";v=\"139\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"Windows\""
}
cookies = {
"yyb_muid": "2B9420A697D76AAC099C36DE968D6BB1",
"pac_uid": "0_Zex1sJDbceXPr",
"omgid": "0_Zex1sJDbceXPr",
"_qimei_uuid42": "19b1a143210100de671045edae6e9b6602f862c37c",
"_qimei_fingerprint": "04ed829d4c2c4a86985c30210cbb06bf",
"_qimei_q36": "",
"_qimei_h38": "527f2544671045edae6e9b660200000b419b1a",
"_qimei_i_3": "64e75f86945202dac99ff939588d20b5f4bdf2a54753578be5877c5f20907439676166943989e28d94b7",
"_qimei_i_2": "6ccc70faf638",
"_qimei_i_1": "6fc76d87975d06d9c493fa365c8573e4f2bbf0a0475d568be6892e582493206c616365913980b0dd8783c2f1",
"_qimei_q32": "",
"mpuv": "VTRdP8/JUBznpTT6FGt8lg==",
"pgv_pvid": "7583787552",
"_ga": "GA1.1.1934625953.1768292327",
"_ga_RPMZTEBERQ": "GS2.1.s1768359098$o2$g0$t1768359098$j60$l0$h0",
"lbs_refer": "9148bf92cf751e8b928c9e894b2d77c527c17b334a12b72674db53afab3092e0"
}
url = "https://h5gw.map.qq.com/ws/geocoder/v1/"
params = {
"key": "[你的key]",
"location": f"{lat_str},{lng_str}",
"apptag": "lbs_geocoder",
"output": "jsonp",
"callback": "jsonp_15d65f2c814701"
}
response = requests.get(url, headers=headers, cookies=cookies, params=params)
pattern = r'^\w+\s*&&\s*\w+\s*\(([\s\S]+?)\)\s*;$'
match = re.search(pattern, response.text)
if match:
json_str = match.group(1)
data = json.loads(json_str)
return data["result"]["address_component"]["city"][:-1]
def get_id(data):
poi_id = data['url'].split('/poi/')[1].split('?')[0]
vals_a = jsonpath.jsonpath(data, '$..poi_id_str') or []
vals_b = jsonpath.jsonpath(data, '$..wm_poi_view_id') or []
a = str(vals_a[0]) if vals_a else None
b = str(vals_b[0]) if vals_b else None
if a is None:
m = re.search(r'"poi_id_str"\s*:\s*"([^"]+)"', json.dumps(data, ensure_ascii=False))
a = m.group(1) if m else ""
if b is None:
m = re.search(r'"wm_poi_view_id"\s*:\s*"([^"]+)"', json.dumps(data, ensure_ascii=False))
b = m.group(1) if m else ""
print((a, b))
with engine.begin() as conn:
conn.execute(text(
"""
CREATE TABLE IF NOT EXISTS id_num_str (
id_num VARCHAR(255) NOT NULL,
id_str VARCHAR(155) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
"""
))
conn.execute(
text("INSERT INTO id_num_str (id_num, id_str) VALUES (:id_num, :id_str)"),
{"id_num": poi_id, "id_str": a}
)
def set_proxy():
# mac系统这段代码可以删除
ps = ProxySetting()
"""设置系统代理"""
ps.enable = True
ps.server = '127.0.0.1:8080'
ps.registry_write()
print('代理已经打开!')
def send_socket(da):
# 这个可以删除
a2 = json.dumps(da)
a3 = a2.encode()
s = socket.socket()
s.connect(('localhost', 12354))
s.sendall(a3)
s.close()
def get_script_path(script_name):
# 保留定位用
scriptpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), script_name)
print(os.path.join(os.path.dirname(os.path.abspath(__file__)), script_name))
return scriptpath
def reqdata(url2):
data = {}
# print(url2)
for i in url2.split('&'):
# print(i.split('='))
key = i.split('=')[0]
value = i.split('=')[1]
data[key] = value
# print(f'"{key}":"{value}",')
return data
def get_headers(headers):
headers2 = {}
for header, value in headers.items():
print(f"{header}: {value}")
headers2[header] = value
return headers2
# R5CTC17ZN2X
def choose2_api(url):
# 把你需要的url 放入列表
target_url = [
'https://wx.waimai.meituan.com/weapp/v11/search/globalpage',
"https://hcapi-wx.waimai.meituan.com/wxapp/v1/poi/product/smooth/render", # 外卖_买药_poi_render
"https://hcapi-wx.waimai.meituan.com/wxapp/v1/poi/sputag/products", # 外卖_买药_poi_products
"https://hcapi-wx.waimai.meituan.com/wxapp/v1/poi/food", # 外卖_买药_poi_food
"https://wx-shangou.meituan.com/wxapp/v1/poi/product/smooth/render", # 外卖_便利店_poi_render
"https://wx-shangou.meituan.com/wxapp/v1/poi/sputag/products", # 外卖_便利店_poi_products
"https://wx-shangou.meituan.com/wxapp/v1/poi/food", # 外卖_便利店_poi_food
"https://wx-shangou.meituan.com/wxapp/v10/product/smooth/render", # 外卖_便利店_poi_render2
"https://wx-shangou.meituan.com/wxapp/v8/poi/sputag/products", # 外卖_便利店_poi_products2
"https://wx-shangou.meituan.com/wxapp/v10/poi/food", # 外卖_便利店_poi_food2
"https://hcapi-wx.waimai.meituan.com/mtweapp/v1/poi/product/smooth/render", # 美团_买药_poi_render
"https://hcapi-wx.waimai.meituan.com/mtweapp/v1/poi/sputag/products", # 美团_买药_poi_products
"https://hcapi-wx.waimai.meituan.com/mtweapp/v1/poi/food", # 美团_买药_poi_food
"https://wx-shangou.meituan.com/mtweapp/v1/poi/product/smooth/render", # 美团_便利店poi_render
"https://wx-shangou.meituan.com/mtweapp/v1/poi/sputag/products", # 美团_便利店poi_products
"https://wx-shangou.meituan.com/mtweapp/v1/poi/food", # 美团_便利店poi_food
"https://wx-shangou.meituan.com/mtweapp/v10/product/smooth/render", # 美团_便利店poi_render2
"https://wx-shangou.meituan.com/mtweapp/v8/poi/sputag/products", # 美团_便利店poi_products2
"https://wx-shangou.meituan.com/mtweapp/v10/poi/food", # 美团_便利店poi_food2
"https://hcapi-wx.waimai.meituan.com/quickbuy/v1/poi/product/smooth/render", # 闪购_买药poi_render
"https://hcapi-wx.waimai.meituan.com/quickbuy/v1/poi/sputag/products", # 闪购_买药poi_products
"https://hcapi-wx.waimai.meituan.com/quickbuy/v1/poi/food", # 闪购_买药poi_food
"https://wx-shangou.meituan.com/quickbuy/v1/poi/product/smooth/render", # 闪购_便利店_poi_render
"https://wx-shangou.meituan.com/quickbuy/v1/poi/sputag/products", # 闪购_便利店_poi_products
"https://wx-shangou.meituan.com/quickbuy/v1/poi/food", # 闪购_便利店_poi_food
'https://wx.waimai.meituan.com/weapp/v1/poi/food', # 美团美食food
# 'https://wx.waimai.meituan.com/weapp/v1/poi/info', # 美团美食info
'https://wx.waimai.meituan.com/weapp/shop/v1/poi/productlist', # 美团美食productlist
'https://wx.waimai.meituan.com/weapp/poi/food/render', # 美团美食rende
'https://ihotel.meituan.com/coresearch/v2/hotel/list',
'https://ihotel.meituan.com/group/v1/poi/',
'https://wx.waimai.meituan.com/weapp/v1/food/payattention',
'https://wx.waimai.meituan.com/weapp/v1/user/favorite/getmyfavorite',
'https://i.waimai.meituan.com/openh5/user/queryFavorite',
'https://ihotel.meituan.com/hbsearch/v4/deal/search/suggest',
"https://i.waimai.meituan.com/external/ajax/poi/",
# "https://i.waimai.meituan.com/openh5/poi/info?",
# "https://ihotel.meituan.com/naruto/hotel/core/router/shelf", # 美团酒店详情1
"https://ihotel.meituan.com/productapi/v3/prepayList", # 美团酒店详情2
"https://mall.meituan.com/api/c/poi", # 小象超市程序分类
"https://hcapi-wx.waimai.meituan.com/storm/graphql/tile/query/from_app_drug_detail", # 美团药店商品详情
"https://hcapi-wx.waimai.meituan.com/storm/bridge/king-kong-page", # 便利店商品详情原始优化包
"/search/miniprogram", # 美团全局搜索
"https://apimobile.meituan.com/group/v1/deal/search/suggest/20", # 美团全局搜索
"v2/poi/product/info", # 便利店商品详情原始优化包
"v2/poi/discount/float", # 美团全局搜索
"https://quic-hotel.17u.cn/api/main/flow/detail/data/v3", # 同程旅行的酒店详情
"https://apimobile.meituan.com/group/v4/poi/search/miniprogram",
"https://m.ctrip.com/restapi/soa2/33278", # 携程酒店详情
'https://m.ctrip.com/restapi/soa2/35021',
'https://wx-shangou.meituan.com/mtweapp/v1/search/inshop/products',# 美团店铺内搜索
# 歪马部分
"https://drunkhorse.meituan.com/api/v2/category/page/main", # 类比food
"https://drunkhorse.meituan.com/api/v2/category/page/products", # products
"https://drunkhorse.meituan.com/api/v2/category/page/render" # render
"https://deliverycommonapi.peisong.meituan.com/address/search", # 美团地址搜索
"https://m5-zb.amap.com/ws/boss/enterprise/open/car_list/v2", # 网约车冒泡报价(车型列表+价格)
"https://m5-zb.amap.com/ws/boss/enterprise/open/check_multi_order", # 网约车订单状态查询(司机应答时间)
"https://m5-zb.amap.com/ws/boss/order/car/order/detail", # 网约车订单详情(应答车型/供应商/车牌)
"https://m5-zb.amap.com/ws/boss/order/car/order/driver/location", # 网约车司机定位追踪(接驾距离/时长)
"https://guide-acs.m.taobao.com/gw/mtop.taobao.mbis.address.keyword.search/", # 淘宝地址搜索
"https://waimai-guide.ele.me/gw/mtop.alsc.address.poi.keywordsearch", # 饿了么地址搜索
"https://klmall.meituan.com/wxmall/api/goods/search?gtCityId", # klmall商品搜索
"https://wxapp.qunar.com/h_venus", # 去哪儿酒店
"passenger.elevatorPublish.pageRefresh", # 哈啰顺风车-拼座包(身份+起终点)
"/ws/amap/ride/hitch/car_list", # 高德顺风车-身份包(拼座报价)
"poi.map.xiaojukeji.com/mapapi/textsearch", # 滴滴顺风车-身份包(地址搜索)
"https://meishi.meituan.com/i/certificate/foodsafety",
"https://meishi.meituan.com/i/api/certificate/foodsafety/info",
"https://drunkhorse.meituan.com/api/v1/promotion/coupon/store/list3",
"https://drunkhorse.meituan.com/api/v4/product/spu/listByPage",
"https://drunkhorse.meituan.com/api/v3/product/spu/search", # 歪马商品搜索
]
for b in target_url:
if b in url:
print('*********hit************')
print(url)
return True
return False
def insert_sqltc(table_name, da):
sql = """INSERT INTO {table_name}
(apmat, ip, json_data, title, channel, is_ok, req_count)
VALUES (%s, %s, %s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
json_data = VALUES(json_data), is_ok = null""".format(table_name=table_name)
print(sql, da)
tent1.write_data_one(sql, da)
def insert_sqltc1(table_name, da):
sql = """INSERT INTO {table_name}
(apmat, ip, json_data, title, channel, is_ok, req_count)
VALUES (%s, %s, %s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
json_data = VALUES(json_data), is_ok = null""".format(table_name=table_name)
print(sql, da)
tent3.write_data_one(sql, da)
def insert_waima_sql(table_name,da):
sql = """INSERT INTO {table_name}
(dfpid, ip, json_data, title, channel, is_ok, req_count)
VALUES (%s, %s, %s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
json_data = VALUES(json_data), is_ok = null""".format(table_name=table_name)
print(sql,da)
tent4.write_data_one(sql, da)
def _parse_ctrip_body(data):
if isinstance(data, dict):
return data
if isinstance(data, str) and data.strip():
try:
return json.loads(data)
except json.JSONDecodeError:
pass
return {}
def _cookie_val(cookie_str, key):
if not cookie_str:
return None
for part in str(cookie_str).replace(';', ',').split(','):
part = part.strip()
if part.startswith(key + '='):
return part.split('=', 1)[1].strip()
return None
def _extract_ctrip_session(url, headers, data):
"""从携程 33278/35021 请求里解析 run_task 需要的账号字段。"""
body = _parse_ctrip_body(data)
head = body.get('head') or {}
cookie = headers.get('cookie') or headers.get('Cookie') or ''
guid = _cookie_val(cookie, 'GUID')
if not guid:
qs = parse_qs(urlparse(url).query)
guid = (qs.get('_fxpcqlniredt') or [None])[0]
if not guid:
guid = head.get('cid') or head.get('guid')
auth = head.get('auth') or ''
udl = headers.get('udl') or headers.get('UDL') or _cookie_val(cookie, '_udl')
duid = headers.get('duid') or headers.get('DUID') or _cookie_val(cookie, 'DUID')
openid = headers.get('x-wx-openid') or headers.get('X-Wx-Openid')
ua = headers.get('user-agent') or headers.get('User-Agent')
referer = headers.get('referer') or headers.get('Referer') or ''
referer_ver = None
app_id = 'wx0e6ed4f51db9d078'
m = re.search(r'servicewechat\.com/([^/]+)/(\d+)/', referer)
if m:
app_id = m.group(1)
referer_ver = m.group(2)
for ext in (head.get('extension') or []):
if ext.get('name') == 'appId' and ext.get('value'):
app_id = ext['value']
if ext.get('name') == 'openid' and ext.get('value') and not openid:
openid = ext['value']
return {
'guid': guid,
'auth': auth,
'udl': udl,
'duid': duid,
'openid': openid,
'ua': ua,
'referer_ver': referer_ver,
'app_id': app_id,
}
def insert_xc_hotel_hd(url, headers, data, title):
"""抓包入库 xc_hotel.xc_hotel_hd,供携程 run_task.py 读取。"""
session = _extract_ctrip_session(url, headers, data)
if not session.get('duid') and not session.get('guid'):
print('[xc_hotel] 跳过:未解析到 duid/guid')
return
if not session.get('auth'):
print('[xc_hotel] 跳过:未解析到 auth(需抓到 33278/35021 请求体)')
return
workid = datetime.date.today().strftime('%Y%m%d')
package_name = title or '携程抓包'
row_id = None
if session.get('duid'):
esc_duid = session['duid'].replace("'", "''")
rows = tent3.get_shoppingmalls(
f"SELECT id FROM xc_hotel_hd WHERE duid = '{esc_duid}' LIMIT 1"
)
if rows:
row_id = rows[0][0]
if row_id is None and session.get('guid'):
esc_guid = session['guid'].replace("'", "''")
rows = tent3.get_shoppingmalls(
f"SELECT id FROM xc_hotel_hd WHERE guid = '{esc_guid}' LIMIT 1"
)
if rows:
row_id = rows[0][0]
args = (
workid,
package_name,
session.get('guid'),
session.get('auth'),
session.get('udl'),
session.get('duid'),
session.get('openid'),
session.get('ua'),
session.get('referer_ver'),
session.get('app_id'),
)
if row_id:
sql = '''
UPDATE xc_hotel_hd SET
workid=%s, package_name=%s, guid=%s, auth=%s, udl=%s, duid=%s,
openid=%s, ua=%s, referer_ver=%s, app_id=%s,
is_ok=NULL, is_active=1
WHERE id=%s
'''
tent3.write_data_one(sql, args + (row_id,))
else:
sql = '''
INSERT INTO xc_hotel_hd
(workid, package_name, guid, auth, udl, duid, openid, ua, referer_ver, app_id, is_active)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 1)
'''
tent3.write_data_one(sql, args)
print(f"[xc_hotel] 已写入 xc_hotel_hd duid={session.get('duid')} guid={session.get('guid')}")
def insert_sql1(table_name, da):
sql = """INSERT INTO {table_name}
(dfpid, ip, json_data, title, channel, is_ok, req_count)
VALUES (%s, %s, %s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
json_data = VALUES(json_data), is_ok = null""".format(table_name=table_name)
print(sql, da)
tent.write_data_one(sql, da)
def insert_sql(table_name, da):
if table_name in USER_TABLES:
sql = """INSERT INTO {table_name}
(dfpid, ip, json_data, title, channel, is_ok, req_count,lat,lng,`user`)
VALUES (%s, %s, %s, %s, %s, %s, %s,%s,%s,%s)
ON DUPLICATE KEY UPDATE
json_data = VALUES(json_data), is_ok = null, `user` = VALUES(`user`)""".format(table_name=table_name)
da = da + (USER,)
else:
sql = """INSERT INTO {table_name}
(dfpid, ip, json_data, title, channel, is_ok, req_count,lat,lng)
VALUES (%s, %s, %s, %s, %s, %s, %s,%s,%s)
ON DUPLICATE KEY UPDATE
json_data = VALUES(json_data), is_ok = null""".format(table_name=table_name)
print(sql, da)
tent.write_data_one(sql, da)
def insert_sql2(table_name, da):
if table_name in USER_TABLES:
sql = """INSERT INTO {table_name}
(dfpid, ip, json_data, title, channel, is_ok, req_count,`user`)
VALUES (%s, %s, %s, %s, %s, %s, %s,%s)
ON DUPLICATE KEY UPDATE
json_data = VALUES(json_data), is_ok = null, `user` = VALUES(`user`)""".format(table_name=table_name)
da = da + (USER,)
else:
sql = """INSERT INTO {table_name}
(dfpid, ip, json_data, title, channel, is_ok, req_count)
VALUES (%s, %s, %s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE
json_data = VALUES(json_data), is_ok = null""".format(table_name=table_name)
tent.write_data_one(sql, da)
def insert_sql3(table_name, da):
sql = """INSERT INTO {table_name}
(dfpid, ip, json_data, title, channel, is_ok, req_count,lat,lng,req)
VALUES (%s, %s, %s, %s, %s, %s, %s,%s,%s,%s)
ON DUPLICATE KEY UPDATE
json_data = VALUES(json_data), is_ok = null""".format(table_name=table_name)
print(sql, da)
tent.write_data_one(sql, da)
def rec_headers(url, headers, data, title, ip_address, req=None):
try:
dfpid = eval(headers['mtgsig'])['a3'] + title
except:
pass
try:
wm_actual_latitude = data['wm_actual_latitude']
wm_actual_longitude = data['wm_actual_longitude']
except:
pass
# hd_city=lat_lng_address(wm_actual_latitude,wm_actual_longitude)
out_data = (url, headers, data)
if '/v1/poi/product/smooth/render' in url or '/v10/product/smooth/render' in url:
channel = 'render'
da = (dfpid, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0, wm_actual_latitude,
wm_actual_longitude)
insert_sql('market_render_headers_tk_test', da)
elif 'v1/search/inshop/products' in url:
channel = '店内search'
da = (dfpid, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0, wm_actual_latitude,
wm_actual_longitude)
insert_sql('market_products_headers_tk_test_search', da)
elif '/v1/poi/sputag/products' in url or '/v8/poi/sputag/products' in url:
channel = 'products'
da = (dfpid, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0, wm_actual_latitude,
wm_actual_longitude)
insert_sql('market_products_headers_tk_test', da)
elif '/v1/poi/food' in url or '/v10/poi/food' in url:
channel = 'food'
da = (dfpid, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
insert_sql1('market_food_headers', da)
elif '/naruto/hotel/core/router/shelf' in url or 'productapi/v3/prepayList' in url:
channel = 'hotel'
da = (dfpid, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
insert_sql1('hotel_hd', da)
elif "https://hcapi-wx.waimai.meituan.com/storm/graphql/tile/query/from_app_drug_detail" in url:
channel = 'item'
title = '便利店商品详情原始优化包'
da = (dfpid, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
insert_sql2('medince_item_hd', da)
elif "https://apimobile.meituan.com/group/v4/poi/search/miniprogram" in url:
channel = 'search'
title = '美团全局搜索带结果'
da = (dfpid, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0, req)
insert_sql3('search_miniprogram_hd', da)
# elif "https://wx-shangou.meituan.com/mtweapp/v2/poi/product/info" in url:
# channel = 'newretail'
# da = (dfpid,ip_address,json.dumps(out_data,ensure_ascii=False),title,channel,None,0)
# insert_sql('medince_item_hd', da)
elif '/v1/food/payattention' in url:
channel = 'payattention'
da = (dfpid, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
print(da)
insert_sql2('market_payattention_hd', da)
elif '/bridge/king-kong-page' in url:
channel = 'king-kong-page'
da = (dfpid, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
print(da)
insert_sql('king_kong', da)
elif 'category/list/v4' in url:
channel = '分类'
dfpid = eval(headers['mtgsig'])['a3'] + channel
da = (dfpid, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
print(da)
insert_sql('elephant_headers', da)
elif 'list/category/v8' in url:
channel = '详情'
dfpid = eval(headers['mtgsig'])['a3'] + channel
da = (dfpid, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
print(da)
insert_sql('elephant_headers', da)
elif 'group/v4/poi/search/miniprogram' in url:
channel = '美团全局搜索'
dfpid = eval(headers['mtgsig'])['a3'] + channel
da = (dfpid, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
print(da)
insert_sql('search_miniprogram_hd', da)
elif 'https://apimobile.meituan.com/group/v1/deal/search/suggest/20' in url:
channel = '美团全局搜索'
dfpid = eval(headers['mtgsig'])['a3'] + channel
da = (dfpid, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
print(da)
insert_sql1('search_suggest_hd', da)
elif 'v2/poi/product/info' in url:
channel = 'product_info'
dfpid = eval(headers['mtgsig'])['a3'] + channel
da = (dfpid, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
print(da)
insert_sql('market_product_info_headers', da)
elif 'v2/poi/discount/float' in url:
channel = 'discount_float'
dfpid = eval(headers['mtgsig'])['a3'] + channel
da = (dfpid, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
print(da)
insert_sql('market_discount_float_headers', da)
elif 'api/main/flow/detail/data/v3' in url:
channel = 'tc_hotel'
apmat = headers['apmat'].split('|')[0]
# ["data"]["roomRpInfo"]["rpMap"]["92327168A3A526802847A0Afee14bf2d4c1ce2125a8caec4bdd43a5"]["outPriceExcTaxBeforeCSum"]
expr = parse("$.data.roomRpInfo.rpMap.*.outPriceExcTaxBeforeCSum")
values = [m.value for m in expr.find(req)]
if '' in values:
return 0
else:
da = (apmat, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
print(da)
insert_sqltc('tc_hotel_hd', da)
elif 'getHotelRoomListInland' in url or 'getHotelRoomPopInfo' in url:
insert_xc_hotel_hd(url, headers, data, title)
def rec_meishi(da, channel_name):
order_name, wm_ctype, dfpid, ip_address, json_data = da
sql1 = f"select id from meishi_headers where dfpid = '{dfpid}'"
kk = tent.get_shoppingmalls(sql1)
if channel_name == 'food':
if bool(kk) is False:
insert_sql = """
insert into meishi_headers (order_name,wm_ctype,dfpid,ip_address,food_data) values (%s,%s,%s,%s,%s) ON DUPLICATE KEY UPDATE
food_data = VALUES(food_data);
"""
tent.write_data_one(insert_sql, da)
else:
idd = kk[0][0]
update_sql = f"""
update meishi_headers set food_data = '{json_data}' where id = {idd}
"""
tent.update_data(update_sql)
elif channel_name == 'products':
if bool(kk) is False:
insert_sql = """
insert into meishi_headers (order_name,wm_ctype,dfpid,ip_address,products_data) values (%s,%s,%s,%s,%s) ON DUPLICATE KEY UPDATE
food_data = VALUES(food_data);
"""
tent.write_data_one(insert_sql, da)
else:
idd = kk[0][0]
update_sql = f"""
update meishi_headers set products_data = '{json_data}' where id = {idd}
"""
tent.update_data(update_sql)
pass
elif channel_name == 'render':
if bool(kk) is False:
insert_sql = """
insert into meishi_headers (order_name,wm_ctype,dfpid,ip_address,render_data) values (%s,%s,%s,%s,%s) ON DUPLICATE KEY UPDATE
food_data = VALUES(food_data);
"""
tent.write_data_one(insert_sql, da)
else:
idd = kk[0][0]
update_sql = f"""
update meishi_headers set render_data = '{json_data}' where id = {idd}
"""
tent.update_data(update_sql)
pass
def response(flow):
false = ''
null = ''
true = ''
if flow.request.headers.get('Upgrade',
'').lower() == 'websocket' and 'wpush.meituan.com/websocket/' in flow.request.url:
# 拒绝websocket
# 这里可以修改返回的状态码和原因,默认是403 Forbidden
flow.response = flow.response
flow.response.status_code = 403
flow.response.reason = 'Forbidden'
# 结束流,不再转发请求
flow.kill(flow.response)
# if "https://appsec-mobile.meituan.com/h5guard/H5guard.js" in flow.request.url or "https://s3plus.meituan.net/v1/mss_e6aa2b2c35b3432988a7a61f7ed79d37/h5guard/H5guard.js" in flow.request.url:
# # 替换原始响应体
# print('找到替换的目标')
# flow.response.text = con
# # 确保设置正确的 Content-Type 头
# flow.response.headers["Content-Type"] = "application/javascript"
if 'https://h5.waimai.meituan.com/waimai/mindex/menu?' in flow.request.url or 'https://cactivityapi-sc.waimai.meituan.com/' in flow.request.url or 'https://yiyao-h5.meituan.com/web/merchantQualification.html?' in flow.request.url or 'https://meishi.meituan.com/meishi/poi/index.html?' in flow.request.url or 'https://titan-ws.pinduoduo.com' in flow.request.url:
# js注入
print(flow.request.url)
if flow.response.headers.get('Content-Type', '').startswith('text/html'):
# 注入JavaScript代码
js_code = """
<script>
alert('MARKET_程序启动正常,可以准备开始');
!(function () {
// 获取dfpid
function getCookieValue(cookieName) {
const cookies = document.cookie.split('; ');
for (let item of cookies) {
if (item.includes(cookieName)) {
// 对命中的 item 进行切分,并返回第 0 个部分的值
const keyValuePair = item.split('-')[0]; // 先切分 "-"
return keyValuePair.split('=')[1]; // 再切分 "=",取值部分
}
}
return null;
}
// 调用函数并获取 "WEBDFPID" 的值
const result = getCookieValue("WEBDFPID");
const targetClientId = result+'_pc'
console.log(targetClientId); // 输出:abcdefg
// WebSocket 连接
const ws = new WebSocket('wss://mtworker.tech:5003/');
// 连接成功建立的回调方法
ws.onopen = function (event) {
console.log("Connected to server");
ws.send(result+"_web"); // 发送客户端ID
};
// 接收消息的回调方法
ws.onmessage = function (event) {
console.log(event.data);
let _data1 = event.data;
let _data2 = JSON.parse(_data1);
let _data3 = _data2.datas;
let _data4 = JSON.parse(_data3);
console.log(typeof (_data4));
console.log(_data4);
// 调用函数获取 mtgsig 值
let mtg = getValue(_data4);
let cook = document.cookie;
let ua = window.navigator.userAgent;
// 构造返回数据
let rt_data = {
cookie: cook,
userAgent: ua,
mtgsig: mtg,
};
// 将消息和目标客户端 ID 拼接成字符串格式:targetClientId:message
let messageWithTarget = `${targetClientId}:${JSON.stringify(rt_data)}`;
ws.send(messageWithTarget); // 发送消息到目标客户端
};
// 连接关闭的回调方法
ws.onclose = function (event) {
console.log("Disconnected from server");
};
// 获取 mtgsig 值的函数
function getValue(daa) {
H5guard.initWithKey({ appKey:'dcf7c9fd764e553cf16d99551f67c92916edf992353a0c37b8359eba19d53524'});
var mts2 = H5guard.sign(daa);
console.log(daa);
return daa;
}
})();
</script>
"""
flow.response.content = flow.response.content.replace(b'</head>', js_code.encode('utf-8') + b'</head>')
url = (flow.request.url)
t2 = choose2_api(url)
client_info = {
"ip": flow.client_conn.address[0],
"port": flow.client_conn.address[1],
"tls_version": getattr(flow.client_conn.tls_version, "name", None),
"cipher": getattr(flow.client_conn.cipher, "name", None),
"timestamp": flow.client_conn.timestamp_start
}
# print(client_info)
if t2:
headers = dict(flow.request.headers)
data = flow.request.content
data2 = data.decode('utf8')
try:
if flow.request.method == "POST":
data3 = reqdata(data2)
else:
data3 = data2
except:
data3 = json.loads(data2)
req2 = flow.response.content
req = req2.decode('utf-8')
print(req)
if not (
"https://ihotel.meituan.com/productapi/v3/prepayList" in url or "https://ihotel.meituan.com/naruto/hotel/core/router/shelf" in url):
ress = json.loads(req)
title = url.split('?')[0].split('/')[-1]
ip_address = client_info['ip']
try:
dfpid = eval(headers['mtgsig'])['a3']
print(dfpid)
except:
pass
if 'https://hcapi-wx.waimai.meituan.com/wxapp/' in url:
# 外卖买药接口
title = '外卖-买药接口'
print(title)
rec_headers(url, headers, data3, title, ip_address)
if 'https://drunkhorse.meituan.com/api/v1/promotion/coupon/store/list3' in url or 'https://drunkhorse.meituan.com/api/v4/product/spu/listByPage' in url or ('https://drunkhorse.meituan.com/api/v3/product/spu/search' in url and 'suggest_info' not in url):
params = dict(flow.request.query)
status_code = flow.response.status_code
req = flow.response.content.decode('utf-8')
out_data = {'headers': headers, 'url': flow.request.url, 'method': flow.request.method, 'params': params,
'data': data2, 'status_code': status_code}
json_data = json.dumps(out_data, ensure_ascii=False)
dfpid = eval(headers['mtgsig'])['a3']
if 'promotion/coupon/store/list3' in url:
title = '歪马券列表'
channel = 'coupon_list'
da = (dfpid + title, ip_address, json_data, title, channel, None, 0)
insert_waima_sql('waima_coupon_list_headers', da)
elif 'product/spu/search' in url:
title = '歪马商品搜索'
channel = 'search'
da = (dfpid + title, ip_address, json_data, title, channel, None, 0)
insert_waima_sql('waima_search_headers', da)
else:
title = '歪马商品详情'
channel = 'spu_detail'
da = (dfpid + title, ip_address, json_data, title, channel, None, 0)
insert_waima_sql('waima_spu_detail_headers', da)
return
elif 'https://hcapi-wx.waimai.meituan.com/quickbuy/' in url:
# 闪购买药接口
title = '闪购-买药接口'
rec_headers(url, headers, data3, title, ip_address)
elif 'https://hcapi-wx.waimai.meituan.com/mtweapp' in url:
# 美团买药接口
title = '美团-买药接口'
rec_headers(url, headers, data3, title, ip_address)
if 'https://wx-shangou.meituan.com/wxapp/' in url:
# 外卖小程序便利店
title = '外卖-美团_便利店'
rec_headers(url, headers, data3, title, ip_address)
elif 'https://wx-shangou.meituan.com/mtweapp/' in url:
# 美团便利店
title = '美团-美团_便利店'
rec_headers(url, headers, data3, title, ip_address)
elif 'https://apimobile.meituan.com/group/v4/poi/search/miniprogram' in url:
# 美团便利店
title = '美团-全局搜索'
rec_headers(url, headers, data3, title, ip_address, req)
if 'https://mall.meituan.com/api/c/poi/' in url:
# 小象超市
title = '小象'
rec_headers(url, headers, data3, title, ip_address)
if 'group/v4/poi/search/miniprogram' in url:
# 小象超市
title = '美团全局搜索'
rec_headers(url, headers, data3, title, ip_address)
if 'https://apimobile.meituan.com/group/v1/deal/search/suggest/20' in url:
# 小象超市
title = '美团全局搜索'
rec_headers(url, headers, data3, title, ip_address)
elif 'https://wx-shangou.meituan.com/quickbuy/' in url:
# 闪购-美团_便利店
title = '闪购-美团_便利店'
rec_headers(url, headers, data3, title, ip_address)
elif '/v1/search/inshop/products' in url:
title = '便利店_店内搜索'
rec_headers(url, headers, data3, title, ip_address)
#
#
#
if 'https://wx.waimai.meituan.com/weapp/v1/poi/food' in url:
k = menu_buffer.get(dfpid, {})
k['food'] = (headers, flow.request.url, data3)
menu_buffer[dfpid] = k
if 'food' in k and 'productlist' in k and 'render' in k:
das = (k['food'], k['productlist'], k['render'])
da = (dfpid, json.dumps(das), 0)
# and is_ok = null
sql = """
insert into menu_hd2 (title, hd_data, count_req) values (%s, %s, %s) on duplicate key update hd_data = values(hd_data), is_ok = null
"""
tent.write_data_one(sql, da)
elif 'https://wx.waimai.meituan.com/weapp/shop/v1/poi/productlist' in url:
k = menu_buffer.get(dfpid, {})
k['productlist'] = (headers, flow.request.url, data3)
menu_buffer[dfpid] = k
if 'food' in k and 'productlist' in k and 'render' in k:
das = (k['food'], k['productlist'], k['render'])
da = (dfpid, json.dumps(das), 0)
sql = """
insert into menu_hd2 (title, hd_data, count_req) values (%s, %s, %s) on duplicate key update hd_data = values(hd_data)
"""
tent.write_data_one(sql, da)
elif 'https://wx.waimai.meituan.com/weapp/poi/food/render' in url:
k = menu_buffer.get(dfpid, {})
k['render'] = (headers, flow.request.url, data3)
menu_buffer[dfpid] = k
if 'food' in k and 'productlist' in k and 'render' in k:
das = (k['food'], k['productlist'], k['render'])
da = (dfpid, json.dumps(das), 0)
sql = """
insert into menu_hd2 (title, hd_data, count_req) values (%s, %s, %s) on duplicate key update hd_data = values(hd_data)
"""
tent.write_data_one(sql, da)
# elif 'https://wx.waimai.meituan.com/weapp/' in url:
# format_today = str(datetime.date.today()).replace('-', '')
# channel = '美食' + format_today
# out_data = {'headers': headers, 'url': flow.request.url, 'method': flow.request.method, 'data': data3,
# 'channel': channel,
# 'request': ress}
# path = os.path.join(r'headers_data',channel,dfpid,title)
# if os.path.exists(path) is False:
# os.makedirs(path)
# with open(f'{path}/{title}','w',encoding='utf-8') as f:
# f.write(json.dumps(out_data))
elif 'https://wx.waimai.meituan.com/weapp/v1/poi/info' in url:
format_today = str(datetime.date.today()).replace('-', '')
channel = '店铺详情' + format_today
out_data = {'headers': headers, 'url': flow.request.url, 'method': flow.request.method, 'data': data3,
'channel': channel,
'request': ress}
path = os.path.join(r'headers_data', channel, dfpid, title)
if os.path.exists(path) is False:
os.makedirs(path)
with open(f'{path}/{title}', 'w', encoding='utf-8') as f:
f.write(json.dumps(out_data))
elif 'https://wx.waimai.meituan.com/weapp/v1/poi/info' in url:
format_today = str(datetime.date.today()).replace('-', '')
channel = '店铺详情' + format_today
out_data = {'headers': headers, 'url': flow.request.url, 'method': flow.request.method, 'data': data3,
'channel': channel,
'request': ress}
path = os.path.join(r'headers_data', channel, dfpid, title)
if os.path.exists(path) is False:
os.makedirs(path)
with open(f'{path}/{title}', 'w', encoding='utf-8') as f:
f.write(json.dumps(out_data))
elif 'https://wx.waimai.meituan.com/weapp/v11/search/globalpage' in url:
format_today = str(datetime.date.today()).replace('-', '')
channel = '美食search' + format_today
out_data = {'headers': headers, 'url': flow.request.url, 'method': flow.request.method, 'data': data3,
'channel': channel,
'request': ress}
path = os.path.join(r'headers_data', channel, dfpid, title)
if os.path.exists(path) is False:
os.makedirs(path)
with open(f'{path}/{title}', 'w', encoding='utf-8') as f:
f.write(json.dumps(out_data))
hd = (headers, flow.request.url, data3)
da = (dfpid, json.dumps(hd), 0)
sql = """
insert into search_globalpage_hd (title,hd_data,count_req) values (%s,%s,%s)
on duplicate key update hd_data = values(hd_data), is_ok = null
"""
tent.write_data_one(sql, da)
if "https://ihotel.meituan.com/productapi/v3/prepayList" in url or "https://ihotel.meituan.com/naruto/hotel/core/router/shelf" in url:
title = '美团酒店详情'
rec_headers(url, headers, data2, title, ip_address)
if "https://hcapi-wx.waimai.meituan.com/storm/graphql/tile/query/from_app_drug_detail" in url:
title = '美团药店商品详情'
rec_headers(url, headers, data3, title, ip_address)
if "https://hcapi-wx.waimai.meituan.com/storm/bridge/king-kong-page" in url:
title = '美团药店分类'
rec_headers(url, headers, data3, title, ip_address)
match = re.search(r'category_name=([^&]+)', req)
category_name = unquote(unquote((match.group(1)))) # xxx
base_path = os.path.join(r'./headers_data/药店分类', category_name)
if not os.path.exists(base_path):
os.makedirs(base_path)
print(category_name)
with open(os.path.join(base_path, 'response_body.json'), 'w', encoding='utf-8') as f:
f.write(req)
with open(os.path.join(base_path, 'request_body.bin'), 'w', encoding='utf-8') as f:
f.write(data2)
if flow.request.method == "GET" or flow.request.method == "POST":
if "https://i.waimai.meituan.com/external/ajax/poi/" in url:
headers = dict(flow.request.headers)
params = dict(flow.request.query)
data = flow.request.content
if bool(data):
data2 = data.decode('utf8')
else:
data2 = ''
req2 = flow.response.content
status_code = flow.response.status_code
req = req2.decode('utf-8')
out_data = {'headers': headers, 'url': flow.request.url, 'method': flow.request.method,
'params': params,
'data': data2, 'request': req, 'status_code': status_code}
# send_socket(out_data)
order_name = 'yiming'
das = (order_name, dfpid, ip_address, json.dumps(out_data, ensure_ascii=False))
insrt_sql = """
insert into ajax_shopinfo (order_name,dfpid,ip_address,ajax_poi) values (%s,%s,%s,%s) ON DUPLICATE KEY UPDATE
ajax_poi = VALUES(ajax_poi),is_ok = null;
"""
tent.write_data_one(insrt_sql, das)
# title = url.split('?')[0].split('/')[-1]
# sv = os.path.join('headersdata', title)
# os.makedirs(sv, exist_ok=True)
# with open(f'{sv}/{title}', 'w', encoding='utf-8') as f:
# f.write(json.dumps(out_data))
# print(out_data)
elif "https://i.waimai.meituan.com/openh5/poi/info?" in url:
headers = dict(flow.request.headers)
params = dict(flow.request.query)
data = flow.request.content
if bool(data):
data2 = data.decode('utf8')
else:
data2 = ''
req2 = flow.response.content
status_code = flow.response.status_code
req = req2.decode('utf-8')
out_data = {'headers': headers, 'url': flow.request.url, 'method': flow.request.method,
'params': params,
'data': data2, 'request': req, 'status_code': status_code}
# send_socket(out_data)
order_name = 'yiming'
das = (order_name, dfpid, ip_address, json.dumps(out_data, ensure_ascii=False))
insrt_sql = """
insert into ajax_shopinfo (order_name,dfpid,ip_address,shopinfo) values (%s,%s,%s,%s) ON DUPLICATE KEY UPDATE
shopinfo = VALUES(shopinfo),is_ok = null;
"""
tent.write_data_one(insrt_sql, das)
# title = url.split('?')[0].split('/')[-1]
# sv = os.path.join('headersdata', title)
# os.makedirs(sv, exist_ok=True)
# with open(f'{sv}/{title}', 'w', encoding='utf-8') as f:
# f.write(json.dumps(out_data))
# print(out_data)
# if 'https://ihotel.meituan.com/core/searchapi/hotel/list' in url:
# title = '酒店'
# # rec_headers(url, headers, data3, title, ip_address)
# format_today = str(datetime.date.today()).replace('-', '')
# channel = 'hotel_hd' + format_today
# out_data = {'headers': headers, 'url': flow.request.url, 'method': flow.request.method, 'data': data2,
# 'channel': channel,
# 'request': ress}
# path = os.path.join(r'headers_data', channel, dfpid, title)
# if os.path.exists(path) is False:
# os.makedirs(path)
# with open(f'{path}/{title}+3', 'w', encoding='utf-8') as f:
# f.write(json.dumps(out_data))
# if "https://i.waimai.meituan.com/external/ajax/poi/" in url:
# title = '置换'
# # rec_headers(url, headers, data3, title, ip_address)
# out_data = {'headers': headers, 'url': flow.request.url, 'method': flow.request.method, 'data': data2,
# 'request': ress}
# get_id(out_data)
# "https://ihotel.meituan.com/coresearch/v2/hotel/list?yodaReady\u003dwx\u0026csecappid\u003dwx7649daed8f2335c4\u0026csecplatform\u003d3\u0026csecversionname\u003d8.0.64\u0026csecversion\u003d1.4.0\u0026openId\u003dodPDr0HGJ2BdrH2WVzcERxshzyRc\u0026antiRepPlatform\u003dAndroid\u0026programName\u003dhotel\u0026utm_medium\u003dWEIXINPROGRAM\u0026riskLevel\u003d71\u0026optimusCode\u003d10\u0026openIdCipher\u003dAwQAAABJAgAAAAEAAAAyAAAAPLgC95WH3MyqngAoyM%2Fhf1hEoKrGdo0pJ5DI44e1wGF9AT3PH7Wes03actC2n%2FGVnwfURonD78PewMUppAAAADhllv2jYeNx9yCsaM0v5v6AKYERzOkSQy2JFZytQ8nFF9LiMZ85YCRcOFNUFx5jELO%2FHBPnRkMqew%3D%3D\u0026utm_campaign\u003dentry%253DMTHotel_scene%253D1106\u0026token\u003dAgF0INyYVIZwWhw1NKumpDfk0w_ASCcoq1NP7Tgf7gQQQGGcMcyRqqns-CKBnWYCGGFVfQaRWS7FRwAAAACXLwAASZknfjhzabVI9i97U8UWMhMV5U66I4vc9qeTZJwVuGHoN_llNPDFgSmCPTgANP37\u0026usertoken\u003dAgF0INyYVIZwWhw1NKumpDfk0w_ASCcoq1NP7Tgf7gQQQGGcMcyRqqns-CKBnWYCGGFVfQaRWS7FRwAAAACXLwAASZknfjhzabVI9i97U8UWMhMV5U66I4vc9qeTZJwVuGHoN_llNPDFgSmCPTgANP37\u0026userToken\u003dAgF0INyYVIZwWhw1NKumpDfk0w_ASCcoq1NP7Tgf7gQQQGGcMcyRqqns-CKBnWYCGGFVfQaRWS7FRwAAAACXLwAASZknfjhzabVI9i97U8UWMhMV5U66I4vc9qeTZJwVuGHoN_llNPDFgSmCPTgANP37\u0026userId\u003d5712038078\u0026userid\u003d5712038078\u0026uuid\u003d19aed98f648c8-1a3eb7beb6a992-0-0-19aed98f648c8\u0026locateCityId\u003d20\u0026locatecityid\u003d20\u0026appMiniVersion\u003d8.90.1\u0026lat\u003d23.1\u0026lng\u003d113.3\u0026appletShieldScene\u003dnull\u0026hotelStar\u003d\u0026price\u003d\u0026cityId\u003d20\u0026ci\u003d20\u0026channelCityId\u003d20\u0026gps_cityid\u003d20\u0026antiRepCityId\u003d20\u0026antiRepLocateCityId\u003d20\u0026category\u003d5\u0026client\u003dandroid\u0026cateId\u003d20\u0026cate\u003d20\u0026attr_28\u003d129\u0026version_name\u003d9.14.800\u0026mypos\u003d23.1%2C113.3\u0026sourceType\u003dhotelSearch\u0026wechatVersion\u003d8.0.64\u0026sdkVersion\u003d3.11.3\u0026startDay\u003d20251205\u0026endDay\u003d20251205\u0026magicMemberCode\u003d1105%2C1106\u0026offset\u003d0\u0026q\u003d%E5%B9%BF%E5%B7%9E%E5%A1%94\u0026cellTagType\u003d1\u0026limit\u003d6\u0026hotelCustomGpsStatus\u003d1\u0026specialDealHotelScene\u003dtrue\u0026riskPlatform\u003d13\u0026channelSelectCityId\u003d20\u0026appletVersionName\u003d9.11.1721\u0026appletAppId\u003dwx7649daed8f2335c4\u0026utm_fp\u003dMINI_PROGRAM\u0026SDKVersion\u003d3.11.3"
if 'https://ihotel.meituan.com/coresearch/v2/hotel/list' in url:
title = '酒店'
# rec_headers(url, headers, data3, title, ip_address)
format_today = str(datetime.date.today()).replace('-', '')
channel = 'hotel_hd' + format_today
out_data = {'headers': headers, 'url': flow.request.url, 'method': flow.request.method, 'data': data2,
'channel': channel,
'request': ress}
path = os.path.join(r'headers_data', channel, dfpid, title)
if os.path.exists(path) is False:
os.makedirs(path)
with open(f'{path}/{title}+3', 'w', encoding='utf-8') as f:
f.write(json.dumps(out_data))
#
# elif 'https://ihotel.meituan.com/hbsearch/v4/deal/search/suggest' in url:
# title = '酒店关键字搜索'
# # rec_headers(url, headers, data3, title, ip_address)
# format_today = str(datetime.date.today()).replace('-', '')
# channel = 'hotel_hd' + format_today
# out_data = {'headers': headers, 'url': flow.request.url, 'method': flow.request.method, 'data': data2,
# 'channel': channel,
# 'request': ress}
# path = os.path.join(r'headers_data', channel, dfpid, title)
# if os.path.exists(path) is False:
# os.makedirs(path)
# with open(f'{path}/{title}', 'w', encoding='utf-8') as f:
# f.write(json.dumps(out_data))
# if 'https://ihotel.meituan.com/producctapi/v3/prepayList' in url:
# title = '美团酒店详情'
# # rec_headers(url, headers, data3, title, ip_address)
# format_today = str(datetime.date.today()).replace('-', '')
# channel = 'hotel_hd' + format_today
# out_data = {'headers': headers, 'url': flow.request.url, 'method': flow.request.method, 'data': data2,
# 'channel': channel,
# 'request': ress}
# path = os.path.join(r'headers_data', channel, dfpid, title)
# if os.path.exists(path) is False:
# os.makedirs(path)
# with open(f'{path}/{title}', 'w', encoding='utf-8') as f:
# f.write(json.dumps(out_data))
if 'https://ihotel.meituan.com/group/v1/poi/' in url:
title = '美团酒店列表'
# rec_headers(url, headers, data3, title, ip_address)
format_today = str(datetime.date.today()).replace('-', '')
channel = 'hotel_hd' + format_today
out_data = {'headers': headers, 'url': flow.request.url, 'method': flow.request.method, 'data': data2,
'channel': channel,
'request': ress}
path = os.path.join(r'headers_data', channel, dfpid, title)
if os.path.exists(path) is False:
os.makedirs(path)
with open(f'{path}/{title}', 'w', encoding='utf-8') as f:
f.write(json.dumps(out_data))
if 'https://wx.waimai.meituan.com/weapp/v1/food/payattention' in url:
title = '收藏'
rec_headers(url, headers, data3, title, ip_address)
elif 'https://i.waimai.meituan.com/openh5/user/queryFavorite' in url or 'https://wx.waimai.meituan.com/weapp/v1/user/favorite/getmyfavorite' in url:
title = '收藏列表'
# rec_headers(url, headers, data3, title, ip_address)
format_today = str(datetime.date.today()).replace('-', '')
channel = 'getmyfavorite' + format_today
out_data = {'headers': headers, 'url': flow.request.url, 'method': flow.request.method, 'data': data2,
'channel': channel,
'request': ress}
path = os.path.join(r'headers_data', channel, dfpid, title)
if os.path.exists(path) is False:
os.makedirs(path)
with open(f'{path}/{title}+{str(time.time())}', 'w', encoding='utf-8') as f:
f.write(json.dumps(out_data))
elif '/sku/list/category/v8' in url:
# rec_headers(url, headers, data3, title, ip_address)
format_today = str(datetime.date.today()).replace('-', '')
channel = '小象超市' + format_today + str(time.time())
match = re.search(r'__reqTraceID=([^&]+)', flow.request.url)
req_trace_id = match.group(1)
title = req_trace_id
print(f"提取到的 __reqTraceID 为: {req_trace_id}")
out_data = {'headers': headers, 'url': flow.request.url, 'method': flow.request.method, 'data': data3,
'channel': channel,
'request': ress}
path = os.path.join(r'headers_data', channel, dfpid, title)
if os.path.exists(path) is False:
os.makedirs(path)
with open(f'{path}/{title}', 'w', encoding='utf-8') as f:
f.write(json.dumps(out_data))
hd = (headers, flow.request.url, data3)
da = (channel, json.dumps(hd), 0)
sql = """
insert into elephant_hd (title,hd_data,count_req) values (%s,%s,%s)
on duplicate key update hd_data = values(hd_data), is_ok = null
"""
tent.write_data_one(sql, da)
if 'https://quic-hotel.17u.cn/api/main/flow/detail/data/v3' in url:
title = '同程酒店'
rec_headers(url, headers, data3, title, ip_address, req)
elif 'soa2/33278/getHotelRoomListInland' in url:
title = '携程酒店_列表'
rec_headers(url, headers, data3, title, ip_address)
elif 'soa2/35021/getHotelRoomPopInfo' in url:
title = '携程酒店_详情'
rec_headers(url, headers, data3, title, ip_address)
# format_today = str(datetime.date.today()).replace('-', '')
# channel = 'hotel_hd' + format_today
# out_data = {'headers': headers, 'url': flow.request.url, 'method': flow.request.method, 'data': data2,
# 'channel': channel,
# 'request': ress}
# path = os.path.join(r'headers_data', channel, headers['apmat'], title)
# if os.path.exists(path) is False:
# os.makedirs(path)
# with open(f'{path}/{title}+3', 'w', encoding='utf-8') as f:
# f.write(json.dumps(out_data))
elif 'https://drunkhorse.meituan.com/api/v2/category/page/main' in url:
title = '歪马food'
format_today = str(datetime.date.today()).replace('-', '')
channel = title + format_today
out_data = {'headers': headers, 'url': flow.request.url, 'method': flow.request.method, 'data': data2,
'channel': channel,
'request': ress}
print('当前的店铺poi' + json.loads(data2)['poiIdStr'])
path = os.path.join(r'headers_data', channel, dfpid, title)
if os.path.exists(path) is False:
os.makedirs(path)
with open(f'{path}/{title}+{str(time.time())}', 'w', encoding='utf-8') as f:
f.write(json.dumps(out_data))
elif 'https://drunkhorse.meituan.com/api/v2/category/page/products' in url:
title = '歪马products'
format_today = str(datetime.date.today()).replace('-', '')
channel = title + format_today
out_data = {'headers': headers, 'url': flow.request.url, 'method': flow.request.method, 'data': data2,
'channel': channel,
'request': ress}
print('当前的店铺poi' + json.loads(data2)['poiIdStr'])
path = os.path.join(r'headers_data', channel, dfpid, title)
if os.path.exists(path) is False:
os.makedirs(path)
with open(f'{path}/{title}+{str(time.time())}', 'w', encoding='utf-8') as f:
f.write(json.dumps(out_data))
elif 'https://drunkhorse.meituan.com/api/v2/category/page/render' in url:
title = '歪马render'
format_today = str(datetime.date.today()).replace('-', '')
channel = title + format_today
out_data = {'headers': headers, 'url': flow.request.url, 'method': flow.request.method, 'data': data2,
'channel': channel,
'request': ress}
print('当前的店铺poi' + json.loads(data2)['poiIdStr'])
path = os.path.join(r'headers_data', channel, dfpid, title)
if os.path.exists(path) is False:
os.makedirs(path)
with open(f'{path}/{title}+{str(time.time())}', 'w', encoding='utf-8') as f:
f.write(json.dumps(out_data))
#
# #这个地址可以改
# elif 'https://i.waimai.meituan.com/openh5/user/queryFavorite' in url :
# title = '美团关键词'
# # rec_headers(url, headers, data3, title, ip_address)
# format_today = str(datetime.date.today()).replace('-', '')
# channel = 'getmyfavorite' + format_today
# out_data = {'headers': headers, 'url': flow.request.url, 'method': flow.request.method, 'data': data2,
# 'channel': channel,
# 'request': ress}
# path = os.path.join(r'headers_data', channel, dfpid, title)
# if os.path.exists(path) is False:
# os.makedirs(path)
# with open(f'{path}/{title}+{str(time.time())}', 'w', encoding='utf-8') as f:
# f.write(json.dumps(out_data))
# hd = (headers, flow.request.url, data3)
# da = (dfpid, json.dumps(hd), 0)
# sql = """
# insert into elephant_hd (title,hd_data,count_req) values (%s,%s,%s)
# on duplicate key update hd_data = values(hd_data), is_ok = null
# """
# tent.write_data_one(sql, da)
# getmyfavorite
def run():
mitmdump(["-s", __file__, "-q", "-m", "socks5@2080", "-m", "regular@8080"]) # 修改代码
if __name__ == '__main__':
set_proxy()
run()