歪马送酒每日采集流程(云端出签)
This commit is contained in:
+184
@@ -0,0 +1,184 @@
|
||||
import re
|
||||
import pymysql
|
||||
|
||||
class All_Setting():
|
||||
def __init__(self,host,port,db):
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.db = db
|
||||
|
||||
def remove_symbols(self,text):
|
||||
pattern = re.compile(r'[^\w\s]')
|
||||
return pattern.sub('', text)
|
||||
|
||||
def get_chinese(self,text,printTxt=False):
|
||||
# text = "海王星辰(广州智慧城店)"
|
||||
pattern = r'[^\w\s]'
|
||||
result = re.sub(pattern, '', text)
|
||||
if printTxt:
|
||||
print(result)
|
||||
return result
|
||||
|
||||
def get_shoppingmalls(self,sql):
|
||||
res_list = []
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
if conn:
|
||||
print('ok')
|
||||
cursor = conn.cursor()
|
||||
res = cursor.execute(sql)
|
||||
c2 = cursor.fetchall()
|
||||
return c2
|
||||
|
||||
def write_data(self,sql,data):
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
# 拿到游标
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.executemany(sql,data)
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
conn.close() # 添加连接关闭
|
||||
|
||||
|
||||
def update_data(self,sql):
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
# 拿到游标
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(sql)
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
conn.close() # 添加连接关闭
|
||||
|
||||
def update_data_many(self,sql, values):
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
# 拿到游标
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.executemany(sql, values)
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
conn.close() # 添加连接关闭
|
||||
|
||||
def write_data_one(self,sql,data):
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
# 拿到游标
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(sql,data)
|
||||
conn.commit()
|
||||
cursor.close()
|
||||
conn.close() # 添加连接关闭
|
||||
|
||||
def get(self,sql):
|
||||
conn = pymysql.connect(
|
||||
host= self.host, # 我的IP地址
|
||||
port=self.port, # 不是字符串不需要加引号。
|
||||
user='root',
|
||||
password='Aliyun@7646!',
|
||||
db=self.db,
|
||||
charset='utf8mb4'
|
||||
)
|
||||
# 拿到游标
|
||||
if conn:
|
||||
print("连接成功!")
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(sql)
|
||||
result = cursor.fetchall()
|
||||
cursor.close()
|
||||
conn.close() # 添加连接关闭
|
||||
return result
|
||||
|
||||
import json
|
||||
import time,requests
|
||||
|
||||
|
||||
def get_sign_meituan(url, dfpid, data):
|
||||
url_mtg = "http://118.89.119.254:18003/mt_jym_1_2"
|
||||
payload = json.dumps({
|
||||
"url": url,
|
||||
"data": data,
|
||||
"dfpid": dfpid,
|
||||
"method": "POST",
|
||||
"ua_type": "android"
|
||||
})
|
||||
headers = {
|
||||
'token': 'j760kynsopjfm0sa9ghjwsd',
|
||||
'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
response1 = requests.request("POST", url_mtg, headers=headers, data=payload)
|
||||
print(response1.text)
|
||||
mtgsig1 = response1.json()
|
||||
return str(mtgsig1)
|
||||
|
||||
def get_sign_waimai(url, dfpid, data):
|
||||
print('我是外卖mtg')
|
||||
|
||||
url_mtg = "http://118.89.119.254:18003/get_mt_tg_0507_jym"
|
||||
payload = json.dumps({
|
||||
"url": url,
|
||||
"data": data,
|
||||
"dfpid": dfpid,
|
||||
"method": "POST",
|
||||
# "ua_type": "android"
|
||||
})
|
||||
headers = {
|
||||
'token': 'j760kynsopjfm0sa9ghjwsd',
|
||||
'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
response = requests.request("POST", url_mtg, headers=headers, data=payload)
|
||||
mtgsig = response.json()
|
||||
print(mtgsig)
|
||||
return str(mtgsig)
|
||||
|
||||
def get_Datatext(dataq):
|
||||
str1 = ''
|
||||
for i in dataq:
|
||||
key, value = i, dataq[i]
|
||||
str2 = f'{key}={value}&'
|
||||
str1 = str1 + str2
|
||||
data = str1[0:-1]
|
||||
return data
|
||||
|
||||
|
||||
+442
@@ -0,0 +1,442 @@
|
||||
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()
|
||||
+317
@@ -0,0 +1,317 @@
|
||||
import json
|
||||
|
||||
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 的行
|
||||
tent = ten.All_Setting(host='192.168.5.5', port=3306, db='headers_project')
|
||||
HEADERS_TABLE = 'waima_coupon_list_headers'
|
||||
|
||||
# 任务库: 店铺任务从这张表按店铺去重, 券列表 response 也写回这个库
|
||||
tent_coupon = ten.All_Setting(host='192.168.5.5', port=3306, db='project_waima')
|
||||
TASK_TABLE = 'waima_keyword_input'
|
||||
RESULT_TABLE = 'waima_coupon_list'
|
||||
ITEM_TABLE = 'waima_coupon_list_item' # 拆字段后的券明细表
|
||||
|
||||
# 代理库: 按任务城市取代理, 没有对应城市代理的任务跳过不跑
|
||||
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 = {
|
||||
'北京市': '北京',
|
||||
'上海市': '上海',
|
||||
'广州市': '广州',
|
||||
'深圳市': '广州',
|
||||
'厦门市': '福州',
|
||||
'成都市': '成都',
|
||||
}
|
||||
|
||||
BATCH = '2026-12-03'
|
||||
WM_POI_ID = -100 # 店铺数字 id(抓包商品页请求里就是 -100)
|
||||
SORT = [] # app 首次打开券弹窗传的是空数组
|
||||
MAX_NUM = 500 # 单个包最多请求次数(跟 run_pro3 一样按 current_count 卡)
|
||||
REQ_TIMEOUT = 5 # 单条 https 请求等待秒数
|
||||
|
||||
CATEGORY_NAME = {6: '通用券', 7: '商品券'} # couponCategoryType
|
||||
|
||||
|
||||
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_req_count(row_id):
|
||||
sql = f'''
|
||||
update {HEADERS_TABLE} set req_count=req_count+1,current_count=current_count+1 where id='{row_id}'
|
||||
'''
|
||||
tent.update_data(sql)
|
||||
|
||||
|
||||
def update_is_ok(row_id, is_ok):
|
||||
sql = f'''
|
||||
update {HEADERS_TABLE} set is_ok={is_ok} where id='{row_id}'
|
||||
'''
|
||||
tent.update_data(sql)
|
||||
|
||||
|
||||
def get_task_rows():
|
||||
"""从关键词任务表按店铺去重, 一个店铺跑一次券列表; new_store_id 为空的不跑"""
|
||||
sql = f'''
|
||||
select distinct batch, store_id, new_store_id, store_name, city, latitude, longitude from {TASK_TABLE} where batch = '{BATCH}' and new_store_id is not null and new_store_id <> ''
|
||||
'''
|
||||
rows = tent_coupon.get_shoppingmalls(sql)
|
||||
print('待跑店铺 %d 个' % len(rows))
|
||||
return rows
|
||||
|
||||
|
||||
def is_done(batch, store_id):
|
||||
"""该批次+店铺的券列表是否已经入过库"""
|
||||
sql = f'''
|
||||
select id from {RESULT_TABLE} where batch='{batch}' and store_id='{store_id}' limit 1
|
||||
'''
|
||||
rows = tent_coupon.get_shoppingmalls(sql)
|
||||
return len(rows) > 0
|
||||
|
||||
|
||||
def insert_coupon_list(batch, store_id, store_name, rawdata):
|
||||
"""整个 response 入库"""
|
||||
sql = f'''
|
||||
insert into {RESULT_TABLE} (batch, store_id, store_name, rawdata) values (%s,%s,%s,%s)
|
||||
'''
|
||||
insert_data = (batch, store_id, store_name, rawdata)
|
||||
tent_coupon.write_data_one(sql, insert_data)
|
||||
|
||||
|
||||
def clean_coupon_items(data, shop_id, new_shop_id):
|
||||
"""可用券+可领券拍平成一行一券; shop_id 是原 store_id, new_shop_id 是按坐标召回拿到的 poiIdStr"""
|
||||
rows = []
|
||||
for coupon in data['availableCouponInfos'] + data['receivableCouponList']:
|
||||
item = (
|
||||
shop_id,
|
||||
new_shop_id,
|
||||
str(coupon['couponConfigId']), # 源里可用券是 int, 可领券是 str, 统一转串
|
||||
coupon['channelType'],
|
||||
coupon['channelConfigId'],
|
||||
coupon['couponName'],
|
||||
coupon['couponTypeDoc'],
|
||||
coupon['couponCategoryType'],
|
||||
coupon['couponPrice'],
|
||||
coupon['reduceDoc'],
|
||||
coupon['limitPriceText'],
|
||||
coupon['couponConditionText'],
|
||||
coupon['useDoc'],
|
||||
json.dumps(coupon['couponUseRules'], ensure_ascii=False),
|
||||
coupon['tabId'],
|
||||
)
|
||||
rows.append(item)
|
||||
return rows
|
||||
|
||||
|
||||
def insert_coupon_items(rows):
|
||||
sql = f'''
|
||||
insert into {ITEM_TABLE} (shop_id,new_shop_id,couponConfigId,channelType,channelConfigId,couponName,couponTypeDoc,couponCategoryType,couponPrice,reduceDoc,limitPriceText,couponConditionText,useDoc,couponUseRules,tabId) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
'''
|
||||
tent_coupon.write_data(sql, rows)
|
||||
|
||||
|
||||
def show_coupon_list(data):
|
||||
"""打印响应里的券列表概要"""
|
||||
available = data['availableCouponInfos']
|
||||
goods_list = [c for c in available if c['couponCategoryType'] == 7]
|
||||
common_list = [c for c in available if c['couponCategoryType'] == 6]
|
||||
print('可用券 %d 张(商品券 %d, 通用券 %d), 可领券 %d 张, tab %s' % (
|
||||
len(available), len(goods_list), len(common_list),
|
||||
len(data['receivableCouponList']), data['tabList']))
|
||||
for c in available:
|
||||
print(' [%s] %s | 面额%s %s | configId=%s | viewId=%s | tabId=%s | 状态%s%s' % (
|
||||
CATEGORY_NAME.get(c['couponCategoryType'], c['couponCategoryType']),
|
||||
c['couponName'], c['couponPrice'], c['couponConditionText'],
|
||||
c['couponConfigId'], c['couponViewId'], c['tabId'],
|
||||
c['couponStatus'], c['availableStatus']))
|
||||
return goods_list
|
||||
|
||||
|
||||
def run_coupon_list():
|
||||
header_rows = get_header_rows()
|
||||
if not header_rows:
|
||||
print('没有可用的模板包')
|
||||
return
|
||||
task_queue = list(get_task_rows()) # pymysql fetchall 是 tuple, 转 list 才能 pop/append
|
||||
proxs = get_proxs()
|
||||
attempt_index = 0
|
||||
while task_queue:
|
||||
task_row = task_queue.pop(0)
|
||||
batch, store_id, new_store_id, store_name, city, latitude, longitude = task_row
|
||||
proxy = get_city_proxy(city, proxs)
|
||||
if not proxy:
|
||||
print('没有对应城市代理, 跳过店铺=%s(%s) 城市=%s' % (store_name, store_id, city))
|
||||
continue
|
||||
# 任务表存的是十进制度, homePage* 头要 ×1e6 的整数(如 23.129433 -> 23129433)
|
||||
latitude = str(int(round(float(latitude) * 1000000)))
|
||||
longitude = str(int(round(float(longitude) * 1000000)))
|
||||
if is_done(batch, store_id):
|
||||
print('=== 批次=%s 店铺=%s(%s) 已有券列表, 跳过 ===' % (batch, store_name, store_id))
|
||||
continue
|
||||
header_id, json_data, current_count = header_rows[attempt_index % len(header_rows)]
|
||||
attempt_index += 1
|
||||
template = json.loads(json_data)
|
||||
set_task_loc_headers(template['headers'], city, latitude, longitude)
|
||||
print('=== 任务 批次=%s 店铺=%s(store_id=%s new_store_id=%s) 模板包 id=%s current_count=%s ===' % (
|
||||
batch, store_name, store_id, new_store_id, header_id, current_count))
|
||||
|
||||
# app 的 poi-transform 拦截器会把 body 里的 wmPoiId 换成店铺数字 id 并补上 poiIdStr, 这里按抓包里那份的值来
|
||||
body = {
|
||||
'sort': SORT,
|
||||
'wmPoiId': WM_POI_ID,
|
||||
'poiIdStr': new_store_id, # 店铺 poiIdStr 取任务表的 new_store_id(按坐标召回的), 不写死
|
||||
}
|
||||
print('请求体:', json.dumps(body, ensure_ascii=False, separators=(',', ':')))
|
||||
|
||||
resp = req_https(template['url'], body, template, proxy)
|
||||
print(' status', resp.status_code)
|
||||
if '您还没有登录,请先登录' in resp.text:
|
||||
print(' 账号未登录, 标记 is_ok=406')
|
||||
update_is_ok(header_id, 406)
|
||||
continue
|
||||
if resp.status_code != 200:
|
||||
print(' 响应头:', resp.headers)
|
||||
print(' 响应体:', resp.text[:500])
|
||||
update_is_ok(header_id, resp.status_code)
|
||||
continue
|
||||
|
||||
inner = resp.json()
|
||||
if inner['code'] == 0 and not inner['data']['availableCouponInfos'] and not inner['data']['receivableCouponList'] and not inner['data']['unavailableCouponInfos']:
|
||||
print(' 可用券/可领券/不可用券都为空, 判定包已失效, 标记 is_ok=403, 任务放回池子换包重跑')
|
||||
update_is_ok(header_id, 403)
|
||||
header_rows = [row for row in header_rows if row[0] != header_id]
|
||||
if not header_rows:
|
||||
print(' 没有可用的模板包, 退出')
|
||||
return
|
||||
task_queue.append(task_row)
|
||||
continue
|
||||
|
||||
update_req_count(header_id)
|
||||
|
||||
insert_coupon_list(batch, store_id, store_name, resp.text)
|
||||
print(' 入库: 批次=%s 店铺=%s(%s)' % (batch, store_name, store_id))
|
||||
|
||||
if inner['code'] != 0:
|
||||
print(' 接口返回异常:', inner['code'], inner['msg'])
|
||||
continue
|
||||
goods_list = show_coupon_list(inner['data'])
|
||||
print('商品券 %d 张' % len(goods_list))
|
||||
|
||||
item_rows = clean_coupon_items(inner['data'], store_id, new_store_id)
|
||||
insert_coupon_items(item_rows)
|
||||
print(' 清洗入库: %d 条券明细' % len(item_rows))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_coupon_list()
|
||||
@@ -0,0 +1,317 @@
|
||||
import json
|
||||
import random
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
import requests
|
||||
import newsetting as ten
|
||||
|
||||
|
||||
# 远端 mtgsig 签名服务(同 8月/海底捞 里那套)
|
||||
SIGN_URL = 'http://129.211.12.35:18003/minipro_mt_0206'
|
||||
SIGN_TOKEN = 'test_sdfio23923ojbedfojgbouqgew4r32dds'
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
# 模板包库: 从这张表取 is_ok 为 null 的包出签
|
||||
tent = ten.All_Setting(host='192.168.5.5', port=3306, db='headers_project')
|
||||
HEADERS_TABLE = 'waima_search_headers'
|
||||
|
||||
# 任务库: 按 batch 取坐标, 召回结果写回 new_store_id
|
||||
tent_input = ten.All_Setting(host='192.168.5.5', port=3306, db='project_waima')
|
||||
TASK_TABLE = 'waima_keyword_input'
|
||||
|
||||
# 代理库: 按任务城市取代理, 没有对应城市代理就直连
|
||||
tent_proxy = ten.All_Setting(host='192.168.5.5', port=3306, db='project_proxy')
|
||||
PROXY_TABLE = 'proxs_list'
|
||||
|
||||
BATCH = datetime.now().strftime('%Y-%m-%d') # 要处理的批次, 默认当天
|
||||
RECALL_PATH = '/api/v1/store/location/recall' # 门店召回接口, 给坐标返回服务门店
|
||||
MAX_NUM = 500 # 单个模板包最多请求次数
|
||||
PACK_USE_NUM = 3 # 每个模板包连发多少次后换下一个包
|
||||
REQ_INTERVAL = 5 # 每个坐标之间的间隔秒数
|
||||
REQ_TIMEOUT = 25 # 单条请求等待秒数
|
||||
|
||||
# 任务表 city -> 首页城市ID(市级行政区划代码)
|
||||
CITY_ID = {
|
||||
'北京市': '110100',
|
||||
'上海市': '310100',
|
||||
'广州市': '440100',
|
||||
'深圳市': '440300',
|
||||
'厦门市': '350200',
|
||||
'成都市': '510100',
|
||||
}
|
||||
|
||||
|
||||
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):
|
||||
"""成功请求一次: 累加轮换计数和本地 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_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):
|
||||
"""按城市取代理; 任务表是'深圳市', 代理表是'深圳', 先精确再互相包含; 没有就返回 None 走直连"""
|
||||
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
|
||||
return None
|
||||
|
||||
|
||||
def get_task_groups():
|
||||
"""取该批次所有坐标, 按城市+坐标去重; 同一坐标的多条任务 id 归到一组, 后面一次更新"""
|
||||
sql = f'''
|
||||
select id, city, address, latitude, longitude from {TASK_TABLE} where batch = '{BATCH}' order by id
|
||||
'''
|
||||
rows = tent_input.get_shoppingmalls(sql)
|
||||
print('批次 %s 任务 %d 条' % (BATCH, len(rows)))
|
||||
groups = {}
|
||||
for task_id, city, address, latitude, longitude in rows:
|
||||
# 用四舍五入后的浮点做 key, 避免 '22.53464' 和 '22.534640' 被当成两个坐标
|
||||
key = (city, round(float(latitude), 6), round(float(longitude), 6))
|
||||
if key not in groups:
|
||||
groups[key] = {'city': city, 'address': address, 'latitude': latitude,
|
||||
'longitude': longitude, 'ids': []}
|
||||
groups[key]['ids'].append(task_id)
|
||||
print('去重后坐标 %d 个' % len(groups))
|
||||
return list(groups.values())
|
||||
|
||||
|
||||
def set_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 build_body(latitude, longitude):
|
||||
"""按 sdk/lbs/utils.js getLocationPreQueryParams 的构造: identityJson + contentJson 两个 JSON 字符串"""
|
||||
ts = int(time.time() * 1000)
|
||||
identity = {'id': ts, 'medium': '', 'pivot': -1, 'agent': ''}
|
||||
content = {'location': {'latitude': latitude, 'longitude': longitude, 'accuracy': 0, 'id': ts, 'type': 'GCJ02'}}
|
||||
return {
|
||||
'locationPreQuery': {
|
||||
'identityJson': json.dumps(identity, ensure_ascii=False, separators=(',', ':')),
|
||||
'contentJson': json.dumps(content, ensure_ascii=False, separators=(',', ':')),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def req_signed(template, url, body, proxy):
|
||||
"""发一条带签名的请求; body 必须和出签的字节串完全一致, 所以用紧凑 JSON"""
|
||||
header = dict(template['headers'])
|
||||
header.pop('Host', None)
|
||||
header.pop('Content-Length', None)
|
||||
header.pop('Connection', None)
|
||||
|
||||
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:', str(header['mtgsig'])[:60])
|
||||
return requests.post(url, headers=header, data=data_str.encode('utf-8'),
|
||||
timeout=REQ_TIMEOUT, proxies=proxy)
|
||||
|
||||
|
||||
def req_recall(template, group, proxy):
|
||||
"""按坐标召回门店; host 和 query 沿用模板包, path 换成召回接口"""
|
||||
base_url = template['url'].split('/api/')[0]
|
||||
query = template['url'].split('?', 1)[1]
|
||||
url = base_url + RECALL_PATH + '?' + query
|
||||
body = build_body(float(group['latitude']), float(group['longitude']))
|
||||
return req_signed(template, url, body, proxy)
|
||||
|
||||
|
||||
def update_new_store_id(id_list, poi_id_str):
|
||||
"""把召回到的 poiIdStr 写回这一组任务行"""
|
||||
id_str = ','.join(str(task_id) for task_id in id_list)
|
||||
sql = f'''
|
||||
update {TASK_TABLE} set new_store_id='{poi_id_str}' where id in ({id_str})
|
||||
'''
|
||||
tent_input.update_data(sql)
|
||||
|
||||
|
||||
def req_task_group(pack_pool, group, proxy):
|
||||
"""一个坐标召回一次; 包被风控就出池换包重试, 返回 True 表示这组处理完了"""
|
||||
last_header_id = None
|
||||
while True:
|
||||
header_id = get_pack(pack_pool)
|
||||
if header_id is None:
|
||||
print(' 没有可用的模板包')
|
||||
return False
|
||||
template = pack_pool['templates'][header_id]
|
||||
if header_id != last_header_id:
|
||||
set_loc_headers(template['headers'], group['city'], str(int(round(float(group['latitude']) * 1000000))),
|
||||
str(int(round(float(group['longitude']) * 1000000))))
|
||||
print(' 当前模板包 id=%s' % header_id)
|
||||
last_header_id = header_id
|
||||
|
||||
resp = req_recall(template, group, proxy)
|
||||
status = resp.status_code
|
||||
print(' 召回 status=%s' % status)
|
||||
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.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']
|
||||
if not page_data:
|
||||
print(' 该坐标没有召回门店, 响应:', resp.text[:300])
|
||||
return True
|
||||
poi_id_str = page_data['poiIdStr']
|
||||
print(' 门店=%s 距离=%s 城市=%s poiIdStr=%s' % (
|
||||
page_data['wmPoiName'], page_data['distanceToUser'], page_data['cityId'], poi_id_str))
|
||||
update_new_store_id(group['ids'], poi_id_str)
|
||||
print(' 回写 %d 行: 任务id=%s' % (len(group['ids']), group['ids'][:5]))
|
||||
return True
|
||||
|
||||
|
||||
def run_recall():
|
||||
header_rows = get_header_rows()
|
||||
if not header_rows:
|
||||
print('没有可用的模板包')
|
||||
return
|
||||
pack_pool = init_pack_pool(header_rows)
|
||||
proxs = get_proxs()
|
||||
groups = get_task_groups()
|
||||
for group in groups:
|
||||
proxy = get_city_proxy(group['city'], proxs)
|
||||
if not proxy:
|
||||
print(' 城市=%s 没有对应代理, 直连' % group['city'])
|
||||
print('=== %s %s 坐标=%s,%s 任务%d行 proxy=%s ===' % (
|
||||
group['city'], group['address'], group['latitude'], group['longitude'], len(group['ids']), proxy))
|
||||
done = req_task_group(pack_pool, group, proxy)
|
||||
if not done:
|
||||
print('模板包池已空, 停止')
|
||||
break
|
||||
time.sleep(REQ_INTERVAL)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_recall()
|
||||
+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()
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
# 歪马送酒每日采集流程
|
||||
|
||||
顺序:**查批次 → 补门店ID →(券日)券列表 → 券商品 → 搜索**
|
||||
批次由外部准备,本流程不复制批次。
|
||||
|
||||
命令都在本目录执行:`C:\Users\mjz\Desktop\python\9月\歪马送酒\AI代码`
|
||||
|
||||
## 1. 查批次
|
||||
|
||||
```sql
|
||||
select count(*) from waima_keyword_input where batch = 'D';
|
||||
```
|
||||
|
||||
0 行就停,报告"当天批次不存在"。
|
||||
|
||||
## 2. 补门店ID(每天,必须在券和搜索之前)
|
||||
|
||||
```bash
|
||||
python 歪马送酒_按坐标补门店ID.py
|
||||
```
|
||||
|
||||
BATCH 默认当天,不用改。
|
||||
|
||||
## 3. 判券日
|
||||
|
||||
```sql
|
||||
select distinct need_coupon from waima_keyword_input where batch = 'D';
|
||||
```
|
||||
|
||||
`need_coupon = 1` → 跑第 4、5 步;`0` → 跳过券,只跑第 6 步。
|
||||
|
||||
## 4. 券列表(券日)
|
||||
|
||||
改脚本第 46 行 `BATCH = 'D'`,再跑:
|
||||
|
||||
```bash
|
||||
python 歪马送酒_商品券列表.py
|
||||
```
|
||||
|
||||
已入库的店自动跳过,失败的店重跑即补。
|
||||
|
||||
## 5. 券商品(券日)
|
||||
|
||||
```bash
|
||||
python 歪马送酒_shark请求.py
|
||||
```
|
||||
|
||||
无 BATCH 常量;后台跑,进度查库,中断重跑即续:
|
||||
|
||||
```sql
|
||||
select sum(is_ok is null), sum(is_ok = 1) from waima_coupon_list_item;
|
||||
```
|
||||
|
||||
## 6. 关键词搜索(每天)
|
||||
|
||||
改脚本第 30 行 `BATCH = 'D'`,再跑:
|
||||
|
||||
```bash
|
||||
python 歪马送酒_搜索.py
|
||||
```
|
||||
|
||||
## 7. 收尾
|
||||
|
||||
报四项:搜索 `current_page >= page` 完成数、`new_store_id` 补全数、券明细 `is_ok` 分布、两个包池的 `is_ok` 分布。
|
||||
|
||||
---
|
||||
|
||||
## 注意
|
||||
|
||||
- 券是否跑看 `need_coupon`,搜索每天跑;跳过券时不能连搜索一起跳过。
|
||||
- 包池 403/418/406 会掉号,池空脚本直接退出。
|
||||
- 日志块缓冲会滞后,进度一律看库。
|
||||
- 券明细表没有 `batch` 列,按天统计用 `date(created_at)`。
|
||||
- 只改 `BATCH` 常量,不改脚本结构。
|
||||
|
||||
---
|
||||
|
||||
## 8. 完整示例:券日 2026-12-03(实测)
|
||||
|
||||
```bash
|
||||
cd "C:\Users\mjz\Desktop\python\9月\歪马送酒\AI代码"
|
||||
```
|
||||
|
||||
**1)查批次**
|
||||
|
||||
```sql
|
||||
select count(*) from waima_keyword_input where batch = '2026-12-03';
|
||||
-- 228
|
||||
```
|
||||
|
||||
**2)补门店ID**
|
||||
|
||||
```bash
|
||||
python 歪马送酒_按坐标补门店ID.py
|
||||
```
|
||||
|
||||
→ 6 个坐标召回全部 200,`new_store_id` 228/228。
|
||||
|
||||
**3)判券**
|
||||
|
||||
```sql
|
||||
select distinct need_coupon from waima_keyword_input where batch = '2026-12-03';
|
||||
-- 1,跑券
|
||||
```
|
||||
|
||||
**4)券列表**(脚本第 46 行改成 `BATCH = '2026-12-03'`)
|
||||
|
||||
```bash
|
||||
python 歪马送酒_商品券列表.py
|
||||
```
|
||||
|
||||
→ 6 个店全 200,当天新建券明细 401 条。
|
||||
|
||||
```sql
|
||||
select count(*) from waima_coupon_list_item where date(created_at) = '2026-12-03';
|
||||
-- 401
|
||||
```
|
||||
|
||||
**5)券商品**(不改常量,后台跑)
|
||||
|
||||
```bash
|
||||
python 歪马送酒_shark请求.py
|
||||
```
|
||||
|
||||
→ 取全表 `is_ok is null` 401 条(恰好都是当天新建),150 张券、928 页,最终 401/401 完成。
|
||||
|
||||
```sql
|
||||
select sum(is_ok is null), sum(is_ok = 1) from waima_coupon_list_item;
|
||||
-- 0, 401
|
||||
```
|
||||
|
||||
**6)搜索**(脚本第 30 行改成 `BATCH = '2026-12-03'`)
|
||||
|
||||
```bash
|
||||
python 歪马送酒_搜索.py
|
||||
```
|
||||
|
||||
→ 228/228 完成,234 页。日志里的「厦门市 改用省会 福州 代理」是正常兜底。
|
||||
|
||||
**7)收尾**
|
||||
|
||||
- 搜索完成:`current_page >= page` = 228/228
|
||||
- 补门店ID:228/228
|
||||
- 券明细:401 条全部 `is_ok=1`
|
||||
- 包池:查两个 `*_headers` 的 `is_ok` 分布,看 403/418/406 掉号
|
||||
|
||||
> 以上是 2026-12-03 那轮的真实数字,换一天任务量、券数、页数会变,判定逻辑不变。
|
||||
Reference in New Issue
Block a user