1708 lines
79 KiB
Python
1708 lines
79 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
|
||
from mitmproxy import http
|
||
import json, socket, os
|
||
from winproxy import ProxySetting
|
||
import newsetting
|
||
|
||
# ==================== 运行参数(改这里) ====================
|
||
USER = 'tk'
|
||
USE_API_PROXY = True
|
||
API_PROXY = {"http": "http://uuvg:uuvgt@139y.smart.51tcp.net:20431", "https": "http://uuvg:uuvgt@139y.smart.51tcp.net:20880"}
|
||
_SKIP_FWD_REQ = {'host', 'content-length', 'transfer-encoding', 'proxy-connection', 'connection', 'expect'}
|
||
_SKIP_FWD_RESP = {'content-encoding', 'content-length', 'transfer-encoding', 'connection', 'proxy-authenticate'}
|
||
# ============================================================
|
||
|
||
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')
|
||
tent_waima = newsetting.All_Setting('192.168.5.5', 3306, 'headers_project') # 歪马抓包库
|
||
menu_buffer = {}
|
||
formatted_date = time.strftime("%Y年%m月%d日", time.localtime())
|
||
|
||
# 已加 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]
|
||
|
||
|
||
# 同坐标只打一次逆地理。lat/lng 入库仍是百万分之一整数,city 去掉末尾「市」
|
||
_CITY_CACHE = {}
|
||
_GEO_URL = 'https://h5gw.map.qq.com/ws/geocoder/v1/'
|
||
|
||
|
||
def pick_lat_lng(data, url):
|
||
"""优先 body,其次 URL。返回抓包原值(百万分之一整数)。"""
|
||
keys = (
|
||
('wm_latitude', 'wm_longitude'),
|
||
('latitude', 'longitude'),
|
||
('wm_actual_latitude', 'wm_actual_longitude'),
|
||
)
|
||
src = data if isinstance(data, dict) else {}
|
||
for lat_k, lng_k in keys:
|
||
lat, lng = src.get(lat_k), src.get(lng_k)
|
||
if lat and lng and str(lat) not in ('0', 'None', '') and str(lng) not in ('0', 'None', ''):
|
||
return str(lat).split('.')[0], str(lng).split('.')[0]
|
||
params = parse_qs(urlparse(url).query, keep_blank_values=True)
|
||
for lat_k, lng_k in keys:
|
||
lat = (params.get(lat_k) or [None])[0]
|
||
lng = (params.get(lng_k) or [None])[0]
|
||
if lat and lng and lat not in ('0',) and lng not in ('0',):
|
||
return str(lat).split('.')[0], str(lng).split('.')[0]
|
||
return None, None
|
||
|
||
|
||
def location_city(lat_raw, lng_raw):
|
||
"""百万分之一整数转城市。23132066,113293752 → 广州。"""
|
||
key = (str(lat_raw), str(lng_raw))
|
||
if key in _CITY_CACHE:
|
||
return _CITY_CACHE[key]
|
||
lat = float(lat_raw) / 1000000
|
||
lng = float(lng_raw) / 1000000
|
||
resp = requests.get(_GEO_URL, params={
|
||
'key': 'none',
|
||
'location': f'{lat},{lng}',
|
||
'apptag': 'lbs_geocoder',
|
||
'output': 'json',
|
||
}, timeout=8)
|
||
resp.raise_for_status()
|
||
body = resp.json()
|
||
if body.get('status') != 0:
|
||
raise RuntimeError(f"status={body.get('status')} message={body.get('message')}")
|
||
city = (body.get('result') or {}).get('address_component', {}).get('city') or ''
|
||
if city.endswith('市'):
|
||
city = city[:-1]
|
||
_CITY_CACHE[key] = city
|
||
return city
|
||
|
||
|
||
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://scsearchapi.waimai.meituan.com/wxdrug/v2/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://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", # 歪马商品搜索
|
||
"https://i.waimai.meituan.com/weapp/pinhaofan/v2/poi/info",
|
||
# 从 1.3.py 并入
|
||
'https://i.waimai.meituan.com/openh5/search/globalpage',
|
||
"https://hcapi-wx.waimai.meituan.com/mtweapp/v1/poi/info", # 美团_买药_poi_info
|
||
"https://wx-shangou.meituan.com/mtweapp/v2/poi/info", # 美团_便利店_poi_info
|
||
'https://wx.waimai.meituan.com/weapp/v2/poi/channelpage', # 美团美食频道页
|
||
'https://wx.waimai.meituan.com/weapp/v1/comment/poi', # 美团美食店铺评价
|
||
"https://i.waimai.meituan.com/ajax/v6/poi/qualification", # 店铺资质
|
||
"from_app_drug_detail", # 美团药店商品详情
|
||
"https://deliverycommonapi.peisong.meituan.com/address/search", # 美团地址搜索
|
||
"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", # 快驴搜索
|
||
"https://wxapp.qunar.com/h_venus", # 去哪儿酒店
|
||
"https://meishi.meituan.com/i/certificate/foodsafety",
|
||
"https://meishi.meituan.com/i/api/certificate/foodsafety/info",
|
||
"https://m5-zb.amap.com/ws/boss/enterprise/open/car_list/v2", # 网约车报价
|
||
"https://m5-zb.amap.com/ws/boss/enterprise/open/order/detail", # 网约车企业订单详情
|
||
"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", # 网约车司机定位
|
||
"passenger.elevatorPublish.pageRefresh", # 哈啰顺风车
|
||
"/ws/amap/ride/hitch/car_list", # 高德顺风车
|
||
"poi.map.xiaojukeji.com/mapapi/textsearch", # 滴滴顺风车
|
||
]
|
||
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)
|
||
tent_waima.write_data_one(sql, da)
|
||
|
||
|
||
def insert_sfc_sql(table_name, da):
|
||
sql = """INSERT INTO {table_name}
|
||
(dfpid, account_key, cred_json, ip, json_data, title, channel, is_ok, req_count)
|
||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||
ON DUPLICATE KEY UPDATE
|
||
json_data = VALUES(json_data), account_key = VALUES(account_key), cred_json = VALUES(cred_json), is_ok = null""".format(table_name=table_name)
|
||
print(sql, da)
|
||
tent.write_data_one(sql, da)
|
||
|
||
|
||
def save_drug_search_hd(headers, full_url, body):
|
||
"""美团买药搜索 wxdrug/v2/search/globalpage。
|
||
写入 headers_project.search_globalpage_hd_mt,tent 即 192.168.5.2:3307。
|
||
hd_data 给 药品搜索/部分.py:url、params、headers、payload。
|
||
"""
|
||
parsed = urlparse(full_url)
|
||
base = f'{parsed.scheme}://{parsed.netloc}{parsed.path}'
|
||
query = {}
|
||
for key, value in parse_qs(parsed.query, keep_blank_values=True).items():
|
||
query[key] = value[0] if value else ''
|
||
mtgsig = headers.get('mtgsig') or headers.get('Mtgsig') or '{}'
|
||
title = eval(mtgsig)['a3']
|
||
packet = {
|
||
'url': base,
|
||
'params': query,
|
||
'headers': headers,
|
||
'payload': body,
|
||
}
|
||
da = (title, json.dumps(packet, ensure_ascii=False), 0)
|
||
sql = '''
|
||
insert into search_globalpage_hd_mt (title, hd_data, count_req)
|
||
values (%s, %s, %s)
|
||
on duplicate key update hd_data = values(hd_data), is_ok = null, count_req = 0
|
||
'''
|
||
tent.write_data_one(sql, da)
|
||
print(f'美团买药搜索已入库 search_globalpage_hd_mt title={title}')
|
||
|
||
|
||
def qyd_packet_title(url):
|
||
if '/car_list/v2' in url:
|
||
return 'car_list_v2'
|
||
if '/check_multi_order' in url:
|
||
return 'check_multi_order'
|
||
if '/order/car/order/driver/location' in url:
|
||
return 'driver_location'
|
||
if '/enterprise/open/order/detail' in url:
|
||
return 'enterprise_order_detail'
|
||
if '/order/car/order/detail' in url:
|
||
return 'car_order_detail'
|
||
return 'qyd_packet'
|
||
|
||
|
||
def save_qyd_packet(headers, url, method, data, response_body):
|
||
format_today = str(datetime.date.today()).replace('-', '')
|
||
title = qyd_packet_title(url)
|
||
session_id = headers.get('sessionid') or headers.get('Sessionid') or str(int(time.time() * 1000))
|
||
packet_id = f"{int(time.time() * 1000)}_{title}"
|
||
path = os.path.join(r'headers_data', '网约车' + format_today, session_id, packet_id)
|
||
if os.path.exists(path) is False:
|
||
os.makedirs(path)
|
||
request_data = {'headers': headers, 'url': url, 'method': method, 'data': data,
|
||
'time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
|
||
response_data = {'url': url, 'method': method, 'status_code': 200,
|
||
'time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
|
||
with open(os.path.join(path, 'request.json'), 'w', encoding='utf-8') as f:
|
||
f.write(json.dumps(request_data, ensure_ascii=False, indent=2))
|
||
with open(os.path.join(path, 'response.json'), 'w', encoding='utf-8') as f:
|
||
f.write(json.dumps(response_data, ensure_ascii=False, indent=2))
|
||
with open(os.path.join(path, 'response_body.json'), 'w', encoding='utf-8') as f:
|
||
f.write(response_body)
|
||
|
||
|
||
def save_local_packet(headers, url, method, data, response_body, category):
|
||
format_today = str(datetime.date.today()).replace('-', '')
|
||
timestamp = str(int(time.time() * 1000))
|
||
packet_id = f"{timestamp}_{category}"
|
||
path = os.path.join(r'headers_data', f'{category}_' + format_today, timestamp, packet_id)
|
||
if os.path.exists(path) is False:
|
||
os.makedirs(path)
|
||
request_data = {'headers': headers, 'url': url, 'method': method, 'data': data,
|
||
'time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
|
||
response_data = {'url': url, 'method': method, 'status_code': 200,
|
||
'time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
|
||
with open(os.path.join(path, 'request.json'), 'w', encoding='utf-8') as f:
|
||
f.write(json.dumps(request_data, ensure_ascii=False, indent=2))
|
||
with open(os.path.join(path, 'response.json'), 'w', encoding='utf-8') as f:
|
||
f.write(json.dumps(response_data, ensure_ascii=False, indent=2))
|
||
with open(os.path.join(path, 'response_body.json'), 'w', encoding='utf-8') as f:
|
||
f.write(response_body)
|
||
|
||
|
||
def save_file(datws):
|
||
batch = '外卖小程序测试'
|
||
url2 = datws['url'].split('?')[0].split('/')[-1]
|
||
filepath = os.path.join('./', formatted_date, batch, url2)
|
||
os.makedirs(filepath, exist_ok=True)
|
||
with open(f'{filepath}/{time.time()}.json', 'w', encoding='utf-8') as f:
|
||
f.write(json.dumps(datws, ensure_ascii=False))
|
||
print('保存完成')
|
||
|
||
|
||
def save_sfc_gd_identity(headers, url, data, ip_address):
|
||
channel = 'car_list'
|
||
title = '高德顺风车-身份包'
|
||
account_key = headers.get('sessionid', '')
|
||
if account_key == '':
|
||
cookie = headers.get('Cookie', '') or headers.get('cookie', '')
|
||
match = re.search(r'sessionid=([^;]+)', cookie)
|
||
account_key = match.group(1) if match else ''
|
||
if account_key == '':
|
||
raise Exception('高德顺风车缺少sessionid,不能生成account_key')
|
||
cred_json = json.dumps({'sessionid': account_key, 'asac': headers.get('asac', ''),
|
||
'bx-umidtoken': headers.get('bx-umidtoken', '')}, ensure_ascii=False)
|
||
header_host = ''
|
||
for header_key in headers:
|
||
if header_key.lower() == 'host' or header_key.lower() == ':authority':
|
||
header_host = headers[header_key]
|
||
url_data = urlparse(url)
|
||
if header_host:
|
||
save_url = url_data.scheme + '://' + header_host + url_data.path
|
||
if url_data.query:
|
||
save_url = save_url + '?' + url_data.query
|
||
else:
|
||
save_url = url
|
||
out_data = (headers, save_url, data)
|
||
dfpid = account_key + channel
|
||
print('保存高德顺风车身份包:', save_url, dfpid)
|
||
da = (dfpid, account_key, cred_json, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
|
||
insert_sfc_sql('sfc_gd_headers', da)
|
||
|
||
|
||
def save_sfc_dd_identity(headers, url, data, ip_address):
|
||
channel = 'textsearch'
|
||
title = '滴滴顺风车-身份包'
|
||
params = {}
|
||
for key, value in parse_qs(urlparse(url).query).items():
|
||
params[key] = value[0]
|
||
if isinstance(data, str) and data:
|
||
for key, value in parse_qs(data).items():
|
||
params[key] = value[0]
|
||
token = params.get('token', '')
|
||
user_id = params.get('user_id', '')
|
||
openid = params.get('openid', '')
|
||
if token == '':
|
||
raise Exception('滴滴顺风车缺少token,不能生成account_key')
|
||
account_key = token + '|' + openid
|
||
cred_json = json.dumps({'token': token, 'user_id': user_id, 'openid': openid}, ensure_ascii=False)
|
||
out_data = (headers, url, data)
|
||
dfpid = account_key + channel
|
||
print('保存滴滴顺风车身份包:', url, dfpid)
|
||
da = (dfpid, account_key, cred_json, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
|
||
insert_sfc_sql('sfc_dd_headers', da)
|
||
|
||
|
||
def save_sfc_hl_headers(headers, url, data, ip_address):
|
||
channel = 'pageRefresh'
|
||
title = '哈啰顺风车-拼座包'
|
||
json_data = json.loads(data)
|
||
risk_control = json_data.get('riskControlData', {})
|
||
token = json_data.get('token', '')
|
||
open_id = json_data.get('openId', '') or risk_control.get('openId', '')
|
||
union_id = json_data.get('unionId', '') or risk_control.get('unionId', '')
|
||
account_key = token + '|' + open_id + '|' + union_id
|
||
cred_json = json.dumps({'token': token, 'openId': open_id, 'unionId': union_id}, ensure_ascii=False)
|
||
if '/api?' in url:
|
||
save_url = 'https://taxiapi.hellobike.com' + urlparse(url).path + '?' + urlparse(url).query
|
||
else:
|
||
save_url = url
|
||
out_data = (headers, save_url, data)
|
||
dfpid = account_key + channel
|
||
print('保存哈啰顺风车拼座包:', save_url, dfpid)
|
||
da = (dfpid, account_key, cred_json, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
|
||
insert_sfc_sql('sfc_hl_headers', 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_medince_item(da):
|
||
sql = """INSERT INTO medince_item_hd
|
||
(dfpid, ip, json_data, title, channel, is_ok, req_count, lat, lng, city, `user`)
|
||
VALUES (%s, %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`),
|
||
lat = IF(VALUES(lat) IS NULL OR VALUES(lat) = '', lat, VALUES(lat)),
|
||
lng = IF(VALUES(lng) IS NULL OR VALUES(lng) = '', lng, VALUES(lng)),
|
||
city = IF(VALUES(city) IS NULL OR VALUES(city) = '', city, VALUES(city))"""
|
||
tent.write_data_one(sql, da)
|
||
|
||
|
||
def save_medince_item(url, data, dfpid, ip_address, out_data, title, channel):
|
||
lat, lng = pick_lat_lng(data, url)
|
||
city = None
|
||
if lat and lng:
|
||
try:
|
||
city = location_city(lat, lng) or None
|
||
except Exception as e:
|
||
print(f'[city] {lat},{lng} 转城市失败: {e}')
|
||
print(f'[medince] lat={lat} lng={lng} city={city} user={USER} title={title}')
|
||
da = (
|
||
dfpid, ip_address, json.dumps(out_data, ensure_ascii=False),
|
||
title, channel, None, 0, lat, lng, city, USER,
|
||
)
|
||
insert_medince_item(da)
|
||
|
||
|
||
def insert_sql3(table_name, da):
|
||
sql = """INSERT INTO {table_name}
|
||
(dfpid, ip, json_data, title, channel, is_ok, req_count,req)
|
||
VALUES (%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 'https://hcapi-wx.waimai.meituan.com/mtweapp/v1/poi/info' in url or 'https://wx-shangou.meituan.com/mtweapp/v2/poi/info' in url:
|
||
channel = 'poi_info'
|
||
da = (dfpid, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
|
||
insert_sql1('shopinfo_hd', da)
|
||
elif '/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 = '便利店商品详情'
|
||
save_medince_item(url, data, dfpid, ip_address, out_data, title, channel)
|
||
elif "from_app_drug_detail" in url:
|
||
channel = 'item'
|
||
save_medince_item(url, data, dfpid, ip_address, out_data, title, channel)
|
||
elif 'https://ihotel.meituan.com/hbsearch/v4/deal/search/suggest' in url:
|
||
channel = 'suggest'
|
||
da = (dfpid, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
|
||
print(da)
|
||
insert_sql1('hotel_suggest_hd', da)
|
||
elif "https://i.waimai.meituan.com/weapp/pinhaofan/v2/poi/info" in url:
|
||
channel = 'item'
|
||
title = '拼好饭搜索'
|
||
da = (dfpid, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
|
||
insert_sql2('pinhaofan_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_sql1('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_sql1('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_sql1('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_sql1('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_sql1('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_sql1('market_discount_float_headers', da)
|
||
|
||
elif 'v2/poi/channelpage' in url:
|
||
channel = 'channelpage'
|
||
dfpid = eval(headers['mtgsig'])['a3']
|
||
da = (dfpid, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
|
||
print(da)
|
||
insert_sql1('market_channelpage_headers', da)
|
||
|
||
elif "https://deliverycommonapi.peisong.meituan.com/address/search" 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('market_address_search_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 or 'https://sharkwsbj.sankuai.com/shark' 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')
|
||
ip_address = client_info['ip']
|
||
if 'https://scsearchapi.waimai.meituan.com/wxdrug/v2/search/globalpage' in url:
|
||
save_drug_search_hd(headers, flow.request.url, data2)
|
||
return
|
||
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
|
||
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
|
||
if '/ws/amap/ride/hitch/car_list' in url:
|
||
print('命中高德顺风车身份包,写入 sfc_gd_headers:', url)
|
||
save_sfc_gd_identity(headers, flow.request.url, data2, ip_address)
|
||
return
|
||
if 'poi.map.xiaojukeji.com/mapapi/textsearch' in url:
|
||
print('命中滴滴顺风车身份包,写入 sfc_dd_headers:', url)
|
||
save_sfc_dd_identity(headers, flow.request.url, data2, ip_address)
|
||
return
|
||
try:
|
||
if flow.request.method == "POST":
|
||
data3 = reqdata(data2)
|
||
else:
|
||
data3 = data2
|
||
except:
|
||
data3 = json.loads(data2)
|
||
if 'https://i.waimai.meituan.com/ajax/v6/poi/qualification' in url:
|
||
params = dict(flow.request.query)
|
||
mtgsig = json.loads(params.get('mtgsig', '{}'))
|
||
dfpid = mtgsig.get('a3', '')
|
||
format_today = str(datetime.date.today()).replace('-', '')
|
||
channel = '店铺资质' + format_today
|
||
title = url.split('?')[0].split('/')[-1]
|
||
out_data = {'headers': headers, 'url': flow.request.url, 'method': flow.request.method, 'data': data3,
|
||
'channel': channel}
|
||
print('命中店铺资质,直接写入 qualification_hd:', url)
|
||
da = (dfpid + title + channel, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
|
||
insert_sql1('qualification_hd', da)
|
||
return
|
||
req2 = flow.response.content
|
||
req = req2.decode('utf-8')
|
||
print(req)
|
||
if 'https://klmall.meituan.com/wxmall/api/goods/search?gtCityId' in url:
|
||
save_local_packet(headers, flow.request.url, flow.request.method, data3, req, '快驴搜索')
|
||
return
|
||
if 'https://guide-acs.m.taobao.com/gw/mtop.taobao.mbis.address.keyword.search/' in url:
|
||
save_local_packet(headers, flow.request.url, flow.request.method, data3, req, '淘宝地址搜索')
|
||
return
|
||
if 'https://deliverycommonapi.peisong.meituan.com/address/search' in url:
|
||
save_local_packet(headers, flow.request.url, flow.request.method, data3, req, '美团地址搜索')
|
||
rec_headers(url, headers, data3, '地址搜索', ip_address)
|
||
return
|
||
if 'https://waimai-guide.ele.me/gw/mtop.alsc.address.poi.keywordsearch' in url:
|
||
save_local_packet(headers, flow.request.url, flow.request.method, data3, req, '饿了么地址搜索')
|
||
return
|
||
if 'https://m5-zb.amap.com/ws/boss/enterprise/open/car_list/v2' in url or 'https://m5-zb.amap.com/ws/boss/enterprise/open/order/detail' in url or 'https://m5-zb.amap.com/ws/boss/enterprise/open/check_multi_order' in url or 'https://m5-zb.amap.com/ws/boss/order/car/order/detail' in url or 'https://m5-zb.amap.com/ws/boss/order/car/order/driver/location' in url:
|
||
save_qyd_packet(headers, flow.request.url, flow.request.method, data3, req)
|
||
return
|
||
if 'https://wxapp.qunar.com/h_venus' in url:
|
||
cookies = dict(flow.request.cookies)
|
||
channel = 'qunar_hotel'
|
||
title = '去哪儿酒店'
|
||
out_data = (url, headers, data3, cookies)
|
||
dfpid = cookies.get('_s', '') + title
|
||
da = (dfpid, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
|
||
insert_sql1('qunar_headers', da)
|
||
return
|
||
if 'meishi.meituan.com/i/certificate/foodsafety' in url or 'meishi.meituan.com/i/api/certificate/foodsafety/info' in url:
|
||
cookies = dict(flow.request.cookies)
|
||
for k, v in flow.response.cookies.items():
|
||
cookies[k] = v[0] if isinstance(v, tuple) else v
|
||
channel = 'foodsafety_html' if '/api/' not in url else 'foodsafety_api'
|
||
title = '获取poiIdEncrypt' if '/api/' not in url else '美食证照'
|
||
out_data = (flow.request.url, headers, data3, cookies)
|
||
dfpid = cookies.get('WEBDFPID', str(int(time.time() * 1000))) + channel
|
||
da = (dfpid, ip_address, json.dumps(out_data, ensure_ascii=False), title, channel, None, 0)
|
||
insert_sql1('foodsafety_headers', da)
|
||
return
|
||
if 'passenger.elevatorPublish.pageRefresh' in url:
|
||
print('命中哈啰顺风车拼座包,写入 sfc_hl_headers:', url)
|
||
save_sfc_hl_headers(headers, flow.request.url, data2, ip_address)
|
||
return
|
||
if not (
|
||
"https://ihotel.meituan.com/productapi/v3/prepayList" in url or "https://ihotel.meituan.com/naruto/hotel/core/router/shelf" in url or "https://ihotel.meituan.com/hbsearch/v4/deal/search/suggest" 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)
|
||
|
||
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/v2/poi/channelpage' 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/v1/comment/poi' 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}
|
||
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 or 'https://i.waimai.meituan.com/openh5/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://ihotel.meituan.com/hbsearch/v4/deal/search/suggest' in url:
|
||
title = '酒店搜索推荐'
|
||
rec_headers(url, headers, data2, title, ip_address)
|
||
|
||
if "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/weapp/pinhaofan/v2/poi/info' in url:
|
||
title = '拼好饭搜索'
|
||
rec_headers(url, headers, data3, title, ip_address)
|
||
|
||
#
|
||
# #这个地址可以改
|
||
# 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 _latin1_header(val):
|
||
text = str(val)
|
||
try:
|
||
text.encode('latin-1')
|
||
return text
|
||
except UnicodeEncodeError:
|
||
return text.encode('latin-1', 'ignore').decode('latin-1')
|
||
|
||
|
||
def _proxy_session():
|
||
sess = requests.Session()
|
||
sess.trust_env = False
|
||
sess.proxies.update(API_PROXY)
|
||
sess.verify = False
|
||
return sess
|
||
|
||
|
||
_fwd_sess = None
|
||
|
||
|
||
def _proxy_forward(flow):
|
||
"""把这条请求改从 API_PROXY 出去,回包塞回 flow,客户端无感。"""
|
||
global _fwd_sess
|
||
raw_headers = {}
|
||
for k, v in flow.request.headers.items():
|
||
if k.lower() in _SKIP_FWD_REQ:
|
||
continue
|
||
raw_headers[k] = _latin1_header(v)
|
||
if _fwd_sess is None:
|
||
_fwd_sess = _proxy_session()
|
||
try:
|
||
resp = _fwd_sess.request(
|
||
method=flow.request.method,
|
||
url=flow.request.pretty_url,
|
||
headers=raw_headers,
|
||
data=flow.request.content or None,
|
||
timeout=60,
|
||
)
|
||
except Exception as e:
|
||
print(f'[代理] 转发失败 {flow.request.pretty_url} err={type(e).__name__}: {e}')
|
||
return
|
||
out_headers = {}
|
||
for k, v in resp.headers.items():
|
||
if k.lower() in _SKIP_FWD_RESP:
|
||
continue
|
||
out_headers[k] = v
|
||
flow.response = http.Response.make(resp.status_code, resp.content, out_headers)
|
||
print(f'[代理] {resp.status_code} {flow.request.method} {flow.request.pretty_url}')
|
||
|
||
|
||
def request(flow):
|
||
if not USE_API_PROXY:
|
||
return
|
||
if choose2_api(flow.request.pretty_url):
|
||
_proxy_forward(flow)
|
||
|
||
|
||
def run():
|
||
mitmdump(["-s", __file__, "-q", "-m", "socks5@2080", "-m", "regular@8080"]) # 修改代码
|
||
|
||
|
||
if __name__ == '__main__':
|
||
set_proxy()
|
||
run()
|
||
|
||
|
||
|