upload
This commit is contained in:
@@ -0,0 +1,890 @@
|
||||
import datetime
|
||||
import json
|
||||
import os.path
|
||||
import queue
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures.thread import ThreadPoolExecutor
|
||||
|
||||
import pandas
|
||||
import json
|
||||
import random
|
||||
import time
|
||||
import math
|
||||
import newsetting as ten
|
||||
import uuid
|
||||
# import requests
|
||||
import jsonpath
|
||||
from curl_cffi import requests
|
||||
import redis
|
||||
from mjz_sql import Mysql
|
||||
_verify_logged_ids: set[str] = set()
|
||||
_verify_log_lock = threading.Lock()
|
||||
tent = ten.All_Setting(host='192.168.5.2',port=3307,db='mt_newretail')
|
||||
tent2 = ten.All_Setting(host='192.168.5.2',port=3307,db='headers_project')
|
||||
mt_团购_搜索 = redis.StrictRedis(host='124.220.48.127', port=6379, db=0, password='ader146090', decode_responses=True)
|
||||
|
||||
MAX = 100000
|
||||
|
||||
# 账号→代理绑定记忆(按 workid 分区,重启后仍跑同一城市/代理)
|
||||
PROXY_MEMORY_PATH = os.path.join(
|
||||
os.path.dirname(os.path.abspath(__file__)), 'render_proxy_memory.json'
|
||||
)
|
||||
|
||||
|
||||
def load_proxy_memory():
|
||||
if not os.path.isfile(PROXY_MEMORY_PATH):
|
||||
return {}
|
||||
try:
|
||||
with open(PROXY_MEMORY_PATH, 'r', encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
except Exception as e:
|
||||
print(f'[记忆] 读取失败,将重建: {e}')
|
||||
return {}
|
||||
|
||||
|
||||
def save_proxy_memory(data):
|
||||
with open(PROXY_MEMORY_PATH, 'w', encoding='utf-8') as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=2)
|
||||
|
||||
|
||||
def assign_queues_with_memory(account_ids, grouped_queues, workid):
|
||||
"""
|
||||
把账号绑到代理队列:有记忆且该代理仍有任务则复用;否则轮询新绑并写入文件。
|
||||
返回 [(prox_key, work_queue), ...] 与 account_ids 一一对应。
|
||||
"""
|
||||
memory_all = load_proxy_memory()
|
||||
wid = str(workid)
|
||||
bindings = dict(memory_all.get(wid, {}))
|
||||
prox_keys = list(grouped_queues.keys())
|
||||
if not prox_keys:
|
||||
return [], bindings
|
||||
|
||||
result = [None] * len(account_ids)
|
||||
unbound = []
|
||||
|
||||
for i, aid in enumerate(account_ids):
|
||||
key = str(aid)
|
||||
saved = bindings.get(key)
|
||||
if saved is not None and saved in grouped_queues:
|
||||
result[i] = (saved, grouped_queues[saved])
|
||||
print(f'[记忆] 账号 {aid} 复用代理: {str(saved)[:50]}... (队列 {grouped_queues[saved].qsize()})')
|
||||
else:
|
||||
if saved is not None:
|
||||
print(f'[记忆] 账号 {aid} 原代理已无任务,重新分配')
|
||||
unbound.append(i)
|
||||
|
||||
rr = 0
|
||||
for i in unbound:
|
||||
prox = prox_keys[rr % len(prox_keys)]
|
||||
rr += 1
|
||||
result[i] = (prox, grouped_queues[prox])
|
||||
bindings[str(account_ids[i])] = prox
|
||||
print(f'[记忆] 账号 {account_ids[i]} 新绑定代理: {str(prox)[:50]}... (队列 {grouped_queues[prox].qsize()})')
|
||||
|
||||
memory_all[wid] = bindings
|
||||
save_proxy_memory(memory_all)
|
||||
print(f'[记忆] 已写入 {PROXY_MEMORY_PATH} (workid={wid}, 绑定 {len(bindings)} 条)')
|
||||
return result, bindings
|
||||
|
||||
|
||||
def get_render_current_count(account_id):
|
||||
rows = tent2.get_shoppingmalls(
|
||||
f"SELECT current_count FROM market_render_headers_tk_test WHERE id='{account_id}'"
|
||||
)
|
||||
return rows[0][0] if rows else MAX
|
||||
|
||||
|
||||
def try_inc_render_count(account_id):
|
||||
sql = f'''
|
||||
UPDATE market_render_headers_tk_test
|
||||
SET req_count = req_count + 1, current_count = current_count + 1
|
||||
WHERE id = '{account_id}' AND current_count < {MAX}
|
||||
'''
|
||||
return tent2.update_data(sql)
|
||||
|
||||
|
||||
proxy_config = {
|
||||
'http': 'http://uTn95cM80G_1:gnSUgj7D@112.28.237.136:35782',
|
||||
'https': 'http://uTn95cM80G_1:gnSUgj7D@112.28.237.136:35782'
|
||||
}
|
||||
|
||||
def fix_cyrillic(text):
|
||||
cyrillic_to_latin = {
|
||||
'А': 'A', 'В': 'B', 'С': 'C', 'Е': 'E', 'Н': 'H',
|
||||
'І': 'I', 'Ј': 'J', 'К': 'K', 'М': 'M', 'О': 'O',
|
||||
'Р': 'P', 'Т': 'T', 'Х': 'X', 'а': 'a', 'е': 'e',
|
||||
'о': 'o', 'р': 'p', 'с': 'c', 'х': 'x'
|
||||
}
|
||||
if text is None:
|
||||
return "Mozilla/5.0"
|
||||
if not isinstance(text, str):
|
||||
text = str(text)
|
||||
for cyr, lat in cyrillic_to_latin.items():
|
||||
text = text.replace(cyr, lat)
|
||||
text = text.replace('\r', ' ').replace('\n', ' ').strip()
|
||||
if not text:
|
||||
return "Mozilla/5.0"
|
||||
return text
|
||||
|
||||
def mock_human_move_latlng(lat, lng, min_move_m=8, max_move_m=120):
|
||||
input_is_int = isinstance(lat, int) and isinstance(lng, int)
|
||||
if input_is_int:
|
||||
base_lat = lat / 1_000_000
|
||||
base_lng = lng / 1_000_000
|
||||
else:
|
||||
base_lat = float(lat)
|
||||
base_lng = float(lng)
|
||||
if random.random() < 0.85:
|
||||
move_m = random.uniform(min_move_m, max_move_m * 0.45)
|
||||
else:
|
||||
move_m = random.uniform(max_move_m * 0.45, max_move_m)
|
||||
angle = random.uniform(0, 2 * math.pi)
|
||||
delta_lat = (move_m * math.cos(angle)) / 111_320
|
||||
cos_lat = max(0.000001, abs(math.cos(math.radians(base_lat))))
|
||||
delta_lng = (move_m * math.sin(angle)) / (111_320 * cos_lat)
|
||||
new_lat = base_lat + delta_lat
|
||||
new_lng = base_lng + delta_lng
|
||||
if input_is_int:
|
||||
return int(round(new_lat * 1_000_000)), int(round(new_lng * 1_000_000))
|
||||
return new_lat, new_lng
|
||||
|
||||
def random_user_agent():
|
||||
android_versions = ["10", "11", "12", "13", "14"]
|
||||
build_ids = ["UP1A.231005.007", "TKQ1.221114.001", "SP1A.210812.016", "TP1A.220624.014"]
|
||||
models = [
|
||||
"SEA-AL10", "OCE-AN10", "NOH-AN00", "BLA-AL00",
|
||||
"M2012K11AC", "23013RK75C", "2211133C", "PJD110"
|
||||
]
|
||||
chrome_versions = ["124.0.6367.179", "125.0.6422.165", "126.0.6478.110", "127.0.6533.103"]
|
||||
micro_versions = ["8.0.56.2800", "8.0.57.2801", "8.0.58.2802", "8.0.60.2860"]
|
||||
hex_versions = ["0x28003A53", "0x28003B54", "0x28003C55"]
|
||||
net_types = ["WIFI", "4G", "5G"]
|
||||
return (
|
||||
f"Mozilla/5.0 (Linux; Android {random.choice(android_versions)}; "
|
||||
f"{random.choice(models)} Build/{random.choice(build_ids)}; wv) "
|
||||
f"AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 "
|
||||
f"Chrome/{random.choice(chrome_versions)} Mobile Safari/537.36 "
|
||||
f"MicroMessenger/{random.choice(micro_versions)}({random.choice(hex_versions)}) "
|
||||
f"WeChat/arm64 Weixin NetType/{random.choice(net_types)} "
|
||||
f"Language/zh_CN ABI/arm64 MiniProgramEnv/android"
|
||||
)
|
||||
|
||||
def received_products(req,workid,parent_id,parent_id2,mt_org_id,poi_id_str,business_code):
|
||||
# req, data = reqs['req'], reqs['data']
|
||||
tag2_id = -1
|
||||
|
||||
als = []
|
||||
product_spu_list = req['data']['product_spu_list']
|
||||
for i in product_spu_list:
|
||||
product_id = i.get('id')
|
||||
product_name = i.get('name')
|
||||
description = i.get('description')
|
||||
praise_content = i.get('praise_content')
|
||||
month_saled_content = i.get('month_saled_content')
|
||||
want_to_buy_content = i.get('want_to_buy_content')
|
||||
skus = i.get('skus')
|
||||
tag = i.get('tag')
|
||||
vague_picture1 = i.get('vague_picture')
|
||||
if bool(vague_picture1):
|
||||
vague_picture = 1
|
||||
else:
|
||||
vague_picture = 0
|
||||
promotion_info = i.get('promotion_info')
|
||||
activity_tag_id = i.get('activity_tag_id')
|
||||
praise_rate = i.get('praise_rate')
|
||||
picture = i.get('picture').split('@')[0]
|
||||
product_label_picture_list1 = i.get('product_label_picture_list')
|
||||
if bool(product_label_picture_list1):
|
||||
product_label_picture_list2 = jsonpath.jsonpath(product_label_picture_list1, '$..picture_url')
|
||||
if product_label_picture_list2[
|
||||
0] == 'http://p0.meituan.net/scarlett/d3dae8d854c641b23f7356a3b579f2511455.png':
|
||||
product_label_picture_list = '上新'
|
||||
elif product_label_picture_list2[
|
||||
0] == 'http://p0.meituan.net/scarlett/01c47377f36a321a207f88f1cf61ac8b2690.png':
|
||||
product_label_picture_list = '力荐'
|
||||
else:
|
||||
product_label_picture_list = '其他'
|
||||
else:
|
||||
product_label_picture_list = ''
|
||||
# 更新部分
|
||||
dynamic_act_labels = i.get('dynamic_act_labels')
|
||||
dynamic_text = ''
|
||||
dynamic_url = ''
|
||||
|
||||
if bool(dynamic_act_labels):
|
||||
dynamic_text = str(jsonpath.jsonpath(dynamic_act_labels, '$..text'))
|
||||
dynamic_url = jsonpath.jsonpath(dynamic_act_labels, '$..url')
|
||||
if bool(dynamic_url) is True and 'https://p0.meituan.net/travelcube/48f67218791d7d832adce596bfb627cc4289.png' in dynamic_url:
|
||||
dynamic_url = '超值单品'
|
||||
else:
|
||||
print(dynamic_url)
|
||||
pass
|
||||
|
||||
for b in skus:
|
||||
skus_id = b.get('id')
|
||||
combine = b.get('combine_spec')
|
||||
spec = combine if combine is not None and combine != '' else b.get('spec')
|
||||
if spec == '':
|
||||
try:
|
||||
c = i.get('sku_attrs_map').get(str(skus_id))
|
||||
spec = ",".join([f"{tk['name']}:{tk['value']}" for tk in c])
|
||||
except:
|
||||
pass
|
||||
price = b.get('price')
|
||||
origin_price = b.get('origin_price')
|
||||
upccode = b.get('upccode')
|
||||
stock_label = b.get('stock_label')
|
||||
real_stock = b.get('real_stock')
|
||||
unify_price = b.get('unify_price')
|
||||
|
||||
actual_price2 = jsonpath.jsonpath(unify_price, '$..actual_price_info.actual_price')
|
||||
if bool(actual_price2):
|
||||
actual_price = actual_price2[0]
|
||||
else:
|
||||
actual_price = None
|
||||
if bool(unify_price):
|
||||
activity_info = unify_price['activity_info']
|
||||
quota_per_order = activity_info['quota_per_order'] # 优惠购买限额
|
||||
min_order_count = activity_info['min_order_count'] # 起购份数
|
||||
activity_price = activity_info['activity_price'] # 动态活动价
|
||||
else:
|
||||
activity_info = ''
|
||||
quota_per_order = '' # 优惠购买限额
|
||||
min_order_count = '' # 起购份数
|
||||
activity_price = '' # 动态活动价
|
||||
da2 = (mt_org_id,poi_id_str,workid, parent_id, parent_id2, tag2_id, product_id, product_name, description, praise_content,
|
||||
month_saled_content, skus_id, spec, actual_price, price,
|
||||
origin_price, activity_price, min_order_count, quota_per_order, dynamic_text, dynamic_url,
|
||||
upccode,
|
||||
want_to_buy_content, praise_rate, picture, promotion_info, tag, activity_tag_id, real_stock,
|
||||
stock_label, product_label_picture_list, vague_picture,business_code)
|
||||
print(len(da2))
|
||||
als.append(da2)
|
||||
insert_sql = """
|
||||
insert into productslist (mt_org_id,poi_id_str,workid,parent_id,parent2_id,tag2_id,product_id, product_name, description, praise_content, month_saled_content, skus_id, spec,actual_price, price,origin_price, activity_price, min_order_count, quota_per_order, dynamic_text, dynamic_url,upccode,want_to_buy_content, praise_rate, picture, promotion_info, tag, activity_tag_id, real_stock,stock_label, product_label,vague_picture,business_code) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
"""
|
||||
try:
|
||||
tent.write_data(insert_sql, als)
|
||||
except:
|
||||
time.sleep(2)
|
||||
tent.write_data(insert_sql, als)
|
||||
return True
|
||||
|
||||
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 get_sign_new(url, data, dfpid, mtg_origin):
|
||||
headers = {"content-type": "application/json", "token": "test_fhbosdhf789folhwdjfbiugwqedfrfugdsfsdf"}
|
||||
|
||||
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'
|
||||
# 签名走直连,不要传 proxies={'http': None, ...}
|
||||
req = requests.post(url, headers=headers, json=body, verify=False, timeout=30).text
|
||||
print(req)
|
||||
return req
|
||||
|
||||
# 新接口的mtg(需要微信的open_id)
|
||||
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://124.222.120.219:18003/hz_wm_jym_1008"
|
||||
url = 'http://129.211.12.35:18003/minipro_mt_0206'
|
||||
req = requests.post(url, headers=headers, json=body, verify=False, timeout=30).text
|
||||
print(req)
|
||||
return req
|
||||
|
||||
|
||||
def append_verify_log_once(package_id, content: str) -> bool:
|
||||
"""同一包 id 仅追加一条记录,返回 True 表示本次已写入。"""
|
||||
pid = str(package_id)
|
||||
with _verify_log_lock:
|
||||
if pid in _verify_logged_ids:
|
||||
return False
|
||||
_verify_logged_ids.add(pid)
|
||||
log_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'verify_log.json')
|
||||
with open(log_path, 'a', encoding='utf-8') as f:
|
||||
f.write(content.rstrip())
|
||||
f.write(',\n\n')
|
||||
return True
|
||||
|
||||
def url_encode_query_string(qs):
|
||||
"""
|
||||
对 query string 进行标准 URL 编码,保留 ()-_.
|
||||
符合你提供的期望输出格式。
|
||||
"""
|
||||
from urllib.parse import quote
|
||||
|
||||
parts = qs.split('&')
|
||||
result_parts = []
|
||||
for part in parts:
|
||||
if '=' in part:
|
||||
key, val = part.split('=', 1)
|
||||
else:
|
||||
key, val = part, ''
|
||||
# 保留 ( ) - _ . ~ * ' ! 等?但根据你的输出,至少保留 ( )
|
||||
# 观察:/ : { } [ ] " 空格 中文等都被编码,但 ( ) 没有
|
||||
encoded_key = quote(key, safe='()-.~')
|
||||
encoded_val = quote(val, safe='()-.~')
|
||||
result_parts.append(f"{encoded_key}={encoded_val}")
|
||||
return '&'.join(result_parts)
|
||||
def req_product_smooth2(poi_id_str,spuIds,headersdata,prox,id,lat,lng,num=1):
|
||||
from urllib.parse import quote
|
||||
print('jiangyim')
|
||||
if type(headersdata) == str:
|
||||
headersdata = json.loads(headersdata)
|
||||
headers = headersdata[1]
|
||||
openId = headers['openId']
|
||||
url = headersdata[0]
|
||||
data = headersdata[2]
|
||||
if 'hcapi' in url:
|
||||
data['drug_spu_tag_id'] = ''
|
||||
else:
|
||||
data['spu_tag_id'] = ''
|
||||
|
||||
|
||||
new1_lat, new1_lng = mock_human_move_latlng(lat, lng)
|
||||
new_lat = str(new1_lat).split('.')[0]
|
||||
new_lng = str(new1_lng).split('.')[0]
|
||||
# new_lat, new_lng = lat, lng
|
||||
# if data["wm_actual_latitude"] != '0':
|
||||
# data["wm_actual_latitude"] = new_lat
|
||||
# if data["wm_actual_longitude"] != '0':
|
||||
# data["wm_actual_longitude"] = new_lng
|
||||
data["wm_latitude"] = new_lat
|
||||
data["wm_longitude"] = new_lng
|
||||
data["latitude"] = new_lat
|
||||
data["longitude"] = new_lng
|
||||
|
||||
|
||||
|
||||
# data["wm_actual_latitude"] = new_lat
|
||||
# data["wm_actual_longitude"] = new_lng
|
||||
# data["wm_actual_latitude"] = new_lat
|
||||
# data["wm_actual_longitude"] = new_lng
|
||||
# data["wm_actual_latitude"] = data["wm_latitude"]
|
||||
# data["wm_actual_longitude"] = data["wm_longitude"]
|
||||
|
||||
|
||||
data['tag_type'] = 27
|
||||
|
||||
data['req_time'] = str(int(time.time()*1000))
|
||||
data['poi_id_str'] = poi_id_str
|
||||
# data['drug_spu_tag_id'] = 1
|
||||
data['spuIds'] = quote(str(spuIds).replace(' ',''))
|
||||
mtg_origin = eval(headers['mtgsig'])
|
||||
dfpid = mtg_origin['a3']
|
||||
data2 = get_Datatext(data)
|
||||
# Content-Length 必须和实际发送的 body 一致;以前用 data3 算长度却发 data2,服务端会一直等 body → 30s 超时 0 字节
|
||||
headers['Content-Length'] = str(len(data2))
|
||||
headers['mtgsig'] = get_sign_new1(url,data2,dfpid,mtg_origin,openId)
|
||||
# headers['mtgsig'] = get_sign_new(url,data2,dfpid,mtg_origin)
|
||||
print(prox)
|
||||
print(type(prox))
|
||||
# 任务里的代理本来就是 http://,不要先改成 socks5 再改回来
|
||||
proxies = {}
|
||||
for k, v in prox.items():
|
||||
v = str(v).replace('socks5://', 'http://').replace('socks5s://', 'https://')
|
||||
proxies[k] = v
|
||||
# if num ==1 :
|
||||
# raw_ua = headers.get('User-Agent')
|
||||
# if raw_ua is None or (isinstance(raw_ua, str) and raw_ua.strip() == ""):
|
||||
# raw_ua = random_user_agent()
|
||||
# headers['User-Agent'] = fix_cyrillic(raw_ua)
|
||||
# else:
|
||||
# headers['User-Agent'] = fix_cyrillic(random_user_agent())
|
||||
print(headers['User-Agent'])
|
||||
# input()
|
||||
# if '36.27.223.47:28103' in prox :
|
||||
# syt8427933643:74621467@223.85.111.154:9008
|
||||
# prox = {"http": "http://b5i0:b5i0e@183.146.16.157:28103", "https": "http://b5i0:b5i0e@183.146.16.157:28103"}
|
||||
print('当前代理prox'+str(proxies))
|
||||
try:
|
||||
req = requests.post(url, headers=headers, data=data2, proxies=proxies, verify=False, timeout=30)
|
||||
except Exception as e:
|
||||
print(f'[请求超时/失败] url={url[:80]} prox={proxies} err={e}')
|
||||
raise
|
||||
# req = requests.post(url,headers=headers,data=data2,verify=False)
|
||||
print(req.text)
|
||||
print(new_lat, new_lng)
|
||||
if req.status_code == 200:
|
||||
if '您还没有登录,请先登录' in req.text:
|
||||
sql = f'''
|
||||
update market_render_headers_tk_test set is_ok=406 where id='{id}'
|
||||
'''
|
||||
tent2.update_data(sql)
|
||||
return False
|
||||
if "您的网络好像不太给力,请稍后再试" in req.text:
|
||||
sql = f'''
|
||||
update market_render_headers_tk_test set is_ok=418 where id='{id}'
|
||||
'''
|
||||
tent2.update_data(sql)
|
||||
dass = json.dumps([url, headers, data2])
|
||||
if append_verify_log_once(id, dass):
|
||||
print(f'[verify_log] 包 id={id} 已记录(每个包仅记一次)')
|
||||
return False
|
||||
if try_inc_render_count(id) == 0:
|
||||
return '已达上限'
|
||||
elif '您还没有登录,请先登录' in req.text:
|
||||
sql = f'''
|
||||
update market_render_headers_tk_test set is_ok=406 where id='{id}'
|
||||
'''
|
||||
tent2.update_data(sql)
|
||||
return False
|
||||
elif "您的网络好像不太给力,请稍后再试" in req.text:
|
||||
sql = f'''
|
||||
update market_render_headers_tk_test set is_ok=418 where id='{id}'
|
||||
'''
|
||||
tent2.update_data(sql)
|
||||
dass = json.dumps([url,headers,data2])
|
||||
if append_verify_log_once(id, dass):
|
||||
print(f'[verify_log] 包 id={id} 已记录(每个包仅记一次)')
|
||||
return False
|
||||
elif '该分类暂无商品' in req.text:
|
||||
return '该分类暂无商品'
|
||||
elif req.status_code == 403:
|
||||
sql = f'''
|
||||
update market_render_headers_tk_test set is_ok={req.status_code} where id='{id}'
|
||||
'''
|
||||
tent2.update_data(sql)
|
||||
return False
|
||||
else:
|
||||
sql = f'''
|
||||
update market_render_headers_tk_test set is_ok={req.status_code} where id='{id}'
|
||||
'''
|
||||
tent2.update_data(sql)
|
||||
return False
|
||||
return req.json()
|
||||
|
||||
def req_sputag_products2(poi_id_str,spu_tag_id,headersdata,prox):
|
||||
headers = headersdata['headers']
|
||||
openId = headers.get('openId','')
|
||||
url = headersdata['url']
|
||||
data = headersdata['data']
|
||||
data['req_time'] = int(time.time()*1000)
|
||||
data['poi_id_str'] = poi_id_str
|
||||
data['spu_tag_id'] = spu_tag_id
|
||||
data['tag_type'] = '1'
|
||||
mtg_origin = eval(headers['mtgsig'])
|
||||
dfpid = mtg_origin['a3']
|
||||
data2 = get_Datatext(data)
|
||||
headers['mtgsig'] = get_sign_new1(url,data2,dfpid,mtg_origin,openId)
|
||||
# headers['mtgsig'] = get_sign_new(url,data2,dfpid,mtg_origin)
|
||||
# req = requests.post(url,headers=headers,data=data2,proxies=proxy_config,verify=False)
|
||||
req = requests.post(url,headers=headers,data=data2,proxies=prox,verify=False)
|
||||
# req = requests.post(url,headers=headers,data=data2,verify=False)
|
||||
print(req.text)
|
||||
# print(req.text[:500])
|
||||
return req.json()
|
||||
|
||||
|
||||
|
||||
def acquire_lock(redis_client, lock_key, timeout=10, expire_time=10):
|
||||
""" 获取分布式锁 """
|
||||
identifier = str(uuid.uuid4())
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
if redis_client.set(lock_key, identifier, nx=True, ex=expire_time):
|
||||
return identifier
|
||||
time.sleep(0.01)
|
||||
return False
|
||||
|
||||
def release_lock(redis_client, lock_key, identifier):
|
||||
""" 释放分布式锁 """
|
||||
script = """
|
||||
if redis.call("get", KEYS[1]) == ARGV[1] then
|
||||
return redis.call("del", KEYS[1])
|
||||
else
|
||||
return 0
|
||||
end
|
||||
"""
|
||||
return redis_client.eval(script, 1, lock_key, identifier)
|
||||
|
||||
def get_min_key_and_delete(redis_client, lock_key='my_lock'):
|
||||
""" 获取最小键值并删除该键 """
|
||||
# 获取分布式锁
|
||||
lock_identifier = acquire_lock(redis_client, lock_key)
|
||||
if not lock_identifier:
|
||||
raise Exception("Failed to acquire lock")
|
||||
|
||||
try:
|
||||
# 获取所有键
|
||||
keys = redis_client.keys('*')
|
||||
keys.remove('my_lock')
|
||||
|
||||
if not keys:
|
||||
return None
|
||||
|
||||
# 将键转换为整数并找到最小值
|
||||
|
||||
min_key = min(keys, key=lambda k: int(k))
|
||||
data = redis_client.get(min_key)
|
||||
return_data = json.loads(data)
|
||||
# 删除最小键
|
||||
redis_client.delete(min_key)
|
||||
|
||||
return return_data
|
||||
finally:
|
||||
# 释放分布式锁
|
||||
release_lock(redis_client, lock_key, lock_identifier)
|
||||
|
||||
def get_works():
|
||||
# 美团商超药店
|
||||
data = get_min_key_and_delete(mt_团购_搜索)
|
||||
# hhh 特別版
|
||||
# data = get_min_key_and_delete(redis_client_db7)
|
||||
return data
|
||||
|
||||
def req_product2(parent_id,parent_id2,wm_poi_id, poi_id_str, shop_name, tag1, tag1_name, spu_tag_id, tag2_name, products, render,workid, pro):
|
||||
a1 = req_sputag_products2(poi_id_str,spu_tag_id,products, pro)
|
||||
a2 = received_products(a1,workid,parent_id,parent_id2)
|
||||
|
||||
print(a2)
|
||||
|
||||
if a2 == "该分类暂无商品":
|
||||
print(a2)
|
||||
return "该分类暂无商品"
|
||||
if a2 == "访问出错啦,稍后再试吧~":
|
||||
print(a2)
|
||||
return "访问出错啦,稍后再试吧~"
|
||||
|
||||
product_count = a1['data']['product_count']
|
||||
next_page = int(a1['data']['has_next_page'])
|
||||
org_spulist = a1['data']['allSortedSpuId']
|
||||
spulist = org_spulist[20:]
|
||||
da = (poi_id_str,spu_tag_id,json.dumps(org_spulist),json.dumps(spulist))
|
||||
update_sql = f"""
|
||||
update categorylist set allSortedSpuId = '{org_spulist}' , product_count = '{product_count}' , has_next_page = '{next_page}' where index_id = '{parent_id2}'
|
||||
"""
|
||||
tent.update_data(update_sql)
|
||||
insert_render = f"""
|
||||
insert into render_list (poi_id_str,spu_tag_id,allSortedSpuId,lastSortedSpuId) values (%s,%s,%s,%s)
|
||||
"""
|
||||
tent.write_data_one(insert_render,da)
|
||||
return '请求解析成功'
|
||||
|
||||
|
||||
# update_sql = f"""
|
||||
# update categorylist set allSortedSpuId = '{org_spulist}' , product_count = '{product_count}' , has_next_page = '{next_page}' where index_id = '{parent_id2}'
|
||||
# """
|
||||
# tent.update_data(update_sql)
|
||||
# if next_page:
|
||||
# numall = len(spulist)
|
||||
# result = math.ceil(numall / 60)
|
||||
# for i in range(result):
|
||||
# start_num = i*60
|
||||
# print('start_num:%d'%start_num)
|
||||
# end_num = (i+1)*60
|
||||
# if i == result-1:
|
||||
# spulist1 = spulist[start_num:]
|
||||
# else:
|
||||
# spulist1 = spulist[start_num:end_num]
|
||||
# print('req_sputag_products')
|
||||
# b1 = req_product_smooth2(wm_poi_id,poi_id_str,spu_tag_id,spulist1,render, pro)
|
||||
# b2 = received_products(b1,workid,parent_id,parent_id2)
|
||||
# # time.sleep(random.randint(1,3))
|
||||
# return '请求解析成功'
|
||||
|
||||
|
||||
|
||||
def run(products, render,workid, pro):
|
||||
req_data = get_works()
|
||||
reversed_list = list(reversed(req_data))
|
||||
for i in reversed_list:
|
||||
print(i)
|
||||
parent_id2,parent_id,wm_poi_id, poi_id_str, shop_name, tag1_id, tag1_name, tag2_id, tag2_name = i
|
||||
try:
|
||||
aa = req_product2(parent_id,parent_id2,wm_poi_id, poi_id_str, shop_name, tag1_id, tag1_name, tag2_id, tag2_name, products, render,workid, pro)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
return False
|
||||
|
||||
if aa == '请求解析成功':
|
||||
if tag2_id != '':
|
||||
updatesql = f"""
|
||||
update categorylist set is_ok = 1,workid = '{workid}' where index_id = '{parent_id2}'
|
||||
"""
|
||||
tent.update_data(updatesql)
|
||||
else:
|
||||
updatesql = f"""
|
||||
update categorylist set is_ok = 1,workid = '{workid}' where index_id = '{parent_id2}'"""
|
||||
tent.update_data(updatesql)
|
||||
elif aa == "该分类暂无商品":
|
||||
if tag2_id != '':
|
||||
updatesql = f"""
|
||||
update categorylist set is_ok = 2,workid = '{workid}' where index_id = '{parent_id2}'
|
||||
"""
|
||||
tent.update_data(updatesql)
|
||||
else:
|
||||
updatesql = f"""
|
||||
update categorylist set is_ok = 2,workid = '{workid}' where index_id = '{parent_id2}'
|
||||
"""
|
||||
tent.update_data(updatesql)
|
||||
elif aa == "访问出错啦,稍后再试吧~":
|
||||
if tag2_id != '':
|
||||
updatesql = f"""
|
||||
update categorylist set is_ok = 3,workid = '{workid}' where index_id = '{parent_id2}'
|
||||
"""
|
||||
tent.update_data(updatesql)
|
||||
else:
|
||||
updatesql = f"""
|
||||
update categorylist set is_ok = 3,workid = '{workid}' where index_id = '{parent_id2}'
|
||||
"""
|
||||
tent.update_data(updatesql)
|
||||
input(1)
|
||||
|
||||
def get_headers():
|
||||
sql = '''
|
||||
select * from mjz.headers where is_ok = 2
|
||||
'''
|
||||
result = tent.get(sql)
|
||||
# my = Mysql()
|
||||
# result = my.get(sql)
|
||||
products = []
|
||||
render = []
|
||||
headers = []
|
||||
for i in result:
|
||||
y = {}
|
||||
if i[4]=="products":
|
||||
products.append(list(i))
|
||||
elif i[4]=="render":
|
||||
render.append(list(i))
|
||||
return [products,render]
|
||||
|
||||
def get_headers2(path):
|
||||
products = []
|
||||
render = []
|
||||
for root,dirs,files in os.walk(path):
|
||||
if len(files)>0:
|
||||
for file in files:
|
||||
if file == "products":
|
||||
with open(os.path.join(root,file),"r",encoding="utf-8") as f:
|
||||
pro = f.read()
|
||||
products.append([0,pro])
|
||||
if file == "render":
|
||||
with open(os.path.join(root,file),"r",encoding="utf-8") as f:
|
||||
ren = f.read()
|
||||
render.append([0,ren])
|
||||
return [products,render]
|
||||
|
||||
|
||||
def run_render(work,headersdata,id,current_count,format_today):
|
||||
while not work.empty():
|
||||
if get_render_current_count(id) >= MAX:
|
||||
print(f'账号 {id} 已达上限 {MAX},停止')
|
||||
break
|
||||
da = work.get_nowait()
|
||||
print(da)
|
||||
idd,parent_id,mt_org_id,poi_id_str,rank,spulist,is_ok,prox_data,lat,lng,workid,business_code,create_time,city = da
|
||||
prox2 = json.loads(prox_data)
|
||||
# 保持 http 代理,勿改 socks5(后面又改回 http,且 https→socks5s 会坏)
|
||||
print(prox2)
|
||||
# input(12665156461)
|
||||
# prox2 = {"http": "http://v272C7AmSr_8:x8L8YXbu@112.29.157.201:31584", "https": "http://v272C7AmSr_8:x8L8YXbu@112.29.157.201:31584"}
|
||||
# prox2 = {"http": "http://v9065uiu3j_4:CpVgnnLy@112.30.182.175:25863", "https": "http://v9065uiu3j_4:CpVgnnLy@112.30.182.175:25863"}
|
||||
spuIds = json.loads(spulist)
|
||||
render = req_product_smooth2(poi_id_str, spuIds, headersdata,prox2,id,lat,lng)
|
||||
if render is False:
|
||||
return False
|
||||
if render == '已达上限':
|
||||
print(f'账号 {id} 已达上限 {MAX},停止')
|
||||
break
|
||||
def save_req_render(render, poi_id_str):
|
||||
import os
|
||||
today = datetime.date.today()
|
||||
formatted_date = today.strftime('%Y%m%d')
|
||||
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
path = os.path.join(base_dir, formatted_date, 'render')
|
||||
os.makedirs(path, exist_ok=True) # 直接用传入的 path
|
||||
filename = f"{poi_id_str + '_' +str(rank)}.json" # 或保留日期前缀
|
||||
filepath = os.path.join(path, filename)
|
||||
with open(filepath, 'w', encoding='utf-8') as f:
|
||||
f.write(json.dumps(render))
|
||||
# with open(fr'C:\公司项目\A7_便利店全店\products\歪马送酒(华景新城店)\render\{poi_id_str+"_"+str(rank)}.json','w',encoding='utf-8')as f:
|
||||
# f.write(json.dumps(render))
|
||||
# format_today = '20260420_1'
|
||||
save_req_render(render=render,poi_id_str=poi_id_str)
|
||||
received_products(render,workid,parent_id,'-1',mt_org_id,poi_id_str,business_code)
|
||||
update_sql= """
|
||||
update target_rendet set `is__ok` = 1 where `id` = '%s'
|
||||
"""%(idd)
|
||||
tent.update_data(update_sql)
|
||||
time.sleep(random.randint(1,3))
|
||||
|
||||
|
||||
def past():
|
||||
# if __name__ == '__main__':
|
||||
path = r'C:\Users\Administrator\PycharmProjects\pythonProject\商超全店项目-zhuifeng\headers_data2'
|
||||
p = ThreadPoolExecutor(10)
|
||||
# products,render = get_headers()
|
||||
products,render = get_headers2(path)
|
||||
prox_list = []
|
||||
with open('yiyouip', 'r', encoding='utf-8') as f:
|
||||
ips = f.read().split('\n')
|
||||
for ip in ips:
|
||||
ip2 = ip.replace('socks5', 'http')
|
||||
prox_list.append({
|
||||
'http': ip2,
|
||||
'https': ip2
|
||||
})
|
||||
random.shuffle(prox_list)
|
||||
for i in range(len(products)):
|
||||
p.submit(run,json.loads(products[i][1]),json.loads(render[i][1]),"6666666",prox_list[i%len(prox_list)])
|
||||
print(i)
|
||||
# run(pro,ren,"6666666", pro_list[0])
|
||||
|
||||
|
||||
def update_doing(ids):
|
||||
sql = '''
|
||||
update market_render_headers set is_ok=666 where id=%s
|
||||
'''
|
||||
tent2.update_data_many(sql, ids)
|
||||
|
||||
if __name__ == '__main__':
|
||||
# path = r'C:\Users\Administrator\PycharmProjects\pythonProject\商超全店项目-zhuifeng\headers_data2\1757314910200OGCGWSS60e593ce0a815b08d658526270cd17d68115\render\render'
|
||||
# with open(path,'r',encoding='utf-8') as f:
|
||||
# hd = json.load(f)
|
||||
# MAX = 100
|
||||
# i=7886
|
||||
# m=1815
|
||||
# # sql = f'''
|
||||
# # update market_render_headers set is_ok = null where is_ok = 418 and title like '%美团_便利店%' and id>{i}
|
||||
# # '''
|
||||
# # tent2.update_data(sql)
|
||||
# sql = f'''
|
||||
# select * from market_render_headers where is_ok is null and title like '%美团_便利店%' and id>={i} and current_count<{MAX} '''
|
||||
# # sql = f'''
|
||||
# # select * from market_render_headers where is_ok is null and title like '%闪购-美团_便利店%' and id>={i} and current_count<{MAX}
|
||||
# # '''
|
||||
# # sql = f'''
|
||||
# # select * from market_render_headers where is_ok is null and title like '%美团_便利店%' and id>={i} and current_count<{MAX}
|
||||
# # '''
|
||||
# renders,ids,current_counts = [],[],[]
|
||||
# rt = tent2.get_shoppingmalls(sql)
|
||||
#
|
||||
# print(len(rt))
|
||||
# # input(11)
|
||||
# if len(rt)>10:
|
||||
# p = ThreadPoolExecutor(10)
|
||||
# else:
|
||||
# p = ThreadPoolExecutor(len(rt))
|
||||
# for i in rt:
|
||||
# renders.append(i[3])
|
||||
# ids.append(i[0])
|
||||
# current_counts.append(i[8])
|
||||
# # path = r'C:\Users\Administrator\PycharmProjects\pythonProject\商超全店项目-zhuifeng\headers_data2'
|
||||
# # products,renders = get_headers2(path)
|
||||
# work = queue.Queue()
|
||||
# WORKID = '20260324'
|
||||
# sql = f"""
|
||||
# select * from target_rendet where is__ok is null and workid='{WORKID}'
|
||||
# """
|
||||
# a11 = tent.get_shoppingmalls(sql)
|
||||
# # 4343
|
||||
# for b in a11[:]:
|
||||
# # print(b)
|
||||
# work.put(b)
|
||||
# # update_doing(ids)
|
||||
# for i in range(len(renders)):
|
||||
# p.submit(run_render,work,renders[i],ids[i],current_counts[i])
|
||||
# print(i)
|
||||
# i=0
|
||||
# run_render(work, renders[i], ids[i],current_counts[i])
|
||||
# for i in range(len(renders)):
|
||||
# run_render(work, renders[i], ids[i],current_counts[i])
|
||||
# if run_render(work,hd,id) is False:
|
||||
# break
|
||||
# sql1 = """
|
||||
# select distinct poi_id_str,prox_data,lat,lng from categorylist
|
||||
# """
|
||||
# proxs = tent.get_shoppingmalls(sql1)
|
||||
# print(proxs)
|
||||
i = 0
|
||||
m = 1815
|
||||
sql = f'''
|
||||
select * from market_render_headers_tk_test
|
||||
where is_ok is null and title like '%美团_便利店%'
|
||||
and id>={i} and current_count < {MAX}
|
||||
'''
|
||||
renders, ids, current_counts = [], [], []
|
||||
rt = tent2.get_shoppingmalls(sql)
|
||||
print(len(rt))
|
||||
if len(rt) > 5:
|
||||
p = ThreadPoolExecutor(5)
|
||||
else:
|
||||
p = ThreadPoolExecutor(5)
|
||||
for i in rt:
|
||||
renders.append(i[3])
|
||||
ids.append(i[0])
|
||||
current_counts.append(i[8])
|
||||
|
||||
WORKID = '20260803'
|
||||
# and poi_id_str = '9dNJr7uG2gOdS-kUo5RvWwI'
|
||||
# and prox like '%b5i0:b5i0e@36.27.223.47:28105%'
|
||||
sql = f"""
|
||||
select * from target_rendet where is__ok is null and workid like '%{WORKID}%'
|
||||
"""
|
||||
a11 = tent.get_shoppingmalls(sql)
|
||||
grouped_queues = {}
|
||||
for row in a11:
|
||||
# select * 顺序: ..., is_ok(6), prox_data(7), lat(8), lng(9), ...
|
||||
prox_value = row[7]
|
||||
if prox_value is None or prox_value == '':
|
||||
continue
|
||||
prox_value = str(prox_value)
|
||||
if prox_value not in grouped_queues:
|
||||
grouped_queues[prox_value] = queue.Queue()
|
||||
grouped_queues[prox_value].put(row)
|
||||
queue_list = list(grouped_queues.items())
|
||||
print(f"共有 {len(queue_list)} 个代理组")
|
||||
# format_today = str(datetime.date.today()).replace("-", "")
|
||||
num_groups = len(queue_list)
|
||||
num_renders = len(renders)
|
||||
if num_groups == 0:
|
||||
print('没有可处理的代理队列,任务结束')
|
||||
raise SystemExit(0)
|
||||
if num_renders == 0:
|
||||
print('没有可用的 render 包,任务结束')
|
||||
raise SystemExit(0)
|
||||
|
||||
# 按记忆文件绑定账号→代理,重启后仍跑同一城市
|
||||
assignments, _ = assign_queues_with_memory(ids, grouped_queues, WORKID)
|
||||
|
||||
# for i in range(num_renders):
|
||||
# prox_key, work_queue = assignments[i]
|
||||
# print(f"render[{i}] id={ids[i]} 处理代理组: {str(prox_key)[:50]}... (队列大小: {work_queue.qsize()})")
|
||||
# p.submit(run_render, work_queue, renders[i], ids[i], current_counts[i], WORKID)
|
||||
# p.shutdown(wait=True)
|
||||
|
||||
|
||||
|
||||
# for i in range(num_renders):
|
||||
# queue_idx = i % num_groups
|
||||
# prox_key, work_queue = queue_list[queue_idx]
|
||||
# print(f"render[{i}] 处理代理组: {str(prox_key)[:50]}... (队列大小: {work_queue.qsize()})")
|
||||
# run_render(work_queue, renders[i], ids[i], current_counts[i],WORKID)
|
||||
# input(666)
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user