This commit is contained in:
mjz
2026-10-28 13:44:01 +08:00
parent 8bfe38e9dc
commit 050b2afc82
12 changed files with 1928 additions and 412 deletions
+131 -310
View File
@@ -1,53 +1,80 @@
import datetime
import json
import math
import os
import queue
import random
import re
import sys
import time
from concurrent.futures import ThreadPoolExecutor
import pymysql
from curl_cffi import requests
import json
from newsetting import All_Setting
import redis_lock_get_data
tent2 = All_Setting(host="183.6.7.91", port=33016, db="tk_test")
tent3 = All_Setting(host="183.6.7.91", port=33016, db="headers_project")
sys.path.insert(0, r"C:\Users\mjz\Desktop\python\mjz\小程序逆向\AI代码") # 自己的小程序出签服务客户端
from 小程序mtgsig import get_mtgsig
def get_sign_new1(url, data, dfpid, mtg_origin,openId):
headers = {"content-type": "application/json", "token": "test_sdfio23923ojbedfojgbouqgew4r32dds"}
body = {
"mtg_origin":mtg_origin,
"url": url,
"data": data,
"dfpid": dfpid,
"method": "POST",
"open_id": openId,# 微信的open_id
}
url = 'http://129.211.12.35:18003/minipro_mt_0206'
req = requests.post(url, headers=headers, json=body, proxies={'http': None, 'https': None}, verify=False).text
return req
tent2 = All_Setting(host="183.6.7.91", port=33016, db="tk_test") # category_detail / category_detail_log
tent3 = All_Setting(host="192.168.5.2", port=3307, db="headers_project") # 账号池 / 代理池
def get_sign_new(url, data, dfpid, mtg_origin):
headers = {"content-type": "application/json", "token": "jksdfhiownefopwef902fsdf"}
SHOP_ID_LIST = [
# 10000439,
# 10000900,
# 10000880,
# 10000665,
# 10000839,
# 10000519,
# 10001060,
# 10000163,
# 10000952,
# 10000956,
# 10001084,
# 10001075,
# 10001107,
# 10001195,
# 10001222,
# 10001400,
# 10001506,
# 10001575,
body = {
"mtg_origin": mtg_origin,
"url": url,
"data": data,
"dfpid": dfpid,
"method": "POST",
}
# url = "http://124.222.120.219:18003/hz_wm_jym_1008"
url = "http://8.138.127.139:10063/newmtgsig"
req = requests.post(
url,
headers=headers,
json=body,
proxies={"http": None, "https": None},
verify=False,
).text
return req
# 10000745,
10000665, # 华发站
]
SHOP_IDS_ENV = "ELEPHANT_SHOP_IDS" # 逗号分隔的店铺ID
ONE_NAMES = [ # 只采这些一级分类
"水果鲜花", "蔬菜豆制品", "肉禽蛋", "海鲜水产", "乳品烘焙", "粮油调味",
"熟食快手菜", "冻品面点", "酒水饮料", "休闲零食", "零食冰淇淋", "日用清洁", "个护美妆",
]
SKIP_SECOND = [ # 这些二级分类不采
"时令推荐", "为你推荐", "超低折扣", "会员折扣", "会员专区", "3件8折", "全部", "严选", "新品上架", "时令/新品",
]
city_dict = { # 店铺ID -> 城市,用来取对应城市的代理
10000439: "上海",
10000900: "杭州",
10000880: "北京",
10000665: "深圳",
10000839: "苏州",
10000519: "广州",
10001060: "南京",
10000163: "佛山",
10000952: "东莞",
10000956: "无锡",
10001084: "宁波",
10001075: "常州",
10001107: "绍兴",
10001195: "嘉兴",
10001222: "南通",
10001400: "扬州",
10001506: "金华",
10001575: "温州",
}
CITY_PROX = {} # 城市 -> 代理
SHOP_PROX = {} # 店铺ID -> 代理
def update_headers(is_ok, hd_id):
@@ -72,64 +99,17 @@ def get_Datatext(dataq):
return data
def return_id1(keyword1, keyword2):
import json
with open("all", "r", encoding="utf-8") as f:
data = json.load(f)
alllist = []
for i in data["data"]["poiCategories"]: # 一级标签
onelist = i.get("subPoiCategories", [])
two_list = []
if onelist == []:
continue
else:
for y in onelist:
two_list.append(
{
"id": y["id"],
"name": y["name"],
}
)
alllist.append({"id": i["id"], "name": i["name"], "twolist": two_list})
# print(alllist)
for k in alllist:
if k["name"] == keyword1:
id1 = k["id"]
for y in k["twolist"]:
if y["name"] == keyword2:
id2 = y["id"]
return (id1, id2)
else:
continue
else:
continue
def next_or(response):
if response.json()["data"]["pageInfo"]["nextPageOffset"] != -1:
return True
else:
return False
# 单次访问
def one_(id1, id2, num, shop_id, hd,prox, one_all_num=None):
import re
def one_(id1, id2, num, shop_id, hd, prox, one_all_num=None):
id_, hd_data = hd[0], json.loads(hd[1])
url = hd_data[0]
url1 = url
url1 = hd_data[0]
headers = hd_data[1]
query = url.split("?", 1)[1]
query = url1.split("?", 1)[1]
timestamp = int(time.time())
timestamp_ms = int(time.time())*1000
params = dict(re.findall(r"([^&=]+)=([^&]*)", query))
data = hd_data[2]
params.update({"poi": str(shop_id)})
params.update({"stockPois": str(shop_id)})
params.update({"app_trace":params['uuid']+str(timestamp)})
# params.update({"app_trace":params['uuid']+str(timestamp_ms)})
params.update({"app_trace": params["uuid"] + str(timestamp)})
url1 = f"https://mall.meituan.com/api/c/poi/{str(shop_id)}/sku/list/category/v8?"
url1 = url1 + get_Datatext(params)
data.update({"poiId": str(shop_id)})
@@ -139,27 +119,25 @@ def one_(id1, id2, num, shop_id, hd,prox, one_all_num=None):
data.update({"listTag": 0})
if one_all_num != None:
data["pageInfo"].update({"total": 500})
if id1==id2:
if id1 == id2:
data["pageInfo"].update({"total": 150})
data["secondCategoryInfo"].update({"skuCount": 150})
else:
data["pageInfo"].update({"total": 500})
data["secondCategoryInfo"].update({"skuCount": 500})
data["pageInfo"].update({"prePageOffset": max(0,(num - 2)) * 20})
data["pageInfo"].update({"prePageOffset": max(0, (num - 2)) * 20})
data["pageInfo"].update({"offset": (num - 1) * 20})
data["pageInfo"].update({"nextPageOffset": (num - 1) * 20})
data.update({"cacheKey": f'cate_{shop_id}_{params["userid"]}_{id1}_1'})
# data.update({"type": '1'})
# data["secondCategoryInfo"].update({"type": '1'})
data.update({"type": '0'})
data["secondCategoryInfo"].update({"type": '0'})
data.update({"type": "0"})
data["secondCategoryInfo"].update({"type": "0"})
if id2 == 1001:
data.update({"type": '2'})
data["secondCategoryInfo"].update({"type": '2'})
data.update({"type": "2"})
data["secondCategoryInfo"].update({"type": "2"})
elif id2 == 1003:
data.update({"type": '4'})
data["secondCategoryInfo"].update({"type": '4'})
data.update({"type": "4"})
data["secondCategoryInfo"].update({"type": "4"})
try:
del data["thirdCategoryInfo"]
data.pop("displayedCardMap")
@@ -171,120 +149,48 @@ def one_(id1, id2, num, shop_id, hd,prox, one_all_num=None):
except:
pass
data1 = json.dumps(data, separators=(",", ":"))
mtg_origin = eval(headers["mtgsig"])
dfpid = mtg_origin["a3"]
openId = headers['openId']
# headers['mtgsig'] = get_sign_new(url1, data1, dfpid, mtg_origin)
headers['mtgsig'] = get_sign_new1(url1, data1, dfpid, mtg_origin, openId)
if 'openId' in headers:
openId = headers["openId"]
else:
openId = headers["openid"]
headers["mtgsig"] = get_mtgsig(url1, data1, headers["mtgsig"], openId, "POST") # 走自己的小程序出签服务;r/envVersion 等从包里 a5/a6 自动复用
headers["Content-Length"] = len(data1)
response = requests.post(url1, headers=headers, data=data1, proxies=prox, verify=False)
# response = requests.post(url1, headers=headers, data=data1,verify=False)
print(response.text[:])
return response, shop_id
def 获取小象task():
# get_hotel
datas = redis_lock_get_data.get_hotel()
return datas
# 每个分类都跑一次拿总数(自带20)
def all_one(shop_id, workid, hd, work_queue):
num = 1
try:
i = work_queue.get_nowait()
except queue.Empty:
return 1
detail_id = i[0]
hd_id = hd[0]
shop_id = i[1]
try:
prox = SHOP_PROX[shop_id]
except:
prox = list(SHOP_PROX.values())[0]
prox = list(SHOP_PROX.values())[random.randint(0, len(SHOP_PROX) - 1)]
req, shop_id = one_(i[2], i[4], num, shop_id, hd, prox)
if "您的网络好像不太给力" in req.text:
update_headers(418, hd_id)
return 418
try:
req = req.json()
except Exception as e:
print("号有问题")
print(str(e))
if "Expecting value: line 1 column 1 (char 0)" in str(e) or 'unexpected character: line 1 column 1 (char 0)' in str(e):
update_headers(403, hd_id)
return 403
print(req)
if req["data"] == {}:
print("账号没访问到" * 20)
print("下一个账号试试" * 20)
# tent2.write_data_one(
# """
# INSERT INTO category_detail_log
# (shop_id,category_detail_id, one_id, two_id, req_json,work_id)
# VALUES (%s,%s, %s, %s, %s,%s)
# """,
# (shop_id, num, i[2], i[4], json.dumps(req, ensure_ascii=False),format_today)
# )
# tent2.update_data(update_sql)
return 0
for jj in req["data"]["contents"][0]["subModule"]["contents"]:
one_price = jj["lxInfo"].get("sale_price")
if one_price:
if one_price == "?":
update_headers(406, hd_id)
return 406
else:
break
tent2.write_data_one(
"""
INSERT INTO category_detail_log
(shop_id,category_detail_id, one_id, two_id, req_json,work_id)
VALUES (%s,%s, %s, %s, %s,%s)
""",
(shop_id, num, i[2], i[4], json.dumps(req, ensure_ascii=False), workid),
)
update_sql = f"""
UPDATE category_detail
SET all_num = {int(req["data"]["pageInfo"]["lastPageOffset"])},
is_ok = 1,
one_all_num = {int(req["data"]["pageInfo"]["total"])}
WHERE `id` = {detail_id}
"""
tent2.update_data(update_sql)
update_headers(1, hd_id)
return 1
# 一个分类跑完
def one_all(workid, hd, work_queue):
import math
try:
item = work_queue.get_nowait()
except queue.Empty:
return 1
detail_id, shop_id, one_id, two_id, one_all_num, now_num = item
detail_id, shop_id, one_id, two_id, all_num, now_num = item
if not all_num:
all_num = 400 # 分类接口没给 skuCount 的按 400 兜底,翻到 nextPageOffset=-1 为止
try:
prox = SHOP_PROX[shop_id]
except:
prox = list(SHOP_PROX.values())[0]
if one_all_num is None:
one_all_num = 400
all_num = math.ceil(one_all_num / 20) + 1
now_num = math.ceil(now_num / 20) + 1
for k in range(now_num, all_num):
all_page = math.ceil(all_num / 20) + 1
now_page = math.ceil(now_num / 20) + 1
for k in range(now_page, all_page):
print(f"now_num是{k}")
hd_id = hd[0]
req, shop_id = one_(one_id, two_id, k, shop_id, hd,prox, one_all_num)
req, shop_id = one_(one_id, two_id, k, shop_id, hd, prox, all_num)
if "您的网络好像不太给力" in req.text:
update_headers(418, hd_id)
return 418
try:
req = req.json()
except Exception as e:
print(f'出问题的情况是{e}')
if "Expecting value: line 1 column 1 (char 0)" in str(e) or '403 Forbidden' in str(e) or 'unexpected character: line 1 column 1 (char 0)' in str(e):
print(f"出问题的情况是{e}")
if "Expecting value: line 1 column 1 (char 0)" in str(e) or "403 Forbidden" in str(e) or "unexpected character: line 1 column 1 (char 0)" in str(e):
update_headers(403, hd_id)
return 403
if req["data"] == {}:
@@ -305,14 +211,16 @@ def one_all(workid, hd, work_queue):
""",
(shop_id, k, one_id, two_id, json.dumps(req, ensure_ascii=False), workid),
)
page_now_num = k * 20
if all_num and page_now_num == all_num:
page_now_num = all_num + 20 # 本分类数量正好是 20 的整数倍时,把 now_num 推过 all_num,否则完成判断 now_num>all_num 永远不成立
update_sql = f"""
UPDATE category_detail
SET all_num = {int(req["data"]["pageInfo"]["lastPageOffset"])},
now_num = {k * 20},
is_ok = 1,
one_all_num = {int(req["data"]["pageInfo"]["total"])}
WHERE `id` = {detail_id}
"""
UPDATE category_detail
SET now_num = {page_now_num},
is_ok = 1,
one_all_num = {int(req["data"]["pageInfo"]["total"])}
WHERE `id` = {detail_id}
"""
tent2.update_data(update_sql)
nextPageOffset = int(req["data"]["pageInfo"]["nextPageOffset"])
update_headers(1, hd_id)
@@ -321,14 +229,11 @@ def one_all(workid, hd, work_queue):
return 1
# 一个分类跑完
def one_all2(workid, hd, work_queue):
import math
item_list = 获取小象task()
print(item_list)
for item in item_list:
detail_id, shop_id, one_id, two_id, one_all_num, now_num,workid = item
detail_id, shop_id, one_id, two_id, one_all_num, now_num, workid = item
try:
prox = SHOP_PROX[shop_id]
except:
@@ -341,15 +246,15 @@ def one_all2(workid, hd, work_queue):
for k in range(now_num, all_num):
print(f"now_num是{k}")
hd_id = hd[0]
req, shop_id = one_(one_id, two_id, k, shop_id, hd,prox, one_all_num)
req, shop_id = one_(one_id, two_id, k, shop_id, hd, prox, one_all_num)
if "您的网络好像不太给力" in req.text:
update_headers(418, hd_id)
return 418
try:
req = req.json()
except Exception as e:
print(f'出问题的情况是{e}')
if "Expecting value: line 1 column 1 (char 0)" in str(e) or '403 Forbidden' in str(e) or 'unexpected character: line 1 column 1 (char 0)' in str(e):
print(f"出问题的情况是{e}")
if "Expecting value: line 1 column 1 (char 0)" in str(e) or "403 Forbidden" in str(e) or "unexpected character: line 1 column 1 (char 0)" in str(e):
update_headers(403, hd_id)
return 403
if req["data"] == {}:
@@ -395,7 +300,6 @@ def one_all2(workid, hd, work_queue):
return 1
# 拿到请求头部
def get_hds():
sql3 = f"""
select id,json_data FROM elephant_headers where is_ok is null and channel = '详情'
@@ -404,149 +308,67 @@ def get_hds():
return da
def worker_allone(shop_id, workid, hd, work_queue):
while not work_queue.empty():
if all_one(shop_id, workid, hd, work_queue) != 1:
break
# time.sleep(random.randint(2, 4))
# all_one(shop_id, workid, hd, work_queue)
def worker(workid, hd, work_queue):
while not work_queue.empty():
result = one_all(workid, hd, work_queue)
print(result)
if result !=1:
if result != 1:
break
# time.sleep(random.randint(3, 15))
# one_all(workid, hd, work_queue)
def run_all_one(hds, workid, shop_id_list, one_ids):
work_queue_allone = queue.Queue()
item_list = []
for shop_id in shop_id_list:
sql_all_one_pending = f"""
select * FROM category_detail
where one_id in ({",".join(map(str, one_ids))})
and is_ok is null
and shop_id='{shop_id}' and work_id='{workid}'
"""
items = tent2.get_shoppingmalls(sql_all_one_pending)
for item in items:
item_list.append(item)
work_queue_allone.put(item)
print(item_list)
with ThreadPoolExecutor(max_workers=10) as pool:
for hd in hds:
pool.submit(worker_allone, 0, workid, hd, work_queue_allone)
# for hd in hds:
# worker_allone(0,workid,hd,work_queue_allone)
def run_one_all(hds, workid, shop_id_list, one_ids):
def run_one_all(hds, workid, shop_id_list, one_names):
work_queue = queue.Queue()
shop_ids_sql = ",".join(map(str, shop_id_list))
one_names_sql = ",".join(f"'{name}'" for name in one_names)
skip_second_sql = ",".join(f"'{name}'" for name in SKIP_SECOND)
sql_all_pending = f"""
select id,shop_id,one_id,two_id,one_all_num,now_num FROM category_detail where one_id in ({",".join(map(str, one_ids))}) and work_id='{workid}' and shop_id in ({shop_ids_sql}) and is_ok2 is null and (one_all_num is null or (one_all_num > now_num))
WITH c AS (
SELECT id, shop_id, one_id, two_id, all_num, now_num, three_id, three_name,
MAX(three_name = '全部') OVER (PARTITION BY one_id, two_id) AS has_quan
FROM category_detail
WHERE work_id = '{workid}'
AND shop_id IN ({shop_ids_sql})
AND one_name IN ({one_names_sql})
AND two_name NOT IN ({skip_second_sql})
)
SELECT id, shop_id, one_id, two_id, all_num, now_num FROM c
WHERE now_num <= all_num
AND (three_id IS NULL OR has_quan = 0 OR three_name = '全部')
"""
print(sql_all_pending)
items = tent2.get_shoppingmalls(sql_all_pending)
for item in items[:]:
work_queue.put(item)
# with ThreadPoolExecutor(max_workers=5) as pool:
# for hd in hds:
# pool.submit(worker, workid, hd, work_queue)
for hd in hds:
worker(workid, hd, work_queue)
def run_one_all2(hds, workid, shop_id_list):
# with ThreadPoolExecutor(max_workers=10) as pool:
# for hd in hds:
# pool.submit(one_all2, workid, hd, '')
# for hd in hds:
# one_all2(workid, hd, '')
one_all2(workid, hds[0], '')
one_all2(workid, hds[0], "")
SHOP_ID_LIST = [
# 10000439,
# 10000900,
# 10000880,
# 10000665,
# 10000839,
# 10000519,
# 10001060,
# 10000163,
# 10000952,
# 10000956,
# 10001084,
# 10001075,
# 10001107,
# 10001195,
# 10001222,
# 10001400,
# 10001506,
# 10001575,
10000745,
]
SHOP_IDS_ENV = "ELEPHANT_SHOP_IDS"
city_dict = {
10000439: "上海",
10000900: "杭州",
10000880: "北京",
10000665: "深圳",
10000839: "苏州",
10000519: "广州",
10001060: "南京",
10000163: "佛山",
10000952: "东莞",
10000956: "无锡",
10001084: "宁波",
10001075: "常州",
10001107: "绍兴",
10001195: "嘉兴",
10001222: "南通",
10001400: "扬州",
10001506: "金华",
10001575: "温州",
}
ONE_IDS = [
# 40532,
# 40488,
# 40581,
# 40652,
# 40461,
# 40916,
# 40478,
# 40455,
# 40485,
# 40472,
# 49207,
# 42793,
40485,
]
CITY_PROX = {}
SHOP_PROX = {}
def get_prox():
sql = '''
sql = """
SELECT city,prox_data FROM `proxs_list`
'''
city_tuple=tent3.get_shoppingmalls(sql)
"""
city_tuple = tent3.get_shoppingmalls(sql)
for i in city_tuple:
CITY_PROX[i[0]] = json.loads(i[1])
for key,value in city_dict.items():
for key, value in city_dict.items():
if value in CITY_PROX:
SHOP_PROX[key] = CITY_PROX[value]
return CITY_PROX
def get_workid():
format_today = str(datetime.date.today()).replace("-", "")
workid = format_today
workid = '20261027'
return os.environ.get("ELEPHANT_WORKID", workid)
@@ -562,11 +384,10 @@ def main():
print(hds)
workid = get_workid()
shop_id_list = get_shop_id_list()
# run_all_one(hds, workid, shop_id_list, ONE_IDS)
run_one_all(hds, workid, shop_id_list, ONE_IDS)
run_one_all(hds, workid, shop_id_list, ONE_NAMES)
# run_one_all2(hds, workid, shop_id_list)
if __name__ == "__main__":
get_prox()
# print(list(SHOP_PROX.values())[0])
main()
main()