Files
waima_req/歪马送酒_shark请求.py
T

443 lines
18 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import json
import random
import time
import requests
import newsetting as ten
from urllib.parse import urlencode
# 远端 mtgsig 签名服务(同 8月/海底捞 里那套)
SIGN_URL = 'http://129.211.12.35:18003/minipro_mt_0206'
SIGN_TOKEN = 'test_sdfio23923ojbedfojgbouqgew4r32dds'
# 歪马抓包库: 模板包从这张表里取 is_ok 为 null 的行(券列表的包, 改 url 后请求商品列表)
tent = ten.All_Setting(host='192.168.5.5', port=3306, db='headers_project')
HEADERS_TABLE = 'waima_coupon_list_headers'
# 任务库: 券任务从这张表取, 商品页 response 写进 coupon_detail
tent_coupon = ten.All_Setting(host='192.168.5.5', port=3306, db='project_waima')
TASK_TABLE = 'waima_coupon_list_item'
LIST_TABLE = 'waima_coupon_list' # 反查 batch / store_name
CITY_TABLE = 'waima_keyword_input' # 按店铺反查城市
DETAIL_TABLE = 'waima_coupon_detail' # 商品页 response 落库
SUM_TABLE = 'waima_page_summary' # 页级汇总, 看板直接读, 不用再解析 rawdata
# 代理库: 按店铺城市取代理, 没有对应城市代理的任务跳过不跑
tent_proxy = ten.All_Setting(host='192.168.5.5', port=3306, db='project_proxy')
PROXY_TABLE = 'proxs_list'
# 任务表 city -> 首页城市ID(市级行政区划代码: 取 adcode 前 4 位 + 00)
CITY_ID = {
'北京市': '110100',
'上海市': '310100',
'广州市': '440100',
'深圳市': '440300',
'厦门市': '350200',
'成都市': '510100',
}
# 任务城市没有对应代理时, 退到该省省会的代理(只换出口IP, 任务城市/坐标头不变)
CITY_CAPITAL = {
'北京市': '北京',
'上海市': '上海',
'广州市': '广州',
'深圳市': '广州',
'厦门市': '福州',
'成都市': '成都',
}
LIST_BY_PAGE_PATH = '/api/v4/product/spu/listByPage' # 目标接口, query 参数沿用模板包那份
WM_POI_ID = -100 # 店铺数字 id
PAGE_SIZE = 10 # 每页商品条数
MAX_NUM = 500 # 单个包最多请求次数(跟 run_pro3 一样按 current_count 卡)
PACK_USE_NUM = 30 # 每个模板包连发多少次页面请求后随机换下一个包
REQ_TIMEOUT = 25 # 单条 https 请求等待秒数
def get_sign_new1(url, data, dfpid, mtg_origin, open_id, method='POST'):
"""调远端服务动态生成 mtgsig"""
headers = {"content-type": "application/json", "token": SIGN_TOKEN}
body = {
"mtg_origin": mtg_origin,
"url": url,
"data": data,
"dfpid": dfpid,
"method": method,
"open_id": open_id, # 微信的open_id
}
req = requests.post(SIGN_URL, headers=headers, json=body,
proxies={'http': None, 'https': None}, verify=False).text
print('签名结果:', req[:100])
return req
def req_https(url, body, template, proxy):
"""发一条 https 请求并返回响应; body 是 dict, proxy 是对应城市的代理"""
header = dict(template['headers'])
# Host / Content-Length / Connection 交给 requests 自己算, 留着 body 一变长度就对不上
header.pop('Host', None)
header.pop('Content-Length', None)
header.pop('Connection', None)
mtg_origin = json.loads(header['mtgsig'])
dfpid = mtg_origin['a3']
# 必须是紧凑 JSON, 与签名的字节串完全一致
data_str = json.dumps(body, ensure_ascii=False, separators=(',', ':'))
if 'openid' in header:
openid = header['openid']
else:
openid = header['openId']
header['mtgsig'] = get_sign_new1(url, data_str, dfpid, mtg_origin, openid, 'POST')
return requests.post(url, headers=header, data=data_str.encode('utf-8'),
timeout=REQ_TIMEOUT, proxies=proxy)
def get_proxs():
"""取城市代理, 返回 {city: prox_data}"""
sql = f'''
select city, prox_data from {PROXY_TABLE}
'''
rows = tent_proxy.get_shoppingmalls(sql)
proxs = {}
for row in rows:
city, prox_data = row
if type(prox_data) == str:
prox_data = json.loads(prox_data)
proxs[city] = prox_data
print('城市代理 %d 条' % len(proxs))
return proxs
def get_city_proxy(city, proxs):
"""按城市取代理; 任务表是'深圳市', 代理表是'深圳', 先精确再互相包含; 都没有就退省会"""
proxy_config = proxs.get(city)
if bool(proxy_config):
return proxy_config
for pro_city, prox_data in proxs.items():
if pro_city in city or city in pro_city:
return prox_data
capital = CITY_CAPITAL.get(city)
if capital:
prox_data = proxs.get(capital)
if bool(prox_data):
print(' %s 没有对应城市代理, 改用省会 %s 代理' % (city, capital))
return prox_data
return None
def set_task_loc_headers(header, city, latitude, longitude):
"""按任务城市/坐标覆盖模板包里的 homePage* 头; 包里 camelCase 和全小写两种写法都有"""
values = {
'homepagecityid': CITY_ID[city],
'homepagelatitude': latitude,
'homepagelongitude': longitude,
}
for key in list(header):
if key.lower() in values:
header[key] = values[key.lower()]
def get_header_rows():
"""取未处理的模板包(id / json_data / current_count)"""
sql = f'''
select id, json_data, current_count from {HEADERS_TABLE} where is_ok is null and current_count < {MAX_NUM}
'''
rows = tent.get_shoppingmalls(sql)
print('未处理模板包 %d 条' % len(rows))
return rows
def update_header_count(header_id):
sql = f'''
update {HEADERS_TABLE} set req_count=req_count+1,current_count=current_count+1 where id='{header_id}'
'''
tent.update_data(sql)
def update_header_is_ok(header_id, is_ok):
sql = f'''
update {HEADERS_TABLE} set is_ok={is_ok} where id='{header_id}'
'''
tent.update_data(sql)
def init_pack_pool(header_rows):
"""模板包池初始化: unused 是本轮还没用过的包, used 是本轮已抽到的包及已发次数"""
pack_pool = {
'templates': {},
'counts': {},
'unused': [],
'used': {},
'current_id': None,
}
for header_id, json_data, current_count in header_rows:
pack_pool['templates'][header_id] = json.loads(json_data)
pack_pool['counts'][header_id] = int(current_count)
pack_pool['unused'].append(header_id)
return pack_pool
def get_pack(pack_pool):
"""取当前模板包; 发满 PACK_USE_NUM 次就从本轮未用的包里随机换一个, 一轮用完重置再随机"""
header_id = pack_pool['current_id']
if header_id is not None and pack_pool['used'][header_id] < PACK_USE_NUM:
return header_id
if not pack_pool['unused']:
if not pack_pool['used']:
return None
print(' 一轮模板包都用过, 重置后重新随机')
pack_pool['unused'] = list(pack_pool['used'])
pack_pool['used'] = {}
header_id = random.choice(pack_pool['unused'])
pack_pool['unused'].remove(header_id)
pack_pool['used'][header_id] = 0
pack_pool['current_id'] = header_id
return header_id
def consume_pack(pack_pool, header_id):
"""成功请求一次: 累加 30 次轮换计数和本地 current_count, 到 MAX_NUM 立即出池"""
pack_pool['counts'][header_id] += 1
pack_pool['used'][header_id] += 1
if pack_pool['counts'][header_id] >= MAX_NUM:
print(' 模板包 id=%s 已用满 %d 次, 移出包池' % (header_id, MAX_NUM))
drop_pack(pack_pool, header_id)
def drop_pack(pack_pool, header_id):
"""包被风控/失效: 从包池永久移除, 若是当前包则置空让下一轮重新随机"""
pack_pool['templates'].pop(header_id, None)
pack_pool['counts'].pop(header_id, None)
pack_pool['used'].pop(header_id, None)
if header_id in pack_pool['unused']:
pack_pool['unused'].remove(header_id)
if pack_pool['current_id'] == header_id:
pack_pool['current_id'] = None
def get_task_rows():
"""取未抓完的券任务; current_page 是已抓页数; new_shop_id 是按坐标召回的 poiIdStr"""
sql = f'''
select id, shop_id, new_shop_id, couponConfigId, channelType, channelConfigId, couponName, tabId, current_page
from {TASK_TABLE} where is_ok is null
'''
rows = tent_coupon.get_shoppingmalls(sql)
print('待抓券任务 %d 条' % len(rows))
return rows
def update_cur_page(task_id, page_no):
sql = f'''
update {TASK_TABLE} set current_page={page_no} where id={task_id}
'''
tent_coupon.update_data(sql)
def update_task_is_ok(task_id, is_ok):
sql = f'''
update {TASK_TABLE} set is_ok={is_ok} where id={task_id}
'''
tent_coupon.update_data(sql)
def get_store_info(shop_id):
"""按店铺反查 batch / store_name / 城市(城市从关键词任务表按店铺取)"""
sql = f'''
select t1.batch, t1.store_name, t2.city, t2.latitude, t2.longitude from {LIST_TABLE} t1
left join {CITY_TABLE} t2 on t1.store_id=t2.store_id and t1.batch=t2.batch
where t1.store_id='{shop_id}' order by t1.id desc limit 1
'''
rows = tent_coupon.get_shoppingmalls(sql)
return rows[0]
def get_last_page(shop_id, coupon_id):
"""该券在库里最新一页的 response, 续跑靠它拿 nextOffset 和 session"""
sql = f'''
select rawdata, page from {DETAIL_TABLE} where store_id='{shop_id}' and coupon_id='{coupon_id}' order by id desc limit 1
'''
rows = tent_coupon.get_shoppingmalls(sql)
if not rows:
return None
return rows[0]
def insert_detail(parent_id, batch, shop_id, store_name, coupon_id, page_no, rawdata):
"""一页商品 response 入库; parent_id 强关联 waima_coupon_list_item.id"""
sql = f'''
insert into {DETAIL_TABLE} (parent_id, batch, store_id, store_name, coupon_id, page, rawdata) values (%s,%s,%s,%s,%s,%s,%s)
'''
insert_data = (parent_id, batch, shop_id, store_name, coupon_id, page_no, rawdata)
tent_coupon.write_data_one(sql, insert_data)
def insert_page_summary(batch, shop_id, store_name, coupon_id, page_no, product_count, has_more, total_num, spu_ids, pack_id):
"""页级汇总入库, 看板只读这张小表; spu_ids 逗号拼接, 用于跨页去重; pack_id 是这页用的模板包id"""
sql = f'''
insert into {SUM_TABLE} (source, batch, store_id, store_name, biz_id, page, product_count, has_more, total_num, spu_ids, pack_id) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
on duplicate key update product_count=values(product_count),has_more=values(has_more),total_num=values(total_num),spu_ids=values(spu_ids),pack_id=values(pack_id)
'''
insert_data = ('coupon', batch, shop_id, store_name, coupon_id, page_no, product_count, 1 if has_more else 0, total_num, spu_ids, pack_id)
tent_coupon.write_data_one(sql, insert_data)
def req_coupon_spu_page(template, shop_id, new_shop_id, coupon, tab_id, start_offset, session, proxy):
"""按某张券取一页商品; session 由上一页响应续传, 首包传空 dict"""
coupon_config_id, channel_type, channel_config_id = coupon
body = {
# 'tabId': 'COMMON_COUPON_CAN_USE',
'tabId': tab_id,
'limit': PAGE_SIZE,
'pageSize': PAGE_SIZE,
'startOffset': str(start_offset),
'couponViewId': '', # 任务表没这列, 源数据里可领券的 couponViewId 就是空串, 先按空串发
'filterSpuIds': [],
'couponConfig': {
'couponViewId': '',
'couponConfigId': coupon_config_id,
'channelConfigId': channel_config_id,
'channelType': channel_type,
},
'session': session,
'wmPoiId': WM_POI_ID,
'poiIdStr': new_shop_id, # 店铺 poiIdStr 取 item 表的 new_shop_id(按坐标召回的), 落库仍用 shop_id
}
# 模板包是券列表的 url, 把 path 换成 listByPage, host 和 query 参数沿用模板包那份
base_url = template['url'].split('/api/')[0]
query = template['url'].split('?', 1)[1]
url = base_url + LIST_BY_PAGE_PATH + '?' + query
return req_https(url, body, template, proxy)
def req_coupon_pages(pack_pool, task_data, page, start_offset, session, proxy, city, latitude, longitude):
"""用随机轮换的模板包把这张券翻到底; 返回 (page, start_offset, session, no_pack)
包发满 PACK_USE_NUM 次自动换随机下一个包续传 offset/session; 包被风控就出池, 重试同一页
no_pack=True 表示包池已空, 外层结束整个任务循环"""
task_id, batch, store_name, shop_id, new_shop_id, coupon, tab_id = task_data
coupon_config_id, channel_type, channel_config_id = coupon
last_header_id = None
while True:
header_id = get_pack(pack_pool)
if header_id is None:
print(' 没有可用的模板包')
return page, start_offset, session, True
template = pack_pool['templates'][header_id]
if header_id != last_header_id:
set_task_loc_headers(template['headers'], city, latitude, longitude)
print(' 当前模板包 id=%s' % header_id)
last_header_id = header_id
resp = req_coupon_spu_page(template, shop_id, new_shop_id, coupon, tab_id, start_offset, session, proxy)
status = resp.status_code
print(' 第%d页 startOffset=%s status=%s' % (page + 1, start_offset, status))
if '您还没有登录,请先登录' in resp.text:
print(' 账号未登录, 标记 is_ok=406')
update_header_is_ok(header_id, 406)
drop_pack(pack_pool, header_id)
last_header_id = None
continue
if status == 403:
print(' 403, 账号可能被风控, 标记 is_ok=403')
update_header_is_ok(header_id, 403)
drop_pack(pack_pool, header_id)
last_header_id = None
continue
if status != 200:
print(' 响应头:', resp.headers)
print(' 响应体:', resp.text[:500])
update_header_is_ok(header_id, status)
drop_pack(pack_pool, header_id)
last_header_id = None
continue
update_header_count(header_id)
consume_pack(pack_pool, header_id)
inner = resp.json()
print(inner)
page_data = inner['data']
spu_list = [card['data'] for card in page_data['cards']] # 商品券在 cards[].data 里
if not spu_list:
spu_list = page_data['products'] # 通用券(COMMON_COUPON_CAN_USE)的商品在 products 里, cards 是空的
page += 1
print(' 本页 %d 条, nextOffset=%s, hasMore=%s' % (
len(spu_list), page_data['nextOffset'], page_data['hasMore']))
for item in spu_list:
print(' %s %s 现价%s 原价%s 活动价%s' % (
item['spuId'], item['spuName'][:18], item['price'], item['originPrice'], item['activityPrice']))
insert_detail(task_id, batch, shop_id, store_name, coupon_config_id, page, resp.text)
insert_page_summary(batch, shop_id, store_name, coupon_config_id, page, len(spu_list), page_data['hasMore'], None,
','.join(str(item['spuId']) for item in spu_list), header_id)
update_cur_page(task_id, page)
print(' 入库: 券=%s 第%d页' % (coupon_config_id, page))
if not page_data['hasMore']:
print(' 已到最后一页, 标记 is_ok=1')
update_task_is_ok(task_id, 1)
return page, start_offset, session, False
start_offset = int(page_data['nextOffset'])
if page_data['session']:
session = page_data['session'] # 响应里的 session 续传给下一个包
# time.sleep(random.randint(0,5))
def run_all_coupons():
header_rows = get_header_rows()
if not header_rows:
print('没有可用的模板包')
return
pack_pool = init_pack_pool(header_rows)
task_rows = get_task_rows()
proxs = get_proxs()
for task_index in range(len(task_rows)):
task_id, shop_id, new_shop_id, coupon_config_id, channel_type, channel_config_id, coupon_name, tab_id, current_page = task_rows[task_index]
batch, store_name, city, latitude, longitude = get_store_info(shop_id)
if not city:
print('店铺没有城市信息, 跳过任务 id=%s 店铺=%s(%s)' % (task_id, store_name, shop_id))
continue
if not new_shop_id:
print('任务没有 new_shop_id, 跳过任务 id=%s 店铺=%s(%s)' % (task_id, store_name, shop_id))
continue
proxy = get_city_proxy(city, proxs)
if not proxy:
print('没有对应城市代理, 跳过任务 id=%s 店铺=%s(%s) 城市=%s' % (task_id, store_name, shop_id, city))
continue
# 任务表存的是十进制度, homePage* 头要 ×1e6 的整数(如 23.129433 -> 23129433)
latitude = str(int(round(float(latitude) * 1000000)))
longitude = str(int(round(float(longitude) * 1000000)))
coupon = (coupon_config_id, channel_type, channel_config_id)
task_data = (task_id, batch, store_name, shop_id, new_shop_id, coupon, tab_id)
# 续跑: current_page 是已抓页数, startOffset / session 从库里最后一页 response 恢复
page = current_page
start_offset = 0
session = {}
if page:
last_row = get_last_page(shop_id, coupon_config_id)
if not last_row:
print(' current_page=%s 但库里没有已抓页, 从第1页重来' % page)
page = 0
elif not json.loads(last_row[0])['data']['hasMore']:
print(' 该券已抓完(%s页), 标记 is_ok=1' % page)
update_task_is_ok(task_id, 1)
continue
else:
last_data = json.loads(last_row[0])['data']
start_offset = int(last_data['nextOffset'])
session = last_data['session']
print(' 续跑: 从第%d页开始 startOffset=%s' % (page + 1, start_offset))
print('=== 任务 id=%s 券=%s(configId=%s) 店铺=%s(shop_id=%s new_shop_id=%s) 已抓%s页 ===' % (
task_id, coupon_name, coupon_config_id, store_name, shop_id, new_shop_id, page))
page, start_offset, session, no_pack = req_coupon_pages(
pack_pool, task_data, page, start_offset, session, proxy, city, latitude, longitude)
if no_pack:
return
if __name__ == '__main__':
run_all_coupons()