Files
xiaoxiang/小象超市详情列表请求部分.py
T
2026-04-15 18:12:30 +08:00

473 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import datetime
import os
import queue
import random
import time
from concurrent.futures import ThreadPoolExecutor
import pymysql
from curl_cffi import requests
import json
from newsetting import All_Setting
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")
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
def get_sign_new(url, data, dfpid, mtg_origin):
headers = {"content-type": "application/json", "token": "jksdfhiownefopwef902fsdf"}
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
def update_headers(is_ok, hd_id):
if is_ok == 1:
update_sql = f"""
UPDATE elephant_headers SET current_count = current_count+1,req_count=req_count+1 WHERE id = {hd_id}
"""
else:
update_sql = f"""
UPDATE elephant_headers SET is_ok = {is_ok} WHERE id = {hd_id}
"""
tent3.update_data(update_sql)
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
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
id_, hd_data = hd[0], json.loads(hd[1])
url = hd_data[0]
url1 = url
headers = hd_data[1]
query = url.split("?", 1)[1]
timestamp = int(time.time())
params = dict(re.findall(r"([^&=]+)=([^&]*)", query))
params.update({"app_trace":params['uuid']+str(timestamp)})
data = hd_data[2]
params.update({"poi": str(shop_id)})
params.update({"stockPois": str(shop_id)})
url1 = f"https://mall.meituan.com/api/c/poi/{str(shop_id)}/sku/list/category/v8?"
url1 = url1 + get_Datatext(params)
data.update({"poiId": shop_id})
data.update({"firstCategoryId": id1})
data.update({"categoryId": id2})
data["secondCategoryInfo"].update({"secondCategoryId": id2})
data.update({"listTag": 0})
if one_all_num != None:
data["pageInfo"].update({"total": 500})
if id1==id2:
data["pageInfo"].update({"total": 150})
data["secondCategoryInfo"].update({"skuCount": 150})
else:
data["pageInfo"].update({"total": 300})
data["secondCategoryInfo"].update({"skuCount": 300})
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'})
if id2 == 1001:
data.update({"type": '2'})
data["secondCategoryInfo"].update({"type": '2'})
elif id2 == 1003:
data.update({"type": '4'})
data["secondCategoryInfo"].update({"type": '4'})
try:
del data["thirdCategoryInfo"]
data.pop("displayedCardMap")
del data["pageInfo"]["currentPage"]
del data["pageInfo"]["pageSize"]
del data["pageInfo"]["curPageOffset"]
del data["pageInfo"]["lastPageOffset"]
del data["pageInfo"]["firstPageSize"]
except:
pass
data1 = json.dumps(data, separators=(",", ":"))
mtg_origin = eval(headers["mtgsig"])
dfpid = mtg_origin["a3"]
openId = headers['openId']
headers['mtgsig'] = get_sign_new1(url1, data1, dfpid, mtg_origin, openId)
headers["Content-Length"] = str(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[:])
# input(56123)
return response, shop_id
# 每个分类都跑一次拿总数(自带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]
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
one_price = req["data"]["contents"][0]["subModule"]["contents"][0]["lxInfo"][
"sale_price"
]
if one_price == "?":
update_headers(406, hd_id)
return 406
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),
)
# tent2.update_data(update_sql)
update_sql = f"""
UPDATE category_detail
SET all_num = {int(req["data"]["pageInfo"]["lastPageOffset"])},
now_num = {num * 20},
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
try:
prox = SHOP_PROX[shop_id]
except:
prox = list(SHOP_PROX.values())[0]
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):
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)
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):
update_headers(403, hd_id)
return 403
if req["data"] == {}:
return 1
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, k, one_id, two_id, json.dumps(req, ensure_ascii=False), workid),
)
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}
"""
tent2.update_data(update_sql)
nextPageOffset = int(req["data"]["pageInfo"]["nextPageOffset"])
update_headers(1, hd_id)
if nextPageOffset == -1:
break
return 1
# 拿到请求头部
def get_hds():
sql3 = f"""
select id,json_data FROM elephant_headers where is_ok is null and channel = '详情' and created_at >'2026-04-14'
"""
da = tent3.get_shoppingmalls(sql3)
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():
if one_all(workid, hd, work_queue) !=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 all_num = 0 and is_ok = 0 and now_num = 0
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=5) 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):
work_queue = queue.Queue()
shop_ids_sql = ",".join(map(str, shop_id_list))
sql_all_pending = f"""
select id,shop_id,one_id,two_id,one_all_num,now_num FROM category_detail where one_all_num > now_num and work_id='{workid}' and shop_id in ({shop_ids_sql})
"""
print(sql_all_pending)
# input(45623)
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)
# worker(workid, hds[0], work_queue)
SHOP_ID_LIST = [
10000439,
10000900,
10000880,
10000665,
10000839,
10000519,
10001060,
10000163,
10000952,
10000956,
10001084,
10001075,
10001107,
10001195,
10001222,
10001400,
# 10001506,
# 10001575,
]
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,
]
CITY_PROX = {}
SHOP_PROX = {}
def get_prox():
sql = '''
SELECT city,prox_data FROM `proxs_list`
'''
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():
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
return os.environ.get("ELEPHANT_WORKID", workid)
def get_shop_id_list():
shop_ids = os.environ.get(SHOP_IDS_ENV)
if not shop_ids:
return SHOP_ID_LIST
return [int(shop_id.strip()) for shop_id in shop_ids.split(",") if shop_id.strip()]
def main():
hds = get_hds()
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)
#
if __name__ == "__main__":
get_prox()
# print(list(SHOP_PROX.values())[0])
main()