upload
This commit is contained in:
+144
@@ -0,0 +1,144 @@
|
||||
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()
|
||||
|
||||
|
||||
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()
|
||||
|
||||
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()
|
||||
|
||||
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
|
||||
|
||||
|
||||
@@ -0,0 +1,393 @@
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qsl, quote
|
||||
|
||||
import requests
|
||||
|
||||
import newsetting as ten
|
||||
|
||||
tent = ten.All_Setting(host='192.168.5.5', port=3306, db='project_search_upc')
|
||||
tent1 = ten.All_Setting(host='192.168.5.2', port=3307, db='headers_project')
|
||||
|
||||
# headers = {
|
||||
# "Connection": "keep-alive",
|
||||
# "M-APPKEY": "wxmp_mt-weapp",
|
||||
# "M-TRACEID": "-7695101042993193113",
|
||||
# "X-Requested-With": "XMLHttpRequest",
|
||||
# "clientversion": "3.18.0",
|
||||
# "content-type": "application/x-www-form-urlencoded",
|
||||
# "csecuserid": "9443424166",
|
||||
# "csecuuid": "1a1e802281fc8-eab2df9fcc012-0-0-1a1e802281fc8",
|
||||
# "mtgsig": "{\"a1\":\"1.2\",\"a2\":1794908381654,\"a3\":\"4u893y641w225z68y7x6974953036vyv8z8v197687677978z815v087\",\"a4\":\"cc8562cb3ed3e099cb6285cc99e0d33e1d03652484e3b61a\",\"a5\":\"kpgeo7msLLAihBonrF3Zjz+cUWmV87Jjx4wndRUgRSi7rUe7A/2aa9pfKpvDdUBDqx4ARXWaEwl9gTaz4ZIMBC7yh+oC2zobD2omo9O81o8b6ZRmzp4IfIYNoeKrMVhN14F13sJuSo55AMYGzdiT/v5FDcl5I8avaeANJtszmyG87Fa+46g8qkLNo0d9H0VzRoGd+7+iHwxVejxnDZHqRk+qQcY0Fz/23PaR9vKE6RnV19U/bcWGIbM6fwr3iR4GLPQvR/m4qhT3AIS+E2GIJYFPU//xSKku4h8xtHd71sUoqUOVqjvvb/SKzDOYDgcpCTPwg8vv3jejMW74qQmJKMjPD9ampFAdRGBsF3yc+fklcQGjxFG8OfjKfhDvKZ==\",\"a6\":\"w1.6QwJMnmpiB5CWb8gWNoWnGI68+7riIhXUdEcPcJyo1ltduAIYzM2Qmlz+7O1eaSCs7Uhsnvqfp0ggnjQ12RAZCMCJAv4Dih+mUVnWHbsgCI/Huuh8VceZ0s/8zUCC+CXXOv8oGwb0BZ2RGng1XozEu1DAVICwPALoM2qpyp4L+5Q+oLNg5zjoVOvKsZm8NCgd71gWGCb4dnmqmYvsjn/FpR2qOFgdIjpPXgWCJSZ9Loodrvvy7u2jVIl3msodme4kAftPf/c4qjt8VNAKyfLRgrDhtFXwBa5D8erSL8S4IUN69o+2H/B1WCiCNPbmW5appfxN3FqAfcmQCNdQVNVaxJq904ko+IL4Jy3bhYEmahsM5Xx/IGRCCi05kDWfJIhKsF7+kyP3yfvbE9boXJpydK6S1Q4/1/VNZvvLcXX7lIEpSLILl1Hua/oUN+cpI096PUKsbOgRMVO9hrtiFCwjk+NW8Lw+b2Aeq4B7W+7r6CCgTlzEh8uSCXvPLUN1fqQFNWlh9oagCXlG7pFaH0P/X86AXUjLUcIWXLnr1ZTWrAk9eHVsNPmXxRrsz3kRMdCgoUdmwPWijOdDS6PAvTtn7qgU787OA38DVCXW5urBAog=\",\"a7\":\"wxde8ac0a21135c07d\",\"x0\":3,\"d1\":\"78ef5fb681331f3d179be79995a78c1a\"}",
|
||||
# "openId": "oJVP50GiICD-vlSLMEktNRordQ-Q",
|
||||
# "openIdCipher": "AwQAAABJAgAAAAEAAAAyAAAAPLgC95WH3MyqngAoyM/hf1hEoKrGdo0pJ5DI44e1wGF9AT3PH7Wes03actC2n/GVnwfURonD78PewMUppAAAADibYlI8XGw4RLoZtg8xUxsnOtLPXC17jezbGf09i4+qhEE98HJbfrM7IbcJfGG8QKGmJnYwqbGbXw==",
|
||||
# "token": "AgE4I6MN-_h2QAy1tCNUUBhkkZePSOFJlqmo5nZPTk9XnM8RPlIq180Enn3xPElhiitoYXnK4crXuwAAAADqPQAAbA-qPAH-O9KsZRgAEh0FhPDNc_4PpbbicpyjRCJWuEL8O_MBodKFop42ybHPtRJ2",
|
||||
# "userid": "9443424166",
|
||||
# "utm_medium": "",
|
||||
# "uuid": "1a1e802281fc8-eab2df9fcc012-0-0-1a1e802281fc8",
|
||||
# "x-env": "online",
|
||||
# "charset": "utf-8",
|
||||
# "Referer": "https://servicewechat.com/wxde8ac0a21135c07d/1594/page-frame.html",
|
||||
# "User-Agent": "Mozilla/5.0 (Linux; Android 14; V2338A Build/UP1A.231005.007; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/156.0.8078.79 Mobile Safari/537.36 XWEB/1560023 MMWEBSDK/20260902 MMWEBID/1205 MicroMessenger/8.0.80.3220(0x28005032) WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64 MiniProgramEnv/android"
|
||||
# }
|
||||
# url = 'https://scsearchapi.waimai.meituan.com/wxdrug/v2/search/globalpage'
|
||||
# params = {
|
||||
# "app_flag": "wxMsc",
|
||||
# "ui": "9443424166",
|
||||
# "region_id": "1000511100",
|
||||
# "region_version": "1794900887108",
|
||||
# "yodaReady": "wx",
|
||||
# "csecappid": "wxde8ac0a21135c07d",
|
||||
# "csecplatform": "3",
|
||||
# "csecversionname": "10.45.1",
|
||||
# "csecversion": "3.0.3"
|
||||
# }
|
||||
# payload = 'wm_ctype=mt_weapp&wm_dtype=V2338A&wm_dversion=8.0.80&wm_uuid=1a1e802281fc8-eab2df9fcc012-0-0-1a1e802281fc8&wm_visitid=d487cd6c-df4b-4c42-8ccd-98e18ac0612c&wm_appversion=10.45.1&wm_channel=&wm_did=&wm_logintoken=AgE4I6MN-_h2QAy1tCNUUBhkkZePSOFJlqmo5nZPTk9XnM8RPlIq180Enn3xPElhiitoYXnK4crXuwAAAADqPQAAbA-qPAH-O9KsZRgAEh0FhPDNc_4PpbbicpyjRCJWuEL8O_MBodKFop42ybHPtRJ2&userToken=AgE4I6MN-_h2QAy1tCNUUBhkkZePSOFJlqmo5nZPTk9XnM8RPlIq180Enn3xPElhiitoYXnK4crXuwAAAADqPQAAbA-qPAH-O9KsZRgAEh0FhPDNc_4PpbbicpyjRCJWuEL8O_MBodKFop42ybHPtRJ2&req_time=1794908381801&waimai_sign=%2F&wm_longitude=116396795&wm_latitude=39884339&longitude=116396795&latitude=39884339&wm_actual_longitude=113280637&wm_actual_latitude=23125178&userid=9443424166&user_id=9443424166&wm_mac=&ci=20&openidcipher=AwQAAABJAgAAAAEAAAAyAAAAPLgC95WH3MyqngAoyM%2Fhf1hEoKrGdo0pJ5DI44e1wGF9AT3PH7Wes03actC2n%2FGVnwfURonD78PewMUppAAAADibYlI8XGw4RLoZtg8xUxsnOtLPXC17jezbGf09i4%2BqhEE98HJbfrM7IbcJfGG8QKGmJnYwqbGbXw%3D%3D&open_id=oJVP50GiICD-vlSLMEktNRordQ-Q&uuid=1a1e802281fc8-eab2df9fcc012-0-0-1a1e802281fc8&platform=13&rc_platform=13&rc_app=0&partner=214&riskLevel=71&client_id=90&biz_id=1137&utm_source=&category_type=102530&category_text=%E7%BE%8E%E5%9B%A2%E4%B9%B0%E8%8D%AF&sub_category_type=0&entrance_id=102530&search_source=0&keyword=%E5%B8%83%E6%B4%9B%E8%8A%AC&search_global_id=908381786286898126&query_type=12002&suggest_global_id=&is_fix_keyword=false&sort_type=0&activity_filter_codes=&originGuideQuery=&secondGuidedShowText=&search_page_type=0&search_cursor=0&filter_item_status=0&page_size=20&agg_style_switch_button=&search_need_module=%5B%5D&product_card_page_index=0&product_tag_id=&slider_select_data=&page_index=0&inner_source=10'
|
||||
|
||||
|
||||
def load_packet():
|
||||
rows = tent1.get_shoppingmalls('''
|
||||
select `index`, title, hd_data
|
||||
from search_globalpage_hd_mt
|
||||
where is_ok is null
|
||||
order by `index` desc
|
||||
limit 1
|
||||
''')
|
||||
if not rows:
|
||||
print('search_globalpage_hd_mt 没有 is_ok 为空的包')
|
||||
return None
|
||||
idx, title, hd_data = rows[0]
|
||||
packet = json.loads(hd_data)
|
||||
print(f'使用 search_globalpage_hd_mt index={idx} title={title}')
|
||||
return idx, packet
|
||||
|
||||
|
||||
def mark_packet(packet_index, is_ok):
|
||||
tent1.update_data(
|
||||
f'update search_globalpage_hd_mt set is_ok={int(is_ok)} where `index`={int(packet_index)}'
|
||||
)
|
||||
print(f'包 index={packet_index} is_ok={is_ok}')
|
||||
|
||||
|
||||
def add_req_count(packet_index):
|
||||
tent1.update_data(
|
||||
f'update search_globalpage_hd_mt set count_req = ifnull(count_req, 0) + 1 where `index`={int(packet_index)}'
|
||||
)
|
||||
print(f'包 index={packet_index} count_req+1')
|
||||
|
||||
|
||||
def packet_dead_code(response):
|
||||
text = response.text or ''
|
||||
if response.status_code in (403, 418):
|
||||
return response.status_code
|
||||
if 'yodaCode' in text or '您的网络好像不太给力' in text:
|
||||
return 418
|
||||
if '您还没有登录' in text:
|
||||
return 406
|
||||
return None
|
||||
|
||||
|
||||
def get_task():
|
||||
sql = f"""
|
||||
select `id`,keyword,lat,lng,batch,target_city,prox
|
||||
FROM target_adcode
|
||||
where `is_search` is null
|
||||
"""
|
||||
a1 = tent.get_shoppingmalls(sql)
|
||||
return a1
|
||||
|
||||
|
||||
def parse_proxy(raw):
|
||||
if isinstance(raw, dict):
|
||||
if raw.get('http') or raw.get('https'):
|
||||
return raw
|
||||
return None
|
||||
text = str(raw or '').strip()
|
||||
if not text or text.lower() == 'null':
|
||||
return None
|
||||
if text.startswith('{'):
|
||||
try:
|
||||
data = json.loads(text)
|
||||
except Exception:
|
||||
return None
|
||||
if isinstance(data, dict) and (data.get('http') or data.get('https')):
|
||||
return data
|
||||
return None
|
||||
if '://' not in text:
|
||||
text = 'http://' + text
|
||||
return {'http': text, 'https': text}
|
||||
|
||||
|
||||
def proxy_label(proxies):
|
||||
url = str((proxies or {}).get('https') or (proxies or {}).get('http') or '')
|
||||
if '@' in url:
|
||||
url = url.split('@', 1)[1]
|
||||
return url.replace('http://', '').replace('https://', '')
|
||||
|
||||
|
||||
def save_task(parent_id, json_data, batch):
|
||||
insert_save_json = """
|
||||
insert into save_json (parent_id ,json_data,batch) values (%s,%s,%s);
|
||||
"""
|
||||
da = (parent_id, json_data, batch)
|
||||
tent.write_data_one(insert_save_json, da)
|
||||
|
||||
|
||||
def get_Datatext(dataq):
|
||||
# 抓包是 --data-urlencode。params 里的 {}" 和 token 里的 /+= 不编码时,
|
||||
# 签名覆盖的字节和网关收到的不一致,直接 403。
|
||||
parts = []
|
||||
for key, value in dataq.items():
|
||||
parts.append(f"{quote(str(key), safe='()-.~')}={quote(str(value), safe='()-.~')}")
|
||||
return '&'.join(parts)
|
||||
|
||||
|
||||
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
|
||||
}
|
||||
# print(url)
|
||||
# print(type(url))
|
||||
# print(data)
|
||||
# print(type(data))
|
||||
# print(dfpid)
|
||||
# print(type(dfpid))
|
||||
# print(mtg_origin)
|
||||
# print(type(mtg_origin))
|
||||
# print(openId)
|
||||
# print(type(openId))
|
||||
# input(64513746)
|
||||
# url = "http://124.222.120.219:18003/hz_wm_jym_1008"
|
||||
url1 = 'http://129.211.12.35:18003/minipro_mt_0206'
|
||||
req = requests.post(url1, headers=headers, json=body, proxies={'http': None, 'https': None}, verify=False).text
|
||||
print(req)
|
||||
|
||||
# input(156131624961)
|
||||
return req
|
||||
|
||||
|
||||
def get_parmas(url):
|
||||
data = {}
|
||||
u1, u2 = url.split('?')
|
||||
for i in u2.split('&'):
|
||||
key, value = i.split('=')
|
||||
data[key] = value
|
||||
return data
|
||||
|
||||
|
||||
SAVE_DIR = Path(__file__).resolve().parent / '数据暂存'
|
||||
|
||||
|
||||
def save_response(keyword, response):
|
||||
if response.status_code != 200:
|
||||
print(f'未保存 status={response.status_code}')
|
||||
return
|
||||
safe_kw = ''.join('_' if ch in '\\/:*?"<>|' else ch for ch in keyword).strip() or 'keyword'
|
||||
now = datetime.now()
|
||||
stamp = now.strftime('%Y%m%d_%H%M%S')
|
||||
day_dir = SAVE_DIR / now.strftime('%Y%m%d')
|
||||
day_dir.mkdir(parents=True, exist_ok=True)
|
||||
path = day_dir / f'{safe_kw}_{stamp}.json'
|
||||
try:
|
||||
data = response.json()
|
||||
text = json.dumps(data, ensure_ascii=False, indent=2)
|
||||
except Exception:
|
||||
text = response.text
|
||||
path.write_text(text, encoding='utf-8')
|
||||
print(f'已保存 {path}')
|
||||
|
||||
|
||||
def to_mt_coord(value):
|
||||
text = str(value).strip()
|
||||
if '.' not in text:
|
||||
return text
|
||||
sign = ''
|
||||
if text.startswith('-'):
|
||||
sign = '-'
|
||||
text = text[1:]
|
||||
whole, frac = text.split('.', 1)
|
||||
frac = ''.join(ch for ch in frac if ch.isdigit())
|
||||
if len(frac) < 6:
|
||||
frac = frac + '1' * (6 - len(frac))
|
||||
else:
|
||||
frac = frac[:6]
|
||||
return sign + whole + frac
|
||||
|
||||
|
||||
def load_city_ci(path):
|
||||
data = json.loads(Path(path).read_text(encoding='utf-8'))
|
||||
rows = []
|
||||
|
||||
def walk(obj):
|
||||
if isinstance(obj, dict):
|
||||
if 'openCityId' in obj or 'cityId' in obj:
|
||||
rows.append(obj)
|
||||
for value in obj.values():
|
||||
walk(value)
|
||||
elif isinstance(obj, list):
|
||||
for value in obj:
|
||||
walk(value)
|
||||
|
||||
walk(data)
|
||||
by_admin = {}
|
||||
by_name = {}
|
||||
for row in rows:
|
||||
cid = str(row.get('openCityId') or row.get('cityId') or '')
|
||||
if not cid:
|
||||
continue
|
||||
level = str(row.get('level') or '')
|
||||
admin = str(row.get('adminCityName') or '').strip()
|
||||
name = str(row.get('openCityName') or row.get('cityName') or '').strip()
|
||||
if level == '2':
|
||||
if admin:
|
||||
by_admin[admin] = cid
|
||||
if name:
|
||||
by_name[name] = cid
|
||||
elif name and name not in by_name:
|
||||
by_name[name] = cid
|
||||
return by_admin, by_name
|
||||
|
||||
|
||||
def lookup_ci(city, by_admin, by_name):
|
||||
text = str(city or '').strip()
|
||||
if text in by_admin:
|
||||
return by_admin[text]
|
||||
if text in by_name:
|
||||
return by_name[text]
|
||||
short = text[:-1] if text.endswith('市') else text
|
||||
if short in by_name:
|
||||
return by_name[short]
|
||||
return ''
|
||||
|
||||
|
||||
def get_url(url_data, og_url):
|
||||
str_url = ''
|
||||
for i in url_data:
|
||||
key = i
|
||||
valus = url_data[i]
|
||||
a2 = str(key) + '=' + str(valus)
|
||||
str_url = str_url + a2 + '&'
|
||||
url2 = str_url[0:-1]
|
||||
all_url = og_url + '?' + url2
|
||||
return all_url
|
||||
|
||||
|
||||
# ua特殊字符清洗方法。抓包 UA 里 iPhone 的 P 常被写成西里尔 Р(\u0420),请求头只能 latin-1
|
||||
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 clean_headers(headers):
|
||||
for key, value in list(headers.items()):
|
||||
if isinstance(value, str):
|
||||
fixed = fix_cyrillic(value)
|
||||
if fixed != value:
|
||||
print(f'请求头 {key} 含西里尔形近字母,已换成拉丁字母')
|
||||
headers[key] = fixed
|
||||
return headers
|
||||
|
||||
|
||||
def run(KEYWORD, LONGITUDE, LATITUDE, headers, url, params, payload, parent_id, ci, proxies):
|
||||
LONGITUDE = to_mt_coord(LONGITUDE)
|
||||
LATITUDE = to_mt_coord(LATITUDE)
|
||||
payload = dict(parse_qsl(payload, keep_blank_values=True))
|
||||
payload['wm_longitude'] = LONGITUDE
|
||||
payload['wm_latitude'] = LATITUDE
|
||||
payload['longitude'] = LONGITUDE
|
||||
payload['latitude'] = LATITUDE
|
||||
payload['ci'] = ci
|
||||
payload['inner_source'] = '10'
|
||||
# payload['wm_actual_longitude'] = LONGITUDE
|
||||
# payload['wm_actual_latitude'] = LATITUDE
|
||||
payload['keyword'] = KEYWORD
|
||||
mtg_origin = eval(headers['mtgsig'])
|
||||
dfpid = mtg_origin['a3']
|
||||
openId = headers['openId']
|
||||
payload['req_time'] = str(int(time.time() * 1000))
|
||||
new_url = get_url(params, url)
|
||||
data2 = get_Datatext(payload)
|
||||
headers['mtgsig'] = get_sign_new1(new_url, data2, dfpid, mtg_origin, openId).strip()
|
||||
clean_headers(headers)
|
||||
print(new_url)
|
||||
print(headers['mtgsig'])
|
||||
session = requests.Session()
|
||||
session.trust_env = False
|
||||
response = session.post(
|
||||
new_url, headers=headers, data=data2.encode('utf-8'),
|
||||
proxies=proxies, verify=False, timeout=30,
|
||||
)
|
||||
print(response.text)
|
||||
print(response)
|
||||
save_response(KEYWORD, response)
|
||||
return response
|
||||
|
||||
|
||||
def main():
|
||||
loaded = load_packet()
|
||||
if not loaded:
|
||||
return
|
||||
packet_index, packet = loaded
|
||||
use_headers = packet['headers']
|
||||
use_url = packet['url']
|
||||
use_params = packet['params']
|
||||
use_payload = packet['payload']
|
||||
by_admin, by_name = load_city_ci(Path(__file__).resolve().parent / 'id.json')
|
||||
task_all = get_task()
|
||||
for i in task_all:
|
||||
parent_id, keyword, lat, lng, batch, city, prox_raw = i
|
||||
ci = lookup_ci(city, by_admin, by_name)
|
||||
if not ci:
|
||||
print(f'任务 {parent_id} 找不到城市id city={city},跳过')
|
||||
continue
|
||||
proxies = parse_proxy(prox_raw)
|
||||
if not proxies:
|
||||
print(f'任务 {parent_id} prox 为空,跳过')
|
||||
continue
|
||||
print(f'任务 {parent_id} {city} ci={ci} {keyword} lng={lng} lat={lat} prox={proxy_label(proxies)}')
|
||||
response = run(keyword, lng, lat, use_headers, use_url, use_params, use_payload, parent_id, ci, proxies)
|
||||
dead = packet_dead_code(response)
|
||||
if dead is not None:
|
||||
mark_packet(packet_index, dead)
|
||||
print(f'任务 {parent_id} 返回 {dead},包已更新,停止')
|
||||
break
|
||||
data = response.text
|
||||
try:
|
||||
body = json.loads(data)
|
||||
except json.JSONDecodeError:
|
||||
print(f'任务 {parent_id} 响应不是 json,不入库')
|
||||
continue
|
||||
if body.get('code') != 0:
|
||||
print(f'任务 {parent_id} code={body.get("code")} msg={body.get("msg")} 不入库')
|
||||
continue
|
||||
save_task(parent_id, data, batch)
|
||||
tent.update_data(f'update target_adcode set `is_search`=1 where id={int(parent_id)}')
|
||||
add_req_count(packet_index)
|
||||
print(f'任务 {parent_id} 已入库')
|
||||
# input(123456)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,102 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import annotations
|
||||
|
||||
"""药品搜索多线程。逻辑同 部分.py,线程数改 WORKERS。"""
|
||||
|
||||
import importlib.util
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from pathlib import Path
|
||||
|
||||
# ==================== 运行参数(改这里) ====================
|
||||
WORKERS = 5
|
||||
# ============================================================
|
||||
|
||||
_src = Path(__file__).resolve().with_name('部分.py')
|
||||
_spec = importlib.util.spec_from_file_location('drug_search_one', _src)
|
||||
one = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(one)
|
||||
|
||||
db_lock = threading.Lock()
|
||||
stop_event = threading.Event()
|
||||
mark_lock = threading.Lock()
|
||||
packet_marked = False
|
||||
|
||||
|
||||
def handle(task, packet_index, use_url, use_params, use_payload, base_headers, by_admin, by_name):
|
||||
global packet_marked
|
||||
if stop_event.is_set():
|
||||
return 'stopped'
|
||||
parent_id, keyword, lat, lng, batch, city = task
|
||||
ci = one.lookup_ci(city, by_admin, by_name)
|
||||
if not ci:
|
||||
print(f'任务 {parent_id} 找不到城市id city={city},跳过')
|
||||
return 'skip'
|
||||
print(f'任务 {parent_id} {city} ci={ci} {keyword} lng={lng} lat={lat}')
|
||||
headers = dict(base_headers)
|
||||
response = one.run(keyword, lng, lat, headers, use_url, use_params, use_payload, parent_id, ci)
|
||||
dead = one.packet_dead_code(response)
|
||||
if dead is not None:
|
||||
stop_event.set()
|
||||
with mark_lock:
|
||||
if not packet_marked:
|
||||
with db_lock:
|
||||
one.mark_packet(packet_index, dead)
|
||||
packet_marked = True
|
||||
print(f'任务 {parent_id} 返回 {dead},包已更新,停止')
|
||||
return 'dead'
|
||||
data = response.text
|
||||
try:
|
||||
body = one.json.loads(data)
|
||||
except one.json.JSONDecodeError:
|
||||
print(f'任务 {parent_id} 响应不是 json,不入库')
|
||||
return 'bad'
|
||||
if body.get('code') != 0:
|
||||
print(f'任务 {parent_id} code={body.get("code")} msg={body.get("msg")} 不入库')
|
||||
return 'bad'
|
||||
with db_lock:
|
||||
one.save_task(parent_id, data, batch)
|
||||
one.tent.update_data(f'update target_adcode set `is_search`=1 where id={int(parent_id)}')
|
||||
one.add_req_count(packet_index)
|
||||
print(f'任务 {parent_id} 已入库')
|
||||
return 'ok'
|
||||
|
||||
|
||||
def main():
|
||||
loaded = one.load_packet()
|
||||
if not loaded:
|
||||
return
|
||||
packet_index, packet = loaded
|
||||
use_url = packet['url']
|
||||
use_params = packet['params']
|
||||
use_payload = packet['payload']
|
||||
base_headers = packet['headers']
|
||||
by_admin, by_name = one.load_city_ci(Path(__file__).resolve().parent / 'id.json')
|
||||
task_all = one.get_task() or []
|
||||
print(f'任务 {len(task_all)} 条,线程 {WORKERS}')
|
||||
ok = 0
|
||||
with ThreadPoolExecutor(max_workers=WORKERS) as pool:
|
||||
futures = [
|
||||
pool.submit(
|
||||
handle, task, packet_index, use_url, use_params, use_payload,
|
||||
base_headers, by_admin, by_name,
|
||||
)
|
||||
for task in task_all
|
||||
]
|
||||
for fut in as_completed(futures):
|
||||
try:
|
||||
result = fut.result()
|
||||
except Exception as e:
|
||||
print(f'任务异常: {e}')
|
||||
continue
|
||||
if result == 'ok':
|
||||
ok += 1
|
||||
if stop_event.is_set():
|
||||
for pending in futures:
|
||||
pending.cancel()
|
||||
break
|
||||
print(f'结束,成功入库 {ok} 条')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user