歪马送酒每日采集流程(云端出签)
This commit is contained in:
+378
@@ -0,0 +1,378 @@
|
||||
import json
|
||||
import random
|
||||
import time
|
||||
|
||||
import requests
|
||||
import newsetting as ten
|
||||
|
||||
|
||||
# 远端 mtgsig 签名服务(同 8月/海底捞 里那套)
|
||||
SIGN_URL = 'http://129.211.12.35:18003/minipro_mt_0206'
|
||||
SIGN_TOKEN = 'test_sdfio23923ojbedfojgbouqgew4r32dds'
|
||||
|
||||
# 歪马抓包库: 模板包从这张表里取 is_ok 为 null 的行
|
||||
tent = ten.All_Setting(host='192.168.5.5', port=3306, db='headers_project')
|
||||
HEADERS_TABLE = 'waima_search_headers'
|
||||
|
||||
# 任务库: 关键词任务从这张表取, 每页 response 也写回这个库
|
||||
tent_input = ten.All_Setting(host='192.168.5.5', port=3306, db='project_waima')
|
||||
TASK_TABLE = 'waima_keyword_input'
|
||||
RESULT_TABLE = 'waima_keyword_search'
|
||||
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'
|
||||
BATCH = '2026-12-04'
|
||||
|
||||
# 任务表 city -> 首页城市ID(市级行政区划代码: 取 adcode 前 4 位 + 00)
|
||||
CITY_ID = {
|
||||
'北京市': '110100',
|
||||
'上海市': '310100',
|
||||
'广州市': '440100',
|
||||
'深圳市': '440300',
|
||||
'厦门市': '350200',
|
||||
'成都市': '510100',
|
||||
}
|
||||
|
||||
# 任务城市没有对应代理时, 退到该省省会的代理(只换出口IP, 任务城市/坐标头不变)
|
||||
CITY_CAPITAL = {
|
||||
'北京市': '北京',
|
||||
'上海市': '上海',
|
||||
'广州市': '广州',
|
||||
'深圳市': '广州',
|
||||
'厦门市': '福州',
|
||||
'成都市': '成都',
|
||||
}
|
||||
|
||||
SORT_TYPE = 1 # 排序值, 跟抓包 body 走
|
||||
PAGE_SIZE = 15 # 每页商品条数, 跟抓包走
|
||||
MAX_NUM = 500 # 单个包最多请求次数(跟 run_pro3 一样按 current_count 卡)
|
||||
PACK_USE_NUM = 30 # 每个模板包连发多少次页面请求后随机换下一个包
|
||||
REQ_INTERVAL = 5 # 每次请求之间的间隔秒数
|
||||
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']
|
||||
mtg_origin = json.loads(header['mtgsig'])
|
||||
header['mtgsig'] = get_sign_new1(url, data_str, mtg_origin['a3'], mtg_origin, openId, 'POST')
|
||||
print('云端出签 mtgsig:', header['mtgsig'])
|
||||
|
||||
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 小于 page); new_store_id 为空的不跑"""
|
||||
sql = f'''
|
||||
select id, batch, store_id, new_store_id, store_name, keyword, page, current_page,latitude,longitude,city from {TASK_TABLE} where current_page < page and batch = '{BATCH}' and new_store_id is not null and new_store_id <> ''
|
||||
'''
|
||||
print(sql)
|
||||
rows = tent_input.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},workid='mjz666' where id={task_id}
|
||||
'''
|
||||
tent_input.update_data(sql)
|
||||
|
||||
|
||||
def update_total_num(task_id, total_num):
|
||||
"""把响应的命中总数写回任务表"""
|
||||
sql = f'''
|
||||
update {TASK_TABLE} set totalNum={total_num} where id={task_id}
|
||||
'''
|
||||
tent_input.update_data(sql)
|
||||
|
||||
|
||||
def insert_search_row(parent_id, batch, store_id, store_name, keyword, page_no, rawdata):
|
||||
"""一页一行的整包 response 入库; parent_id 强关联 waima_keyword_input.id"""
|
||||
sql = f'''
|
||||
insert into {RESULT_TABLE} (parent_id, batch, store_id, store_name, keyword, page, rawdata) values (%s,%s,%s,%s,%s,%s,%s)
|
||||
'''
|
||||
insert_data = (parent_id, batch, store_id, store_name, keyword, str(page_no), rawdata)
|
||||
tent_input.write_data_one(sql, insert_data)
|
||||
|
||||
|
||||
def insert_page_summary(batch, store_id, store_name, keyword, 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 = ('search', batch, store_id, store_name, keyword, page_no, product_count, 1 if has_more else 0, total_num, spu_ids, pack_id)
|
||||
tent_input.write_data_one(sql, insert_data)
|
||||
|
||||
|
||||
def req_search_page(template, poi_id_str, keyword, page_num, proxy):
|
||||
"""按关键词取一页搜索结果; page_num 从 0 开始"""
|
||||
body = {
|
||||
'poiIdStr': poi_id_str, # 店铺 poiIdStr 取任务表的 new_store_id(按坐标召回的), 不写死
|
||||
'keyword': keyword,
|
||||
'sortType': SORT_TYPE,
|
||||
'filterInfos': [],
|
||||
'pageNum': page_num,
|
||||
'pageSize': PAGE_SIZE,
|
||||
}
|
||||
return req_https(template['url'], body, template, proxy)
|
||||
|
||||
|
||||
def req_task_pages(pack_pool, task, current_page, got_num, proxy, city, latitude, longitude):
|
||||
"""用随机轮换的模板包把这个任务剩下的页抓完; 返回 (current_page, got_num, no_pack)
|
||||
包发满 PACK_USE_NUM 次自动换随机下一个包; 包被风控就出池, 重试同一页
|
||||
no_pack=True 表示包池已空, 外层结束整个任务循环"""
|
||||
task_id, batch, store_id, new_store_id, store_name, keyword, page = task[:7]
|
||||
last_header_id = None
|
||||
for page_no in range(int(current_page) + 1, int(page) + 1):
|
||||
while True:
|
||||
header_id = get_pack(pack_pool)
|
||||
if header_id is None:
|
||||
print(' 没有可用的模板包')
|
||||
return current_page, got_num, 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_search_page(template, new_store_id, keyword, page_no - 1, proxy)
|
||||
status = resp.status_code
|
||||
print('=== 关键词: %s 第%d页 status=%s ===' % (keyword, page_no, 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()
|
||||
page_data = inner['data']
|
||||
cards = page_data['cards']
|
||||
print(' 本页 %d 条, 共 %s 条, hasNextPage=%s' % (
|
||||
len(cards), page_data['totalNum'], page_data['hasNextPage']))
|
||||
total_num = page_data['totalNum']
|
||||
got_num += len(cards)
|
||||
update_total_num(task_id, total_num)
|
||||
for card in cards:
|
||||
item = card['data']
|
||||
print(' %s %s 现价%s 原价%s 活动价%s' % (
|
||||
item['spuId'], item['spuName'][:18], item['price'], item['originPrice'], item['activityPrice']))
|
||||
|
||||
insert_search_row(task_id, batch, store_id, store_name, keyword, page_no, resp.text)
|
||||
insert_page_summary(batch, store_id, store_name, keyword, page_no, len(cards), page_data['hasNextPage'], total_num,
|
||||
','.join(str(card['data']['spuId']) for card in cards), header_id)
|
||||
update_cur_page(task_id, page_no)
|
||||
current_page = page_no
|
||||
print(' 入库: 任务id=%s 关键词=%s 第%d页' % (task_id, keyword, page_no))
|
||||
if got_num >= total_num:
|
||||
print(' 累计 %d 条已达命中总数 %d, 提前结束' % (got_num, total_num))
|
||||
update_cur_page(task_id, int(page)) # 提前结束也标成跑完, 免得 current_page<page 下次重跑
|
||||
return int(page), got_num, False
|
||||
break
|
||||
return current_page, got_num, False
|
||||
|
||||
|
||||
def run_search():
|
||||
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, batch, store_id, new_store_id, store_name, keyword, page, current_page, latitude, longitude, city = task_rows[task_index]
|
||||
proxy = get_city_proxy(city, proxs)
|
||||
if not proxy:
|
||||
print('没有对应城市代理, 跳过任务 id=%s 城市=%s 关键词=%s' % (task_id, city, keyword))
|
||||
continue
|
||||
# 任务表存的是十进制度, homePage* 头要 ×1e6 的整数(如 23.129433 -> 23129433)
|
||||
latitude = str(int(round(float(latitude) * 1000000)))
|
||||
longitude = str(int(round(float(longitude) * 1000000)))
|
||||
current_page = int(current_page) # current_page 是已抓页数, 续跑从下一页开始
|
||||
got_num = 0 # 该关键词累计抓到的商品条数
|
||||
print('=== 任务 id=%s 批次=%s 店铺=%s(store_id=%s new_store_id=%s) 关键词=%s 共%s页 current_page=%s 代理 proxy=%s ===' % (
|
||||
task_id, batch, store_name, store_id, new_store_id, keyword, page, current_page, proxy))
|
||||
|
||||
current_page, got_num, no_pack = req_task_pages(
|
||||
pack_pool, task_rows[task_index], current_page, got_num, proxy, city, latitude, longitude)
|
||||
if no_pack:
|
||||
return
|
||||
# time.sleep(REQ_INTERVAL) # 换下一个关键词前的间隔
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_search()
|
||||
Reference in New Issue
Block a user