3
0

main.py 161 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585
  1. # coding=utf-8
  2. import requests
  3. import base64
  4. import uiautomator2 as u2
  5. import time
  6. import sys
  7. import builtins
  8. import subprocess
  9. import re
  10. import random
  11. import json
  12. from aip import AipOcr
  13. import numpy as np
  14. import cv2
  15. import os
  16. from pdd_config import Config
  17. import logging
  18. import pymysql
  19. import datetime
  20. import threading
  21. import oss2
  22. import uuid
  23. from PIL import Image
  24. from pathlib import Path
  25. from test_captcha import solve as captcha_solve
  26. from commons.Logger import get_spider_logger
  27. from commons.feishu_webhook import send_text, send_error_card
  28. from commons.scheduler import CrawlerScheduler
  29. _DEFAULT_PATH = Path(__file__).with_name("city.json")
  30. # 初始化统一日志(控制台 + logs/pdd_new2.log)
  31. _pdd_logger = get_spider_logger("pdd")
  32. logging.root.handlers = _pdd_logger.handlers
  33. logging.root.setLevel(_pdd_logger.level)
  34. # 保留原 print 的调用方式,但统一写入日志,避免到处翻控制台输出。
  35. # 说明:
  36. # 1. 现有代码里的 print(...) 不需要逐个改;
  37. # 2. 默认输出会走 logging,自动带时间、级别并写文件;
  38. # 3. 只有当 print(file=某文件对象) 时,才回退到原生 print,避免改变文件写入语义。
  39. _ORIGINAL_PRINT = builtins.print
  40. def print(*args, sep=" ", end="\n", file=None, flush=False):
  41. message = sep.join(str(arg) for arg in args)
  42. if end and end != "\n":
  43. message = f"{message}{end}"
  44. logged = False
  45. try:
  46. root_logger = logging.getLogger()
  47. if root_logger.handlers:
  48. root_logger.info(message.rstrip("\n"))
  49. logged = True
  50. except Exception:
  51. logged = False
  52. # 日志链路异常或未初始化时,至少保证能在控制台看到输出
  53. if not logged:
  54. _ORIGINAL_PRINT(*args, sep=sep, end=end, file=file if file else sys.stdout, flush=flush)
  55. if file not in (None, sys.stdout, sys.stderr):
  56. _ORIGINAL_PRINT(*args, sep=sep, end=end, file=file, flush=flush)
  57. # 功能:这个模块负责从数据库拉取拼多多待执行任务,把任务分发到空闲设备,
  58. # 然后在单设备线程中驱动 App 完成搜索、采集、校验、去重和落库。
  59. # 边界:这里主要做调度和采集流程编排,不负责数据库表结构定义,也不负责
  60. # OCR 服务、滑块识别服务或盒数提取逻辑本身的实现,它们都通过外部依赖完成。
  61. # 数据库连接池(与 YBM 同库:120.24.26.108:3307/drug_retrieve_test,但不用 DictCursor)
  62. from dbutils.pooled_db import PooledDB
  63. _db_pool = PooledDB(
  64. creator=pymysql,
  65. maxconnections=10,
  66. mincached=2,
  67. maxcached=5,
  68. blocking=True,
  69. charset="utf8mb4",
  70. host="120.24.26.108",
  71. port=3307,
  72. user="root",
  73. password="zhijiayun123456",
  74. database="drug_retrieve_test",
  75. )
  76. def get_mysql():
  77. """从连接池获取数据库连接(兼容旧接口)。调用方负责 conn.close() 归还连接。"""
  78. return _db_pool.connection()
  79. def get_access_token():
  80. AppKey = "1gAzACJOAr7BeILKqkqPOETh"
  81. AppSrcret = "ZNArANb9GwJYgLKg4EfYhukKBfPdl1n3"
  82. token_url = 'https://aip.baidubce.com/oauth/2.0/token'
  83. url = f"{token_url}?grant_type=client_credentials&client_id={AppKey}&client_secret={AppSrcret}"
  84. payload = ""
  85. headers = {
  86. 'Content-Type': 'application/json',
  87. 'Accept': 'application/json'
  88. }
  89. response = requests.request("POST", url, headers=headers, data=payload)
  90. try:
  91. return response.json()['access_token']
  92. except:
  93. return None
  94. # 心跳上报配置
  95. HEARTBEAT_INTERVAL_SECONDS = 60 # 心跳上报间隔(秒)
  96. HEARTBEAT_API_URL = "http://120.24.26.108:8082/api/collect_task/heartbeat" # 与 YBM 共用
  97. SCHEDULER_INTERVAL_SECONDS = 600
  98. MANUAL_SCHEDULER_INTERVAL_SECONDS = 300
  99. PLATFORM_PDD = 3
  100. TASK_STATUS_PENDING = 1
  101. DEVICE_STATUS_IDLE = 0
  102. DEFAULT_MAX_COUNTS_LIMIT = 300
  103. PLATFORM_NAME_MAP = {
  104. PLATFORM_PDD: "拼多多",
  105. str(PLATFORM_PDD): "拼多多",
  106. }
  107. BRAND_ALIAS_MAP = {
  108. "小葵花": ["葵花"],
  109. "999": ['三九'],
  110. }
  111. # 手动任务模式:
  112. # False -> 保持原有数据库取任务逻辑
  113. # True -> 不从数据库取任务,直接使用 MANUAL_TASKS
  114. USE_MANUAL_TASKS = False
  115. # 手动任务示例(按需修改,可配置多条)
  116. # 必填:search_key;device_id 不需要填写,手动模式会自动选择空闲 PDD 设备。
  117. MANUAL_TASKS = []
  118. task_list = [
  119. ("金活依马打正红花油", "依马打正红花油", [], "金活"),("金活依马打正红花油", "依马打正红花油", [], "金活"),("金活依马打正红花油", "依马打正红花油", [], "金活"),("金活依马打正红花油", "依马打正红花油", [], "金活"),("金活依马打正红花油", "依马打正红花油", [], "金活"),("金活依马打正红花油", "依马打正红花油", [], "金活"),("金活依马打正红花油", "依马打正红花油", [], "金活"),("金活依马打正红花油", "依马打正红花油", [], "金活"),
  120. ]
  121. for search_key, title_key, spec_list, brand in task_list:
  122. MANUAL_TASKS.append({
  123. "search_key": search_key,
  124. "title_key": title_key,
  125. "spec_list": spec_list,
  126. "brand": brand,
  127. "save_search_key": search_key,
  128. "enterprise_id": 8,
  129. "start_page": 0,
  130. "end_page": 500,
  131. "max_counts_limit": 500,
  132. "sort": "升序",
  133. "collect_round": 2,
  134. "collect_equipment_account_id": 1,
  135. "collect_region_id": 1,
  136. })
  137. # 这些集合只表示"当前进程里的占用状态"。
  138. # 数据库里设备仍可能显示空闲,因此调度前后都要结合这几份内存状态做去重。
  139. dispatch_lock = threading.Lock()
  140. running_task_ids = set()
  141. running_device_ids = set()
  142. worker_threads = {}
  143. scheduler_stop_event = threading.Event()
  144. scheduler_timer = None
  145. manual_dispatched_task_ids = set()
  146. def get_platform_name(platform):
  147. if platform in (None, ""):
  148. return "拼多多"
  149. return PLATFORM_NAME_MAP.get(platform, PLATFORM_NAME_MAP.get(str(platform), str(platform)))
  150. # 功能:把外部输入安全转成整数;当值为空或格式不合法时回退到默认值。
  151. # 输入约束:允许传入 None、空字符串、数字字符串或整数。
  152. # 返回:成功时返回 int,失败时返回 default。
  153. def parse_optional_int(value, default=None):
  154. if value in (None, ""):
  155. return default
  156. try:
  157. return int(value)
  158. except (TypeError, ValueError):
  159. return default
  160. def get_adb_device_status_map():
  161. # 功能:读取 ADB 真实设备状态;只有状态为 device 才认为可执行自动化。
  162. try:
  163. result = subprocess.run(
  164. ["adb", "devices"],
  165. capture_output=True,
  166. text=True,
  167. timeout=10,
  168. )
  169. except Exception as e:
  170. logging.exception(f"读取 ADB 设备状态失败: {e}")
  171. return {}
  172. status_map = {}
  173. for line in result.stdout.splitlines():
  174. line = line.strip()
  175. if not line or line.startswith("List of devices"):
  176. continue
  177. parts = line.split()
  178. if len(parts) >= 2:
  179. status_map[parts[0]] = parts[1]
  180. return status_map
  181. def is_adb_device_online(device_id, adb_status_map=None):
  182. device_id = str(device_id or "").strip()
  183. if not device_id:
  184. return False
  185. if adb_status_map is None:
  186. adb_status_map = get_adb_device_status_map()
  187. return adb_status_map.get(device_id) == "device"
  188. def fetch_idle_pdd_devices():
  189. # 功能:读取数据库里所有空闲的拼多多设备;真实在线状态由 ADB 再二次判断。
  190. conn = None
  191. try:
  192. conn = get_mysql()
  193. with conn.cursor() as cursor:
  194. sql = """
  195. SELECT *
  196. FROM retrieve_collect_equipment_account
  197. WHERE platform = %s AND status = %s
  198. ORDER BY id ASC
  199. """
  200. cursor.execute(sql, (PLATFORM_PDD, DEVICE_STATUS_IDLE))
  201. return cursor.fetchall()
  202. except Exception as e:
  203. logging.exception(f"读取空闲 PDD 设备失败: {e}")
  204. return []
  205. finally:
  206. if conn:
  207. conn.close()
  208. def fetch_manual_task_payloads():
  209. payloads = []
  210. idle_devices = list(fetch_idle_pdd_devices())
  211. adb_status_map = get_adb_device_status_map()
  212. idle_device_idx = 0
  213. for idx, task in enumerate(MANUAL_TASKS):
  214. task_id = parse_optional_int(task.get("task_id"), 900000 + idx + 1)
  215. if task_id in manual_dispatched_task_ids:
  216. continue
  217. search_key = str(task.get("search_key", "")).strip()
  218. if not search_key:
  219. logging.warning(f"跳过手动任务,缺少 search_key: {task}")
  220. continue
  221. device_row = None
  222. while idle_device_idx < len(idle_devices):
  223. candidate_device = idle_devices[idle_device_idx]
  224. idle_device_idx += 1
  225. candidate_device_id = str(candidate_device[11]).strip()
  226. if not is_adb_device_online(candidate_device_id, adb_status_map):
  227. logging.info(
  228. f"手动任务 {task_id} 跳过 ADB 非在线设备 {candidate_device_id}, "
  229. f"status={adb_status_map.get(candidate_device_id, 'missing')}"
  230. )
  231. continue
  232. with dispatch_lock:
  233. if candidate_device_id in running_device_ids:
  234. continue
  235. running_task_ids.add(task_id)
  236. running_device_ids.add(candidate_device_id)
  237. device_row = candidate_device
  238. break
  239. if not device_row:
  240. logging.info(f"手动任务 {task_id} 没有可用空闲设备,本轮跳过")
  241. continue
  242. device_id = str(device_row[11]).strip()
  243. title_key = task.get("title_key")
  244. save_search_key = task.get("save_search_key")
  245. payloads.append({
  246. "task_id": task_id,
  247. "equipment_id": device_row[1],
  248. "enterprise_id": parse_optional_int(task.get("enterprise_id"), 0),
  249. "platform": parse_optional_int(task.get("platform"), PLATFORM_PDD),
  250. "title_key": title_key if title_key not in (None, "") else search_key,
  251. "spec_list": task.get("spec_list", ""),
  252. "brand": task.get("brand", ""),
  253. "search_key": search_key,
  254. "save_search_key": save_search_key if save_search_key not in (None, "") else search_key,
  255. "start_page": parse_optional_int(task.get("start_page"), 0),
  256. "end_page": parse_optional_int(task.get("end_page"), None),
  257. "max_counts_limit": parse_optional_int(task.get("max_counts_limit"), DEFAULT_MAX_COUNTS_LIMIT),
  258. "collect_config_info": task.get("collect_config_info", ""),
  259. 'collect_equipment_account_id': task.get("collect_equipment_account_id", ""),
  260. 'collect_region_id':task.get("collect_region_id", ""),
  261. 'collect_round': task.get("collect_round", ""),
  262. "sort": task.get("sort", "默认"),
  263. "device_id": device_id,
  264. "task_row": None,
  265. "direct_shop_lookup": bool(task.get("direct_shop_lookup", False)),
  266. })
  267. manual_dispatched_task_ids.add(task_id)
  268. if payloads:
  269. logging.info(f"手动任务模式启用,本轮分发 {len(payloads)} 条任务")
  270. else:
  271. logging.info("手动任务模式启用,但没有可分发的新任务")
  272. return payloads
  273. def fetch_pending_tasks():
  274. """通过调度 API 为每个空闲 PDD 设备拉取任务(替代原 DB 查询 retrieve_collect_task_allocate)。"""
  275. tasks = []
  276. idle_devices = fetch_idle_pdd_devices()
  277. if not idle_devices:
  278. logging.info("当前没有空闲 PDD 设备")
  279. return tasks
  280. for device_row in idle_devices:
  281. username = device_row[4] # 调度系统注册的账号名(如 pdd_1)
  282. device_id = device_row[11] or username # ADB 序列号,空时用 username 兜底
  283. if not username:
  284. continue
  285. with dispatch_lock:
  286. if device_id in running_device_ids:
  287. continue
  288. # 用 username 向调度 API 拉任务(先发心跳注册账号,跟 YBM 一样)
  289. scheduler = CrawlerScheduler(username, str(PLATFORM_PDD))
  290. requests.post(
  291. scheduler.heartbeat_url,
  292. json={"platform": scheduler.platform, "username": scheduler.username},
  293. headers={'X-Crawler-Token': 'zhijiayun_crawler_2026'},
  294. timeout=5,
  295. )
  296. task = scheduler.get_task()
  297. if task:
  298. task['_device_row'] = device_row
  299. task['_device_id'] = device_id
  300. tasks.append(task)
  301. return tasks
  302. def fetch_idle_device_by_equipment_id(equipment_id):
  303. # 功能:按设备 id 查询指定终端是否空闲,避免任务和设备错配。
  304. # 调用 get_mysql() 的目的是查询指定设备是否空闲,避免把任务错误派发到其他终端。
  305. conn = None
  306. try:
  307. conn = get_mysql()
  308. with conn.cursor() as cursor:
  309. sql = """
  310. SELECT *
  311. FROM retrieve_collect_equipment_account
  312. WHERE collect_equipment_id = %s AND status = %s
  313. LIMIT 1
  314. """
  315. cursor.execute(sql, ( equipment_id, DEVICE_STATUS_IDLE))
  316. return cursor.fetchone()
  317. except Exception as e:
  318. logging.exception(f"读取空闲设备失败 equipment_id={equipment_id}: {e}")
  319. return None
  320. finally:
  321. if conn:
  322. conn.close()
  323. def build_task_payload(task_row, device_row):
  324. # 功能:把数据库原始任务行和设备行整理成线程入口可直接消费的任务上下文。
  325. # 返回:统一字段名的字典,避免后续线程逻辑继续依赖固定列下标。
  326. sampling_cycle = str(task_row[12]).strip() if len(task_row) > 12 else ''
  327. sampling_start_time = parse_optional_int(task_row[13] if len(task_row) > 13 else None, 0)
  328. sampling_end_time = parse_optional_int(task_row[14] if len(task_row) > 14 else None, 0)
  329. start_page = parse_optional_int(task_row[15] if len(task_row) > 15 else None, 0)
  330. end_page = parse_optional_int(task_row[16] if len(task_row) > 16 else None, 300)
  331. max_counts_limit = parse_optional_int(
  332. task_row[17] if len(task_row) > 17 else None,
  333. DEFAULT_MAX_COUNTS_LIMIT
  334. )
  335. collect_config_info = json.dumps({
  336. "sampling_cycle": sampling_cycle,
  337. "sampling_start_time": sampling_start_time,
  338. "sampling_end_time": sampling_end_time,
  339. }, ensure_ascii=False)
  340. return {
  341. "task_id": task_row[0],
  342. "task_name": task_row[1],
  343. "collect_equipment_account_id": task_row[3],
  344. "collect_region_id": task_row[4],
  345. "equipment_id": task_row[2],
  346. "enterprise_id": task_row[5],
  347. "platform": task_row[6],
  348. "title_key": task_row[7],
  349. "spec_list": task_row[8],
  350. "brand": task_row[9],
  351. "search_key": f"{task_row[9]}{task_row[7]} {task_row[8] or ''}".strip(),
  352. "save_search_key": f"{task_row[9]}{task_row[7]} {task_row[8] or ''}".strip(),
  353. "start_page": start_page,
  354. "end_page": end_page,
  355. "max_counts_limit": max_counts_limit,
  356. "collect_config_info": collect_config_info,
  357. "collect_round": task_row[24],
  358. "sort": "升序",
  359. "device_id": device_row[11],
  360. "task_row": task_row,
  361. }
  362. def build_task_payload_from_api(task_dict, device_row):
  363. """从调度 API 返回的 task dict + DB 设备行构建 worker 线程可消费的 payload。"""
  364. username = device_row[4] # 调度系统账号名(如 pdd_1)
  365. device_id = device_row[11] or username # ADB 序列号,空时用 username 兜底
  366. search_key = (
  367. f"{task_dict.get('product_brand', '')}"
  368. f"{task_dict.get('product_name', '')} "
  369. f"{task_dict.get('product_specs', '') or ''}"
  370. ).strip()
  371. spec_raw = task_dict.get('product_specs', '') or ''
  372. spec_list = [s.strip() for s in re.split(r'[|、,,\n\r]+', spec_raw) if s.strip()]
  373. collect_config_info = json.dumps({
  374. "sampling_cycle": task_dict.get('sampling_cycle', ''),
  375. "sampling_start_time": task_dict.get('sampling_start_time', 0),
  376. "sampling_end_time": task_dict.get('sampling_end_time', 0),
  377. }, ensure_ascii=False)
  378. return {
  379. "task_id": task_dict.get('id'),
  380. "search_key": search_key,
  381. "title_key": task_dict.get('product_name'),
  382. "spec_list": spec_list,
  383. "brand": task_dict.get('product_brand', ''),
  384. "save_search_key": search_key,
  385. "start_page": task_dict.get('current_page', 0),
  386. "end_page": None,
  387. "max_counts_limit": DEFAULT_MAX_COUNTS_LIMIT,
  388. "collect_config_info": collect_config_info,
  389. "platform": PLATFORM_PDD,
  390. "enterprise_id": task_dict.get('company_id'),
  391. "collect_round": task_dict.get('collect_round'),
  392. "collect_equipment_account_id": task_dict.get('collect_equipment_account_id', 1),
  393. "collect_region_id": task_dict.get('collect_region_id', 1),
  394. "sort": "升序",
  395. "username": username, # 调度 API 账号名
  396. "device_id": device_id, # ADB 序列号
  397. "device_row": device_row,
  398. }
  399. def fetch_runnable_task_payloads():
  400. """通过调度 API 拉取任务,结合 DB 设备空闲状态,生成可执行的 payload 列表。"""
  401. if USE_MANUAL_TASKS:
  402. logging.info("手动任务模式启用,跳过 API 任务分配")
  403. return fetch_manual_task_payloads()
  404. api_tasks = fetch_pending_tasks()
  405. if not api_tasks:
  406. logging.info("当前没有待执行任务")
  407. return []
  408. payloads = []
  409. for task_dict in api_tasks:
  410. device_row = task_dict.get('_device_row')
  411. device_id = task_dict.get('_device_id')
  412. task_id = task_dict.get('id')
  413. if not device_row or not device_id:
  414. continue
  415. with dispatch_lock:
  416. if device_id in running_device_ids:
  417. logging.info(f"设备 {device_id} 已在本进程执行任务,跳过任务 {task_id}")
  418. continue
  419. running_device_ids.add(device_id)
  420. payloads.append(build_task_payload_from_api(task_dict, device_row))
  421. return payloads
  422. def cleanup_finished_workers():
  423. # 功能:同步 worker_threads / running_device_ids / running_task_ids,
  424. # 只保留仍然存活的线程引用,避免失效线程长期占位导致设备和任务被永久跳过。
  425. with dispatch_lock:
  426. dead_device_ids = [
  427. device_id
  428. for device_id, thread in worker_threads.items()
  429. if not thread.is_alive()
  430. ]
  431. for device_id in dead_device_ids:
  432. worker_threads.pop(device_id, None)
  433. running_device_ids.discard(device_id)
  434. orphan_device_ids = [
  435. device_id
  436. for device_id in running_device_ids
  437. if device_id not in worker_threads
  438. ]
  439. for device_id in orphan_device_ids:
  440. running_device_ids.discard(device_id)
  441. if not worker_threads and running_task_ids:
  442. logging.info(
  443. f"cleanup: 无存活 worker,清空残留 running_task_ids: {running_task_ids}"
  444. )
  445. running_task_ids.clear()
  446. def wait_for_active_workers(check_interval=1):
  447. while True:
  448. cleanup_finished_workers()
  449. with dispatch_lock:
  450. alive_threads = [thread for thread in worker_threads.values() if thread.is_alive()]
  451. if not alive_threads:
  452. return
  453. time.sleep(check_interval)
  454. def has_active_workers():
  455. cleanup_finished_workers()
  456. with dispatch_lock:
  457. return any(thread.is_alive() for thread in worker_threads.values())
  458. def all_manual_tasks_dispatched():
  459. expected_task_ids = {
  460. parse_optional_int(task.get("task_id"), 900000 + idx + 1)
  461. for idx, task in enumerate(MANUAL_TASKS)
  462. }
  463. return expected_task_ids.issubset(manual_dispatched_task_ids)
  464. def run_task_worker(task_payload):
  465. """单个任务线程的主入口:通过 CrawlerScheduler 维持心跳,驱动 PDD 采集并上报。"""
  466. task_id = task_payload["task_id"]
  467. device_id = task_payload["device_id"] # ADB 序列号(u2.connect_usb 用)
  468. username = task_payload.get("username", device_id) # 调度系统账号名
  469. search_key = str(task_payload.get("search_key", "")).strip()
  470. pdd = None
  471. should_send_finish_notice = False
  472. # 每个设备线程拥有自己的 CrawlerScheduler 实例,负责心跳 + 上报
  473. scheduler = CrawlerScheduler(username, str(PLATFORM_PDD))
  474. scheduler.start() # 启动后台心跳线程
  475. try:
  476. logging.info(f"[任务 {task_id}] 开始执行,设备: {device_id}")
  477. print(task_payload)
  478. pdd = PDD(
  479. task_payload["search_key"],
  480. device_id,
  481. title_key=task_payload.get("title_key"),
  482. spec_list=task_payload.get("spec_list"),
  483. brand=task_payload.get("brand", ""),
  484. save_search_key=task_payload.get("save_search_key"),
  485. start_page=task_payload.get("start_page"),
  486. end_page=task_payload.get("end_page"),
  487. max_counts_limit=task_payload.get("max_counts_limit"),
  488. collect_config_info=task_payload.get("collect_config_info", ""),
  489. direct_shop_lookup=task_payload.get("direct_shop_lookup", False),
  490. sort=task_payload.get("sort"),
  491. platform=task_payload.get("platform"),
  492. task_id=task_payload.get("task_id"),
  493. enterprise_id=task_payload.get("enterprise_id"),
  494. collect_round=task_payload.get("collect_round"),
  495. collect_equipment_account_id=task_payload.get("collect_equipment_account_id", 1),
  496. collect_region_id=task_payload.get("collect_region_id", 1),
  497. username=task_payload.get("username"),
  498. )
  499. completed_normally = pdd.main(device_id, 1, 0)
  500. if completed_normally:
  501. logging.info(f"[任务 {task_id}] 执行完成,设备: {device_id}")
  502. else:
  503. logging.info(f"[任务 {task_id}] 已结束,设备: {device_id}")
  504. should_send_finish_notice = True
  505. except Exception as e:
  506. end_page = task_payload.get("start_page")
  507. err_msg = str(e)
  508. if pdd is not None:
  509. end_page = getattr(pdd, "page", end_page)
  510. pdd.finish_task_abnormally(end_page, f"任务执行异常: {err_msg}")
  511. else:
  512. report_api(task_id, platform=PLATFORM_PDD, username="unknown",
  513. page=end_page, is_finished=0)
  514. logging.exception(f"[任务 {task_id}] 执行异常,设备: {device_id},错误: {err_msg}")
  515. send_error_card(
  516. task_name=f"PDD任务(task_id={task_id}, device={device_id}, key={search_key})",
  517. err_msg=err_msg,
  518. mention_all=False,
  519. )
  520. should_send_finish_notice = True
  521. finally:
  522. scheduler.stop() # 停止心跳
  523. # 释放内存占用标记
  524. with dispatch_lock:
  525. running_device_ids.discard(device_id)
  526. worker_threads.pop(device_id, None)
  527. if pdd is not None:
  528. try:
  529. pdd.ensure_home_before_task_end(max_rounds=6)
  530. except Exception as cleanup_error:
  531. logging.info(f"[任务 {task_id}] 收尾回主页面失败: {cleanup_error}")
  532. if should_send_finish_notice:
  533. scraped_count = getattr(pdd, "max_counts", 0) if pdd is not None else 0
  534. notify_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  535. platform_name = get_platform_name(task_payload.get("platform"))
  536. drug_name = str(task_payload.get("search_key", "")).strip()
  537. send_text(
  538. f"{notify_time} 通知:\n"
  539. f"平台: {platform_name}, 药品: {drug_name}, 爬取数据: {scraped_count}条"
  540. )
  541. def dispatch_pending_tasks():
  542. # 功能:执行一轮派单,把每个可运行任务绑定到对应设备线程。
  543. # 阶段 1:先清理已经结束的线程引用,避免占用状态过期。
  544. cleanup_finished_workers()
  545. # 阶段 2:重新计算本轮真正可运行的任务集合。
  546. # 手动改任务处
  547. task_payloads = fetch_runnable_task_payloads()
  548. # task_payloads = [
  549. # {
  550. # "task_id": 1,
  551. # "equipment_id": 1,
  552. # "enterprise_id": 1,
  553. # "platform": 3,
  554. # "title_key": '依马打正红花油',
  555. # "spec_list": '25ml',
  556. # "brand": '金活',
  557. # "search_key": '金活 依马打正红花油 25ml',
  558. # "save_search_key": '依马打正红花油',
  559. # "start_page": 0,
  560. # "end_page": 6,
  561. # "max_counts_limit": 30,
  562. # "collect_config_info": [],
  563. # 'collect_equipment_account_id': 1,
  564. # 'collect_region_id': 1,
  565. # 'collect_round': 1,
  566. # "sort": 1,
  567. # "device_id": 'XOYPOZDADU79VGVG',
  568. # "task_row": None,
  569. # "direct_shop_lookup": 1,
  570. # },
  571. # {
  572. # "task_id": 1,
  573. # "equipment_id": 1,
  574. # "enterprise_id": 1,
  575. # "platform": 3,
  576. # "title_key": '依马打正红花油',
  577. # "spec_list": '25ml',
  578. # "brand": '金活',
  579. # "search_key": '金活 依马打正红花油 25ml',
  580. # "save_search_key": '依马打正红花油',
  581. # "start_page": 0,
  582. # "end_page": 6,
  583. # "max_counts_limit": 30,
  584. # "collect_config_info": [],
  585. # 'collect_equipment_account_id': 1,
  586. # 'collect_region_id': 1,
  587. # 'collect_round': 1,
  588. # "sort": 1,
  589. # "device_id": 'U47HZDRG8XJBBURW',
  590. # "task_row": None,
  591. # "direct_shop_lookup": 1,
  592. # },
  593. # {
  594. # "task_id": 1,
  595. # "equipment_id": 1,
  596. # "enterprise_id": 1,
  597. # "platform": 3,
  598. # "title_key": '依马打正红花油',
  599. # "spec_list": '25ml',
  600. # "brand": '金活',
  601. # "search_key": '金活 依马打正红花油 25ml',
  602. # "save_search_key": '依马打正红花油',
  603. # "start_page": 0,
  604. # "end_page": 6,
  605. # "max_counts_limit": 30,
  606. # "collect_config_info": [],
  607. # 'collect_equipment_account_id': 1,
  608. # 'collect_region_id': 1,
  609. # 'collect_round': 1,
  610. # "sort": 1,
  611. # "device_id": 'U8ONIJJJS4CELVD6',
  612. # "task_row": None,
  613. # "direct_shop_lookup": 1,
  614. # }
  615. # ]
  616. if not task_payloads:
  617. return
  618. for task_payload in task_payloads:
  619. device_id = task_payload["device_id"]
  620. try:
  621. # 阶段 3:为每个任务创建独立线程,让不同设备可以并发执行采集。
  622. thread = threading.Thread(
  623. target=run_task_worker,
  624. args=(task_payload,),
  625. daemon=True,
  626. name=f"pdd-{device_id}",
  627. )
  628. with dispatch_lock:
  629. worker_threads[device_id] = thread
  630. thread.start()
  631. logging.info(f"[任务 {task_payload['task_id']}] 已分发到设备 {device_id}")
  632. except Exception:
  633. with dispatch_lock:
  634. # 线程创建失败时同步回滚占用状态,避免任务被"卡住"。
  635. running_task_ids.discard(task_payload["task_id"])
  636. running_device_ids.discard(device_id)
  637. worker_threads.pop(device_id, None)
  638. raise
  639. def schedule_dispatch(delay_seconds=SCHEDULER_INTERVAL_SECONDS, job_func=None):
  640. # 功能:安排下一次轮询触发时间。
  641. # 功能:注册下一轮调度定时器,让调度器按固定间隔持续轮询。
  642. global scheduler_timer
  643. if scheduler_stop_event.is_set():
  644. return
  645. if job_func is None:
  646. job_func = scheduled_dispatch_job
  647. # 采用递归定时器而不是死循环,便于后续统一停机。
  648. scheduler_timer = threading.Timer(delay_seconds, job_func)
  649. scheduler_timer.daemon = False
  650. scheduler_timer.name = "pdd-scheduler"
  651. scheduler_timer.start()
  652. def scheduled_dispatch_job():
  653. # 功能:执行一次定时派单,并保证下一轮轮询仍会继续注册。
  654. # 功能:包装一次定时调度执行,确保本轮出错也不会中断后续轮询。
  655. try:
  656. dispatch_pending_tasks()
  657. except Exception as e:
  658. logging.exception(f"PDD 定时调度异常: {e}")
  659. finally:
  660. schedule_dispatch(SCHEDULER_INTERVAL_SECONDS)
  661. def manual_scheduled_dispatch_job():
  662. try:
  663. dispatch_pending_tasks()
  664. except Exception as e:
  665. logging.exception(f"PDD 手动任务定时调度异常: {e}")
  666. finally:
  667. if all_manual_tasks_dispatched() and not has_active_workers():
  668. logging.info("手动任务模式:全部任务已完成,停止轮询并退出")
  669. scheduler_stop_event.set()
  670. return
  671. schedule_dispatch(MANUAL_SCHEDULER_INTERVAL_SECONDS, manual_scheduled_dispatch_job)
  672. # 调度上报配置(与 YBM 共用同一套 API)
  673. TASK_REPORT_URL = "http://120.24.26.108:8082/api/collect_task/report"
  674. TASK_HEARTBEAT_URL = "http://120.24.26.108:8082/api/collect_task/heartbeat"
  675. TASK_API_HEADERS = {'X-Crawler-Token': 'zhijiayun_crawler_2026'}
  676. def report_api(task_id, platform, username, page=0, is_finished=0,
  677. crawled_count=0, total_pages=0):
  678. """向调度中心上报任务状态(完全对齐 YBM _send_report 格式)。"""
  679. if USE_MANUAL_TASKS:
  680. logging.info(f"手动任务模式:跳过接口上报 task_id={task_id}")
  681. return
  682. params = {
  683. "task_id": task_id,
  684. "platform": str(platform),
  685. "username": str(username) if username else "",
  686. "current_page": page,
  687. "total_pages": total_pages,
  688. "crawled_count": crawled_count,
  689. "is_finished": is_finished,
  690. }
  691. print(params)
  692. try:
  693. res = requests.post(TASK_REPORT_URL, json=params, headers=TASK_API_HEADERS, timeout=20)
  694. print(res.text)
  695. except Exception as e:
  696. logging.exception(f"上报接口异常 task_id={task_id}: {e}")
  697. def report_heartbeat(task_id, page=None, device_id=None):
  698. """上报任务心跳"""
  699. if USE_MANUAL_TASKS:
  700. return
  701. params = {
  702. "collect_task_allocate_id": task_id,
  703. "heartbeat_time": int(time.time()),
  704. "current_page": page if page is not None else 0,
  705. "device_id": device_id if device_id else "",
  706. }
  707. try:
  708. requests.post(TASK_HEARTBEAT_URL, json=params, headers=TASK_API_HEADERS, timeout=10)
  709. logging.debug(f"心跳上报 task_id={task_id}, page={page}")
  710. except Exception as e:
  711. logging.warning(f"心跳上报失败: {e}")
  712. # 获取滑块验证中滑块需要移动的距离
  713. def slide_verify(img_path):
  714. # 功能:把本地截图交给第三方打码服务,换回滑块缺口位移。
  715. # 返回:识别成功时返回滑块位移结果,失败时返回服务端给出的空结果。
  716. with open(img_path, 'rb') as f:
  717. b = base64.b64encode(f.read()).decode() ## 图片二进制流base64字符串
  718. url = "http://api.jfbym.com/api/YmServer/customApi"
  719. data = {
  720. ## 关于参数,一般来说有3个;不同类型id可能有不同的参数个数和参数名,找客服获取
  721. "token": "1nDVocTE2mJ0yLEYb2sZJ5uUY2VIEoGTkIpW44X7Kgk",
  722. "type": "22222",
  723. "image": b,
  724. }
  725. _headers = {
  726. "Content-Type": "application/json"
  727. }
  728. # 识别结果来自第三方服务,当前逻辑只读取它约定的 msg/data 字段。
  729. response = requests.request("POST", url, headers=_headers, json=data).json()
  730. print(response)
  731. if response.get("msg") == "识别成功":
  732. # 获取 data 中的 data 字段
  733. result = response.get("data", {}).get("data")
  734. if result:
  735. print(result) # 输出结果
  736. else:
  737. print("无法获取数据")
  738. else:
  739. print("识别未成功")
  740. return result
  741. class PDD:
  742. # 功能:这个类负责维护单次拼多多采集任务的运行状态,并封装设备连接、
  743. # 页面导航、数据提取、说明书解析、去重校验和写库等操作。
  744. # 边界:这个类负责"如何跑完整个采集流程",但不负责外部调度器的轮询策略,
  745. # 也不负责 OCR/盒数提取等外部依赖的底层实现。
  746. def __init__(
  747. self,
  748. search_key,
  749. device_id,
  750. title_key=None,
  751. spec_list=None,
  752. brand="",
  753. save_search_key=None,
  754. start_page=0,
  755. end_page=None,
  756. max_counts_limit=None,
  757. collect_config_info="",
  758. direct_shop_lookup=False,
  759. sort=None,
  760. platform = None,
  761. task_id = None,
  762. enterprise_id=None,
  763. collect_round=None,
  764. collect_equipment_account_id=None,
  765. collect_region_id=None,
  766. username=None,
  767. ):
  768. # 阶段 1:初始化与 App、OCR、日志、OSS 相关的基础依赖。
  769. self.username = username # 调度系统账号名
  770. self.package_name = 'com.xunmeng.pinduoduo'
  771. self.APP_ID = '116857964'
  772. self.API_KEY = '1gAzACJOAr7BeILKqkqPOETh'
  773. self.SECRET_KEY = 'ZNArANb9GwJYgLKg4EfYhukKBfPdl1n3'
  774. self.client = AipOcr(self.APP_ID, self.API_KEY, self.SECRET_KEY)
  775. self.table_name = "retrieve_scrape_data" # "pdd_drug"
  776. self.shop_table_name = "retrieve_scrape_shop_info" # "pdd_shop_info"
  777. self.loggerPdd = logging.getLogger()
  778. self.clipboard = "" # 初始化剪切板的内容为空
  779. # 阶段 2:固化本次任务的筛选条件、页码边界和搜索参数。
  780. self.enterprise_id = enterprise_id
  781. self.task_id = task_id
  782. self.platform = platform
  783. self.sort = sort
  784. self.sort_key = 0
  785. self.search_key = search_key # 参苓健脾胃颗粒 香砂平胃颗粒 舒肝颗粒 清肺化痰丸
  786. # title_key 支持把"搜索词"和"标题过滤词"拆开;未单独传入时回退到搜索词。
  787. self.title_key = title_key if title_key is not None else search_key
  788. # 规格统一整理成列表,后续匹配逻辑就不用再分辨单值、列表和空值三种输入。
  789. self.spec_list = self._normalize_rule_list(spec_list)
  790. # 统一做一次清洗,避免 None/空白写入数据库。
  791. self.brand = str(brand or "").strip()
  792. self.save_search_key = save_search_key or search_key
  793. # 起止页在入口阶段先做边界修正,主循环只消费规范化后的值。
  794. self.start_page = max(parse_optional_int(start_page, 0), 0)
  795. self.end_page = parse_optional_int(end_page, None) # None = 不限页数
  796. self.max_counts_limit = max_counts_limit
  797. self.collect_config_info = collect_config_info or ""
  798. self.direct_shop_lookup = direct_shop_lookup
  799. # 任务轮次(数据库字段 collect_round)
  800. self.collect_round = collect_round
  801. self.collect_equipment_account_id = collect_equipment_account_id
  802. self.collect_region_id = collect_region_id
  803. self.unrelated_data = 0 # 无关数据数量
  804. self.device_id = device_id
  805. self.page = self.start_page
  806. self._city_lookup_cache = None
  807. self._city_lookup_path = ""
  808. # 阶段 3:初始化运行时统计状态,这些状态会在主循环中持续更新。
  809. # 统计售罄数量
  810. self.sold_out_counts = 0
  811. # 程序启动时间
  812. self.program_start_time = self.app_start_time()
  813. # 统计商品数量
  814. # 最大量数据阈值
  815. self.max_counts = 0
  816. # 统计点击商品的次数
  817. self.click_counts = 0
  818. # 商品在列表的位置
  819. self.search_key_loc = 0
  820. # finish_reported 用来保证无论走哪个退出分支,只向调度系统上报一次结束状态。
  821. self.finish_reported = False
  822. # oss配置
  823. self.oss_config = {
  824. "access_key_id": Config.access_key_id,
  825. "access_key_secret": Config.access_key_secret,
  826. "endpoint": Config.endpoint, # 例: oss-cn-beijing.aliyuncs.com
  827. "bucket_name": Config.bucket_name,
  828. "oss_prefix": Config.oss_prefix # OSS中存放截图的前缀(虚拟文件夹)
  829. }
  830. self.address_region_index = self.build_address_region_index(_DEFAULT_PATH)
  831. # 异常处理
  832. def wr_re(self, mod, device_id, sort=None, page=None):
  833. # 功能:读写或删除本地进度文件,给断点续跑保留入口。
  834. file_path = f'./ycwj/{device_id}_{self.title_key}.txt'
  835. if mod == "写":
  836. try:
  837. data = {
  838. "page": page if page else "",
  839. "sort": sort if sort else "",
  840. }
  841. os.makedirs(os.path.dirname(file_path), exist_ok=True)
  842. with open(file_path, 'w', encoding='utf-8') as f:
  843. json.dump(data, f, ensure_ascii=False, indent=2)
  844. print(f"进度保存成功:{sort},{page}页")
  845. except Exception as e:
  846. print("保存进度失败")
  847. elif mod == "读":
  848. try:
  849. if not os.path.exists(file_path):
  850. return None
  851. with open(file_path, 'r', encoding='utf-8') as f:
  852. data = json.load(f)
  853. print(self.sort)
  854. # if self.sort and self.sort_key == 0:
  855. # self.li_or_lo(self.sort)
  856. if data['page'] != '':
  857. progress_page = int(data['page'])
  858. self.page = max(progress_page, self.start_page)
  859. self.scroll_to_target_page(self.page)
  860. else:
  861. return None
  862. return data
  863. except Exception as e:
  864. print(f"读取进度失败", e)
  865. return None
  866. elif mod == "删":
  867. try:
  868. if os.path.exists(file_path):
  869. os.remove(file_path)
  870. print(f"进度文件已删除:{file_path}")
  871. except Exception as e:
  872. print(f"删除进度文件失败:{e}")
  873. return None
  874. def clear_progress_file(self):
  875. # 功能:任务正常完成后清理断点进度文件。
  876. self.wr_re("删", self.device_id, self.sort)
  877. def is_max_count_reached(self):
  878. # 功能:判断当前采集数量是否达到任务设定上限。
  879. return bool(self.max_counts_limit and self.max_counts >= self.max_counts_limit)
  880. def scroll_to_target_page(self, target_page):
  881. # 功能:按目标页数执行固定次数滑动,用于恢复上次采集的大致位置。
  882. target_page = int(target_page or 0)
  883. if target_page <= 0:
  884. return
  885. # 这里按"页数约等于滑动次数"的经验规则恢复列表位置,宁可保守,不做复杂校准。
  886. for _ in range(target_page):
  887. screen_w, screen_h = self.get_screen_size()
  888. end_y = int(screen_h * 0.18)
  889. self.d.swipe(screen_w // 2, int(screen_h * 0.85), screen_w // 2, end_y, 0.4)
  890. time.sleep(self.get_sleep_time())
  891. def finish_task_normally(self, end_page, reason):
  892. if not self.finish_reported:
  893. report_api(
  894. self.task_id,
  895. platform=self.platform,
  896. username=getattr(self, 'username', ''),
  897. page=end_page,
  898. is_finished=1,
  899. crawled_count=getattr(self, 'max_counts', 0),
  900. total_pages=end_page,
  901. )
  902. self.finish_reported = True
  903. print(reason)
  904. return True
  905. def finish_task_abnormally(self, end_page, reason, finish_status=0):
  906. if not self.finish_reported:
  907. report_api(
  908. self.task_id,
  909. platform=self.platform,
  910. username=getattr(self, 'username', ''),
  911. page=end_page,
  912. is_finished=0,
  913. crawled_count=getattr(self, 'max_counts', 0),
  914. total_pages=end_page,
  915. )
  916. self.finish_reported = True
  917. print(reason)
  918. return False
  919. def finish_task_with_max_count(self, end_page):
  920. # 功能:达到采集上限时复用正常结束逻辑,只替换结束原因。
  921. return self.finish_task_normally(
  922. end_page,
  923. f"达到最大采集数量 {self.max_counts_limit},当前已采集 {self.max_counts} 条,停止任务"
  924. )
  925. # 排序
  926. def li_or_lo(self, key):
  927. # 功能:进入搜索结果页后切换价格排序方式。
  928. if key == "升序":
  929. self.sort_key += 1
  930. self.d.xpath('//*[@text="价格"]').click()
  931. n = self.d.xpath('//*[@text="总价低到高"]')
  932. if n.exists:
  933. n.click()
  934. time.sleep(self.get_sleep_time())
  935. if key == "降序":
  936. self.sort_key += 1
  937. self.d.xpath('//*[@text="价格"]').click()
  938. n = self.d.xpath('//*[@text="单粒价格低到高"]')
  939. if n:
  940. n.click()
  941. else:
  942. self.d.xpath('//*[@text="价格"]').click()
  943. # 返回列表页
  944. def back_to_list_page(self):
  945. # 功能:通过多次尝试返回键,尽量把页面恢复到商品列表页。
  946. try:
  947. for i in range(10):
  948. if self.distinct_target():
  949. return True
  950. if self.d(className='android.widget.EditText').exists and not self.d.xpath('//*[@text="筛选"]').exists:
  951. print('当前已进入搜索输入页,停止继续返回,交给上层重新进入搜索结果页')
  952. return False
  953. print(f'第{i}次尝试退回到列表页')
  954. self.swipe_back(1)
  955. except:
  956. if self.is_pdd_home_page():
  957. print('当前已回到首页,停止继续返回,交给上层重新进入搜索结果页')
  958. return False
  959. else:
  960. print('页面出错,没有退回到列表页')
  961. return False
  962. def get_drug_lis(self, idx):
  963. # 功能:根据当前页布局拿到可点击的商品卡片列表。
  964. # 这里区分 idx==0 和后续页面,是因为首屏与翻页后的 RecyclerView 层级不完全一致。
  965. drug_lis = []
  966. if idx == 0:
  967. drug_lis = self.d.xpath(
  968. '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.FrameLayout[2]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.support.v7.widget.RecyclerView[1]/android.widget.FrameLayout').all()
  969. else:
  970. for i in range(1, 6):
  971. drug_lis = self.d.xpath(
  972. f'/hierarchy/android.widget.FrameLayout[{i}]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.support.v7.widget.RecyclerView[1]/android.widget.FrameLayout').all()
  973. if drug_lis:
  974. break
  975. if drug_lis:
  976. return drug_lis
  977. fallback_xpaths = [
  978. '//android.support.v7.widget.RecyclerView/android.widget.FrameLayout',
  979. '//androidx.recyclerview.widget.RecyclerView/android.widget.FrameLayout',
  980. '//*[@class="android.support.v7.widget.RecyclerView"]/android.widget.FrameLayout',
  981. '//*[@class="androidx.recyclerview.widget.RecyclerView"]/android.widget.FrameLayout',
  982. ]
  983. for fallback_xpath in fallback_xpaths:
  984. drug_lis = self.d.xpath(fallback_xpath).all()
  985. if drug_lis:
  986. logging.info(f"get_drug_lis: fallback xpath 命中 {fallback_xpath},数量={len(drug_lis)}")
  987. break
  988. return drug_lis
  989. # 【新增】图片拼接辅助函数(垂直拼接两张截图)
  990. def merge_two_images(self, img1_path, img2_path, output_path):
  991. """
  992. 垂直拼接两张截图(统一宽度,高度累加)
  993. :param img1_path: 第一张图路径
  994. :param img2_path: 第二张图路径
  995. :param output_path: 拼接后输出路径
  996. """
  997. try:
  998. # 打开两张图片
  999. img1 = Image.open(img1_path)
  1000. img2 = Image.open(img2_path)
  1001. # 统一宽度(以较宽的图为准)
  1002. max_width = max(img1.width, img2.width)
  1003. img1 = img1.resize((max_width, int(img1.height * max_width / img1.width)), Image.Resampling.LANCZOS)
  1004. img2 = img2.resize((max_width, int(img2.height * max_width / img2.width)), Image.Resampling.LANCZOS)
  1005. # 创建拼接后的画布(垂直拼接)
  1006. merge_height = img1.height + img2.height
  1007. merge_img = Image.new('RGB', (max_width, merge_height))
  1008. merge_img.paste(img1, (0, 0))
  1009. merge_img.paste(img2, (0, img1.height))
  1010. # 保存拼接后的图片
  1011. merge_img.save(output_path, quality=95)
  1012. self.loggerPdd.info(f"✅ 图片拼接完成:{output_path}")
  1013. return True
  1014. except Exception as e:
  1015. self.loggerPdd.error(f"❌ 图片拼接失败:{str(e)}")
  1016. return False
  1017. # 【新增】图片压缩辅助函数(基于cv2,控制文件大小)
  1018. def compress_image(self, input_path, output_path, target_size_kb=100, max_quality=80, min_quality=20):
  1019. """
  1020. 压缩图片到指定大小(默认100KB以内),先缩尺寸再调质量
  1021. :param input_path: 原始图片路径
  1022. :param output_path: 压缩后输出路径
  1023. :param target_size_kb: 目标大小(KB),默认100
  1024. :param max_quality: 初始最大质量(1-100)
  1025. :param min_quality: 最低质量(避免过度模糊)
  1026. :return: bool: 压缩是否成功
  1027. """
  1028. try:
  1029. # 1. 读取原始图片
  1030. img = cv2.imread(input_path)
  1031. if img is None:
  1032. self.loggerPdd.error(f"❌ 读取图片失败:{input_path}")
  1033. return False
  1034. # 2. 先按比例缩小尺寸(核心:降低分辨率)
  1035. height, width = img.shape[:2]
  1036. # 先缩放到原尺寸的70%(可根据需要调整,比如60%/50%)
  1037. scale = 0.7 # 缩放比例,越小文件越小(0.7=70%尺寸)
  1038. new_width = int(width * scale)
  1039. new_height = int(height * scale)
  1040. img_resized = cv2.resize(
  1041. img, (new_width, new_height),
  1042. interpolation=cv2.INTER_AREA # 缩小用INTER_AREA更清晰
  1043. )
  1044. # 3. 动态调整质量,直到文件≤target_size_kb或达到最低质量
  1045. quality = max_quality
  1046. ext = os.path.splitext(output_path)[1].lower()
  1047. encode_param = [cv2.IMWRITE_JPEG_QUALITY, quality]
  1048. while quality >= min_quality:
  1049. # 保存图片
  1050. cv2.imwrite(output_path, img_resized, encode_param)
  1051. # 检测文件大小
  1052. file_size = os.path.getsize(output_path) / 1024 # 转KB
  1053. self.loggerPdd.info(f"🔍 质量{quality},文件大小:{file_size:.2f}KB")
  1054. # 达标则退出循环
  1055. if file_size <= target_size_kb:
  1056. self.loggerPdd.info(f"✅ 图片压缩完成:{output_path}(最终质量:{quality},大小:{file_size:.2f}KB)")
  1057. return True
  1058. # 未达标则降低质量(每次降5,可调整步长)
  1059. quality -= 5
  1060. encode_param[1] = quality
  1061. # 若到最低质量仍超标,再缩小尺寸(兜底)
  1062. self.loggerPdd.warning(f"⚠️ 最低质量{min_quality}仍超标,再次缩小尺寸到50%")
  1063. new_width_2 = int(new_width * 0.5)
  1064. new_height_2 = int(new_height * 0.5)
  1065. img_resized_2 = cv2.resize(img_resized, (new_width_2, new_height_2), cv2.INTER_AREA)
  1066. encode_param[1] = min_quality
  1067. cv2.imwrite(output_path, img_resized_2, encode_param)
  1068. final_size = os.path.getsize(output_path) / 1024
  1069. self.loggerPdd.info(f"✅ 兜底压缩完成:{output_path}(质量:{min_quality},大小:{final_size:.2f}KB)")
  1070. return True
  1071. except Exception as e:
  1072. self.loggerPdd.error(f"❌ 图片压缩失败:{str(e)}")
  1073. return False
  1074. # 从商品顶部直接慢速向下滚动截长图 → 堆叠拼接 → 压缩 → 上传OSS
  1075. def screenshot_and_upload_oss(self, screenshot_desc='shop_name_screenhshot'):
  1076. """
  1077. 1. 从当前位置慢速向下滚动截屏 → 2. 堆叠拼接 → 3. 压缩 → 4. 上传OSS → 5. 清理本地文件
  1078. :param screenshot_desc: 截图描述(用于OSS文件名)
  1079. :return: oss_url: 上传后的OSS地址 | None: 失败
  1080. """
  1081. timestamp = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
  1082. unique_id = uuid.uuid4().hex[:8]
  1083. base_name = f"{screenshot_desc}_{self.device_id}_{timestamp}_{unique_id}"
  1084. # 定义临时文件路径
  1085. scroll_screenshot_path = f"./{base_name}_scroll.png" # 滚动长图
  1086. compress_path = f"./{base_name}_compress.jpg" # 压缩后的图
  1087. # 初始化OSS客户端(若未初始化)
  1088. if not hasattr(self, 'oss_bucket'):
  1089. self.oss_auth = oss2.Auth(
  1090. self.oss_config["access_key_id"],
  1091. self.oss_config["access_key_secret"]
  1092. )
  1093. self.oss_bucket = oss2.Bucket(
  1094. self.oss_auth,
  1095. self.oss_config["endpoint"],
  1096. self.oss_config["bucket_name"]
  1097. )
  1098. else:
  1099. print("oss初始化完毕")
  1100. try:
  1101. # ===================== 步骤1:滚动截屏 =====================
  1102. self.loggerPdd.info("📸 开始滚动截屏...")
  1103. try:
  1104. screenshot_image = self._scroll_screenshot()
  1105. screenshot_image.save(scroll_screenshot_path)
  1106. except Exception as e:
  1107. self.loggerPdd.error(f"滚动截图失败:{str(e)}")
  1108. return None
  1109. self.loggerPdd.info(f"✅ 滚动截图完成:{scroll_screenshot_path}")
  1110. # ===================== 步骤2:压缩图片 =====================
  1111. if not self.compress_image(scroll_screenshot_path, compress_path, target_size_kb=100):
  1112. raise Exception("图片压缩失败")
  1113. # ===================== 步骤3:上传压缩后的图片到OSS =====================
  1114. oss_file_path = f"{self.oss_config['oss_prefix']}/{os.path.basename(compress_path)}"
  1115. # 上传文件到OSS
  1116. self.oss_bucket.put_object_from_file(oss_file_path, compress_path)
  1117. # 生成OSS访问URL
  1118. oss_url = f"https://{self.oss_config['bucket_name']}.{self.oss_config['endpoint']}/{oss_file_path}"
  1119. self.loggerPdd.info(f"🚀 OSS上传成功:{oss_url}")
  1120. return oss_url
  1121. except Exception as e:
  1122. self.loggerPdd.error(f"❌ 截图/压缩/上传OSS失败:{str(e)}")
  1123. return None
  1124. finally:
  1125. # ===================== 步骤4:清理所有本地临时文件 =====================
  1126. for file_path in [scroll_screenshot_path, compress_path]:
  1127. if os.path.exists(file_path):
  1128. try:
  1129. os.remove(file_path)
  1130. self.loggerPdd.info(f"🗑️ 清理临时文件:{file_path}")
  1131. except Exception as e:
  1132. self.loggerPdd.warning(f"⚠️ 清理临时文件失败 {file_path}:{str(e)}")
  1133. def _merge_screenshots(self, screens):
  1134. """
  1135. 不做重叠裁剪,直接垂直堆叠
  1136. """
  1137. if len(screens) == 1:
  1138. return screens[0].convert('RGB')
  1139. rgb_screens = [s.convert('RGB') for s in screens]
  1140. total_width = rgb_screens[0].width
  1141. total_height = sum(s.height for s in rgb_screens)
  1142. merged_img = Image.new('RGB', (total_width, total_height))
  1143. y_offset = 0
  1144. for img in rgb_screens:
  1145. merged_img.paste(img, (0, y_offset))
  1146. y_offset += img.height
  1147. self.loggerPdd.info(f"✅ 拼接完成,尺寸: {total_width} x {total_height}")
  1148. return merged_img
  1149. def _scroll_screenshot(self, scroll_times=1):
  1150. """
  1151. 1. 截第一张(当前位置)
  1152. 2. 如果「进店」已经在首屏 → 直接返回,不滚动
  1153. 3. 否则最多滚动 scroll_times 次(默认 1 次),到「进店」即停止
  1154. 4. 堆叠拼接
  1155. """
  1156. self.loggerPdd.info(f"📸 滚动截图开始(最多 {scroll_times} 次滚动)...")
  1157. w, h = self.d.window_size()
  1158. # 第1张:当前位置
  1159. screen_list = [self.d.screenshot()]
  1160. self.loggerPdd.info(f" 截取第 1 张,尺寸: {screen_list[0].width}x{screen_list[0].height}")
  1161. # 首屏已有「进店」→ 直接返回,不用滚
  1162. if self.d(textContains='进店').exists or self.d(textStartsWith='进店').exists:
  1163. self.loggerPdd.info(f"✅ 「进店」已在首屏,不滚动")
  1164. return self._merge_screenshots(screen_list)
  1165. for i in range(scroll_times):
  1166. self.d.swipe(w // 2, int(h * 0.85), w // 2, int(h * 0.15),
  1167. duration=random.uniform(0.8, 1.5))
  1168. time.sleep(random.uniform(2.0, 4.0))
  1169. screen_list.append(self.d.screenshot())
  1170. self.loggerPdd.info(f" 截取第 {i + 2} 张")
  1171. if self.d(textContains='进店').exists or self.d(textStartsWith='进店').exists:
  1172. self.loggerPdd.info(f"✅ 已到达「进店」位置,停止滚动")
  1173. break
  1174. return self._merge_screenshots(screen_list)
  1175. # 代码运行那时候的时间
  1176. def app_current_time(self):
  1177. # 功能:返回当前时刻的格式化时间字符串,主要用于日志打印。
  1178. return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  1179. def slide_link(self):
  1180. # 功能:在分享面板中横向滑动,把"复制链接"附近的目标入口滑到可见区域。
  1181. value_tag = None
  1182. if self.d.xpath('//*[@text="微信"]').exists:
  1183. value_tag = self.d.xpath('//*[@text="微信"]').info['bounds']
  1184. start_x = value_tag['right'] + 20
  1185. end_x = max(start_x - 280, 30)
  1186. self.d.swipe(start_x, value_tag['top'], end_x, value_tag['top'], 0.3)
  1187. return
  1188. if self.d.xpath('//*[@text="朋友圈"]').exists:
  1189. value_tag = self.d.xpath('//*[@text="朋友圈"]').info['bounds']
  1190. start_x = value_tag['right'] + 20
  1191. end_x = max(start_x - 280, 30)
  1192. self.d.swipe(start_x, value_tag['top'], end_x, value_tag['top'], 0.3)
  1193. return
  1194. if self.d.xpath('//*[@text="QQ好友"]').exists:
  1195. value_tag = self.d.xpath('//*[@text="QQ好友"]').info['bounds']
  1196. start_x = value_tag['right'] + 20
  1197. end_x = max(start_x - 280, 30)
  1198. self.d.swipe(start_x, value_tag['top'], end_x, value_tag['top'], 0.3)
  1199. return
  1200. def app_start_time(self):
  1201. """
  1202. 获取app启动时间
  1203. :return:
  1204. """
  1205. return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  1206. def stop_app(self):
  1207. # 功能:停止拼多多 App,并等待设备状态稳定下来。
  1208. self.d.app_stop(self.package_name)
  1209. time.sleep(5)
  1210. def start_app(self):
  1211. # 功能:启动拼多多 App,并预留加载时间。
  1212. self.d.app_start(self.package_name)
  1213. time.sleep(5)
  1214. def restart_app(self):
  1215. """
  1216. 重启app
  1217. :return:
  1218. """
  1219. self.stop_app()
  1220. # 这里先调用 stop_app(),是为了清掉上一次运行残留的页面状态;
  1221. # 后续 start_app() 依赖应用已经被完全拉起,搜索流程才能从稳定起点开始。
  1222. self.start_app()
  1223. def is_pdd_package_foreground(self):
  1224. """只按包名判断是否在拼多多前台,不要求页面锚点可见。"""
  1225. try:
  1226. current_app = self.d.app_current() or {}
  1227. current_package = current_app.get("package", "")
  1228. return current_package == self.package_name
  1229. except Exception:
  1230. return False
  1231. def is_pdd_home_page(self):
  1232. """判断是否在拼多多主页面(底部主导航可见)。"""
  1233. try:
  1234. home_anchors = [
  1235. '//*[@text="首页"]',
  1236. '//*[@text="分类"]',
  1237. '//*[@text="多多视频"]',
  1238. '//*[@text="聊天"]',
  1239. '//*[@text="我的"]',
  1240. '//*[@text="个人中心"]',
  1241. ]
  1242. hit_count = 0
  1243. for anchor_xpath in home_anchors:
  1244. if self.d.xpath(anchor_xpath).exists:
  1245. hit_count += 1
  1246. return hit_count >= 3
  1247. except Exception:
  1248. return False
  1249. def back_to_pdd_home_page(self, max_back_times=2):
  1250. """
  1251. 尝试通过返回键回到拼多多主页面。
  1252. 按你的要求最多执行两次返回。
  1253. """
  1254. if not self.is_pdd_package_foreground():
  1255. return False
  1256. for _ in range(max_back_times):
  1257. if self.is_pdd_home_page():
  1258. break
  1259. self.d.press('back')
  1260. time.sleep(self.get_sleep_time())
  1261. return self.is_pdd_home_page()
  1262. def ensure_home_before_task_end(self, max_rounds=6):
  1263. """
  1264. 任务结束前做收尾:持续回退直到回到拼多多主页面。
  1265. 每轮最多回退两次,总轮数可配置,避免无限循环。
  1266. """
  1267. try:
  1268. if not self.is_pdd_package_foreground():
  1269. logging.info("ensure_home_before_task_end: 拼多多不在前台,先拉起APP")
  1270. self.start_app()
  1271. time.sleep(self.get_sleep_time())
  1272. #有bug,回到拼多多主页后不会继续执行
  1273. for round_idx in range(max_rounds):
  1274. if self.back_to_pdd_home_page(max_back_times=2):
  1275. logging.info(
  1276. f"ensure_home_before_task_end: 已回到拼多多主页面(轮次 {round_idx + 1}/{max_rounds})"
  1277. )
  1278. return True
  1279. logging.info(
  1280. f"ensure_home_before_task_end: 第 {round_idx + 1}/{max_rounds} 轮未到主页面,继续回退"
  1281. )
  1282. home_ready = self.is_pdd_home_page()
  1283. logging.info(f"ensure_home_before_task_end: 收尾结束,主页面状态={home_ready}")
  1284. return home_ready
  1285. except Exception as e:
  1286. logging.info(f"ensure_home_before_task_end: 执行异常: {e}")
  1287. return False
  1288. def focus_search_box(self, max_attempts=6):
  1289. """把搜索框点出来,为 enter_target_page 提供稳定起点。"""
  1290. search_entry_candidates = [
  1291. '//*[@resource-id="android:id/content"]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]'
  1292. ]
  1293. for attempt in range(max_attempts):
  1294. if self.d(className='android.widget.EditText').wait(timeout=1):
  1295. return True
  1296. clicked = False
  1297. for entry_xpath in search_entry_candidates:
  1298. if self.d.xpath(entry_xpath).exists:
  1299. self.d.xpath(entry_xpath).click()
  1300. clicked = True
  1301. time.sleep(self.get_sleep_time())
  1302. if self.d(className='android.widget.EditText').wait(timeout=1):
  1303. return True
  1304. if not clicked:
  1305. # 兜底点顶部搜索区域,兼容节点层级变化。
  1306. try:
  1307. screen_width = self.d.info.get('displayWidth', 1080)
  1308. screen_height = self.d.info.get('displayHeight', 2400)
  1309. self.d.click(screen_width // 2, int(screen_height * 0.08))
  1310. time.sleep(self.get_sleep_time())
  1311. if self.d(className='android.widget.EditText').wait(timeout=1):
  1312. return True
  1313. except Exception as click_error:
  1314. logging.info(f"focus_search_box: 顶部点击失败: {click_error}")
  1315. if not self.is_pdd_package_foreground():
  1316. logging.info("focus_search_box: 检测到拼多多不在前台,重新拉起APP")
  1317. self.start_app()
  1318. time.sleep(self.get_sleep_time())
  1319. logging.info(f"focus_search_box: 第 {attempt + 1}/{max_attempts} 次未定位到搜索框")
  1320. return False
  1321. def focus_search_box_after_restart(self, max_attempts=6):
  1322. """兼容旧调用,统一复用 focus_search_box。"""
  1323. return self.focus_search_box(max_attempts=max_attempts)
  1324. def prepare_entry_before_enter_target(self, force_restart=False):
  1325. """
  1326. 统一入口准备:
  1327. 1) 按需重启;
  1328. 2) 回退最多两次到主页面;
  1329. 3) 点击出搜索框;
  1330. 4) 后续交给 enter_target_page 执行输入和搜索。
  1331. """
  1332. if force_restart:
  1333. self.restart_app()
  1334. time.sleep(self.get_sleep_time())
  1335. elif not self.is_pdd_package_foreground():
  1336. logging.info("prepare_entry: 当前拼多多不在前台,改为先重启")
  1337. self.restart_app()
  1338. time.sleep(self.get_sleep_time())
  1339. home_ready = self.back_to_pdd_home_page(max_back_times=2)
  1340. logging.info(f"prepare_entry: 回到主页面结果={home_ready}")
  1341. search_ready = self.focus_search_box(max_attempts=6)
  1342. logging.info(f"prepare_entry: 搜索框定位结果={search_ready}")
  1343. return search_ready
  1344. def is_pdd_foreground(self):
  1345. """仅当"前台包名是拼多多 + 页面可见"时返回 True。"""
  1346. try:
  1347. current_app = self.d.app_current() or {}
  1348. current_package = current_app.get("package", "")
  1349. current_activity = current_app.get("activity", "")
  1350. device_info = self.d.info or {}
  1351. screen_on = bool(device_info.get("screenOn", True))
  1352. print(
  1353. f"foreground check -> package={current_package}, "
  1354. f"activity={current_activity}, screen_on={screen_on}"
  1355. )
  1356. if not screen_on:
  1357. return False
  1358. if current_package != self.package_name:
  1359. return False
  1360. # 仅包名命中仍不够:要求当前页面能看到拼多多关键锚点,避免"后台残留包名"误判。
  1361. visible_anchor_xpaths = [
  1362. '//*[contains(@text, "搜索")]',
  1363. '//*[@text="首页"]',
  1364. '//*[@text="多多视频"]',
  1365. '//*[@text="聊天"]',
  1366. '//*[@text="我的"]',
  1367. '//*[@text="个人中心"]',
  1368. '//*[@text="进店"]',
  1369. '//*[starts-with(@text, "商品参数")]',
  1370. ]
  1371. for anchor_xpath in visible_anchor_xpaths:
  1372. if self.d.xpath(anchor_xpath).exists:
  1373. return True
  1374. # 商品详情页有时锚点不稳定,放一个输入框兜底判断。
  1375. if self.d(className='android.widget.EditText').exists:
  1376. return True
  1377. print("package 命中拼多多,但页面锚点不可见,按后台处理并触发重启")
  1378. return False
  1379. except Exception as e:
  1380. print(f"failed to read foreground package/page state: {e}")
  1381. return False
  1382. def prepare_search_in_current_app(self):
  1383. """Reuse current PDD page: swipe first, then clear and search without app restart."""
  1384. print("pdd is in foreground, reuse app without restart")
  1385. # Strong swipe-up first, as requested.
  1386. for _ in range(2):
  1387. self.d.swipe_ext("up", scale=0.45)
  1388. time.sleep(0.8)
  1389. search_entry_candidates = [
  1390. '//*[contains(@text, "\u641c\u7d22")]',
  1391. '//*[contains(@content-desc, "\u641c\u7d22")]',
  1392. '//*[@resource-id="android:id/content"]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]'
  1393. '/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]'
  1394. '/android.widget.LinearLayout[1]',
  1395. ]
  1396. # Try to get search input directly; if not found, click possible search entries.
  1397. if not self.d(className='android.widget.EditText').wait(timeout=2):
  1398. for entry_xpath in search_entry_candidates:
  1399. if self.d.xpath(entry_xpath).exists:
  1400. self.d.xpath(entry_xpath).click()
  1401. time.sleep(self.get_sleep_time())
  1402. if self.d(className='android.widget.EditText').wait(timeout=2):
  1403. break
  1404. # Some list pages need one back press before search input appears.
  1405. if not self.d(className='android.widget.EditText').wait(timeout=2):
  1406. self.d.press("back")
  1407. time.sleep(self.get_sleep_time())
  1408. # Last fallback: use existing enter_target_page flow.
  1409. if not self.d(className='android.widget.EditText').wait(timeout=2):
  1410. print("search input not found after swipe, fallback to enter_target_page")
  1411. self.enter_target_page()
  1412. return
  1413. self.d(className='android.widget.EditText').click()
  1414. time.sleep(self.get_sleep_time())
  1415. clear_xpath_candidates = [
  1416. '//*[@text="\u6e05\u9664"]',
  1417. '//*[@text="\u6e05\u7a7a"]',
  1418. '//*[@content-desc="\u6e05\u9664"]',
  1419. '//*[@content-desc="\u6e05\u7a7a"]',
  1420. ]
  1421. for clear_xpath in clear_xpath_candidates:
  1422. if self.d.xpath(clear_xpath).exists:
  1423. self.d.xpath(clear_xpath).click()
  1424. time.sleep(0.5)
  1425. print("clicked clear button")
  1426. break
  1427. self.d.send_keys(self.search_key, clear=True)
  1428. time.sleep(self.get_sleep_time())
  1429. if self.d.xpath('//*[@text="\u641c\u7d22"]').exists:
  1430. self.d.xpath('//*[@text="\u641c\u7d22"]').click()
  1431. else:
  1432. self.d.press("enter")
  1433. time.sleep(self.get_sleep_time())
  1434. @staticmethod
  1435. def get_sleep_time():
  1436. # 功能:生成短随机等待时间,减少固定节奏操作带来的页面未加载或风控风险。
  1437. return random.uniform(0.5, 1.0)
  1438. # return random.randint(5, 8)
  1439. def get_screen_size(self):
  1440. """返回 (width, height) 屏幕尺寸,首次调用后缓存,兼容不同分辨率设备"""
  1441. if not hasattr(self, '_cached_screen_w'):
  1442. info = self.d.info
  1443. self._cached_screen_w = info.get('displayWidth', 720)
  1444. self._cached_screen_h = info.get('displayHeight', 1640)
  1445. return self._cached_screen_w, self._cached_screen_h
  1446. @staticmethod
  1447. def get_current_date():
  1448. # 功能:返回当前采集日期,作为去重和落库字段使用。
  1449. return datetime.datetime.now().strftime('%Y/%m/%d')
  1450. @staticmethod
  1451. def _normalize_rule_list(value):
  1452. # 功能:把单值或集合统一归一成非空字符串列表,供过滤逻辑直接复用。
  1453. if value is None:
  1454. return []
  1455. if isinstance(value, (list, tuple, set)):
  1456. raw_values = value
  1457. else:
  1458. raw_values = [value]
  1459. result = []
  1460. for item in raw_values:
  1461. item_str = str(item).strip()
  1462. if item_str:
  1463. result.append(item_str)
  1464. return result
  1465. @staticmethod
  1466. def _normalize_match_text(value):
  1467. # 功能:把待匹配文本做去空白和小写归一,减少页面文案格式差异带来的误判。
  1468. return re.sub(r'\s+', '', str(value or '')).lower()
  1469. @staticmethod
  1470. def _normalize_region_name(name, level):
  1471. text = re.sub(r"\s+", "", str(name or ""))
  1472. text = text.replace(" ", "")
  1473. if not text:
  1474. return ""
  1475. if level == "province":
  1476. province_alias = {
  1477. "内蒙古自治区": "内蒙古",
  1478. "广西壮族自治区": "广西",
  1479. "宁夏回族自治区": "宁夏",
  1480. "新疆维吾尔自治区": "新疆",
  1481. "西藏自治区": "西藏",
  1482. "香港特别行政区": "香港",
  1483. "澳门特别行政区": "澳门",
  1484. }
  1485. if text in province_alias:
  1486. return province_alias[text]
  1487. for suffix in ("特别行政区", "维吾尔自治区", "回族自治区", "壮族自治区", "自治区", "省", "市"):
  1488. if text.endswith(suffix) and len(text) > len(suffix):
  1489. return text[:-len(suffix)]
  1490. return text
  1491. city_alias = {
  1492. "北京市": "北京",
  1493. "天津市": "天津",
  1494. "上海市": "上海",
  1495. "重庆市": "重庆",
  1496. }
  1497. if text in city_alias:
  1498. return city_alias[text]
  1499. for suffix in ("自治州", "地区", "盟", "州", "市"):
  1500. if text.endswith(suffix) and len(text) > len(suffix):
  1501. return text[:-len(suffix)]
  1502. return text
  1503. def _load_city_lookup(self):
  1504. if self._city_lookup_cache is not None:
  1505. return self._city_lookup_cache
  1506. base_dir = os.path.dirname(os.path.abspath(__file__))
  1507. candidate_paths = [
  1508. os.path.join(base_dir, "city.json"),
  1509. os.path.join(base_dir, "process_shop", "city.json"),
  1510. ]
  1511. city_data = []
  1512. loaded_path = ""
  1513. for path in candidate_paths:
  1514. if not os.path.exists(path):
  1515. continue
  1516. try:
  1517. with open(path, "r", encoding="utf-8") as f:
  1518. candidate_data = json.load(f)
  1519. if isinstance(candidate_data, list):
  1520. city_data = candidate_data
  1521. loaded_path = path
  1522. break
  1523. except Exception as exc:
  1524. logging.warning(f"加载 city.json 失败: {path}, error={exc}")
  1525. province_to_id = {}
  1526. province_city_to_id = {}
  1527. global_city_matches = {}
  1528. for province in city_data:
  1529. province_norm = self._normalize_region_name(province.get("name", ""), "province")
  1530. province_id = parse_optional_int(province.get("id"), 0) or 0
  1531. if province_norm and province_id and province_norm not in province_to_id:
  1532. province_to_id[province_norm] = province_id
  1533. city_map = {}
  1534. for city in province.get("sons", []) or []:
  1535. city_norm = self._normalize_region_name(city.get("name", ""), "city")
  1536. city_id = parse_optional_int(city.get("id"), 0) or 0
  1537. if city_norm and city_id and city_norm not in city_map:
  1538. city_map[city_norm] = city_id
  1539. if city_norm and city_id and province_id:
  1540. global_city_matches.setdefault(city_norm, []).append((province_id, city_id, province_norm))
  1541. if province_norm and province_norm not in province_city_to_id:
  1542. province_city_to_id[province_norm] = city_map
  1543. if loaded_path:
  1544. logging.info(f"已加载 city.json: {loaded_path}")
  1545. else:
  1546. logging.warning("未找到可用 city.json,省市ID将回填为 0")
  1547. self._city_lookup_path = loaded_path
  1548. self._city_lookup_cache = {
  1549. "province_to_id": province_to_id,
  1550. "province_city_to_id": province_city_to_id,
  1551. "global_city_matches": global_city_matches,
  1552. }
  1553. return self._city_lookup_cache
  1554. def _resolve_region_ids(self, province_name, city_name):
  1555. lookup = self._load_city_lookup()
  1556. province_to_id = lookup["province_to_id"]
  1557. province_city_to_id = lookup["province_city_to_id"]
  1558. global_city_matches = lookup["global_city_matches"]
  1559. province_norm = self._normalize_region_name(province_name, "province")
  1560. city_norm = self._normalize_region_name(city_name, "city")
  1561. province_id = 0
  1562. city_id = 0
  1563. if province_norm:
  1564. province_id = province_to_id.get(province_norm, 0)
  1565. if not province_id:
  1566. for key, value in province_to_id.items():
  1567. if province_norm in key or key in province_norm:
  1568. province_id = value
  1569. province_norm = key
  1570. break
  1571. if province_id and city_norm:
  1572. city_map = province_city_to_id.get(province_norm, {})
  1573. city_id = city_map.get(city_norm, 0)
  1574. if not city_id:
  1575. for key, value in city_map.items():
  1576. if city_norm in key or key in city_norm:
  1577. city_id = value
  1578. break
  1579. if city_norm and (not province_id or not city_id):
  1580. matches = global_city_matches.get(city_norm, [])
  1581. if len(matches) == 1:
  1582. matched_province_id, matched_city_id, _ = matches[0]
  1583. province_id = province_id or matched_province_id
  1584. city_id = city_id or matched_city_id
  1585. elif province_id and not city_id:
  1586. for matched_province_id, matched_city_id, _ in matches:
  1587. if matched_province_id == province_id:
  1588. city_id = matched_city_id
  1589. break
  1590. return province_id or 0, city_id or 0
  1591. def _match_any_keyword(self, text, keywords):
  1592. # 功能:判断目标文本是否命中任一过滤词;过滤词为空时直接放行。
  1593. keyword_list = self._normalize_rule_list(keywords)
  1594. if not keyword_list:
  1595. # 没有配置过滤词时默认放行,让调用方只在需要时开启细筛。
  1596. return True
  1597. normalized_text = self._normalize_match_text(text)
  1598. return any(self._normalize_match_text(keyword) in normalized_text for keyword in keyword_list)
  1599. def _get_brand_match_keywords(self):
  1600. brand_keywords = self._normalize_rule_list(self.brand)
  1601. for brand in list(brand_keywords):
  1602. brand_keywords.extend(self._normalize_rule_list(BRAND_ALIAS_MAP.get(brand, [])))
  1603. return list(dict.fromkeys(brand_keywords))
  1604. def is_link_spec_useful(self, product_title, specifications=''):
  1605. # 功能:判断标题或说明书规格里是否包含目标品规。
  1606. if not self.spec_list:
  1607. return True
  1608. title_text = self._normalize_match_text(product_title)
  1609. spec_text = self._normalize_match_text(specifications)
  1610. for spec in self.spec_list:
  1611. normalized_spec = self._normalize_match_text(spec)
  1612. if normalized_spec in title_text or normalized_spec in spec_text:
  1613. return True
  1614. return False
  1615. def is_link_useful(self, product_title, specifications=''):
  1616. # 功能:统一做标题、品牌、规格三层过滤,尽量在早期就排除无关商品。
  1617. if not self._match_any_keyword(product_title, self.title_key):
  1618. print(f"当前商品名称:{product_title} 不包含{self.title_key}关键字")
  1619. return False
  1620. brand_keywords = self._get_brand_match_keywords()
  1621. if not self._match_any_keyword(product_title, brand_keywords):
  1622. print(f"当前商品名称:{product_title} 不包含{brand_keywords}品牌")
  1623. return False
  1624. if not self.is_link_spec_useful(product_title, specifications):
  1625. print(f"当前商品名称:{product_title} 不包含{self.spec_list}品规")
  1626. return False
  1627. return True
  1628. def remove_watermark(self, img_path):
  1629. # 功能:弱化截图中的水印或遮罩,提升后续 OCR 识别成功率。
  1630. """
  1631. 图片去水印(将水印部分变成白色背景)并将数据转化为二进制数据
  1632. :param img_path: 图片路径
  1633. :return: 二进制图片数据
  1634. """
  1635. img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), -1)
  1636. endswith = os.path.splitext(img_path)[1]
  1637. new = np.clip(1.4057577998008846 * img - 38.33089999653017, 0, 255).astype(np.uint8)
  1638. _, img_binary = cv2.imencode(endswith, new)
  1639. return img_binary
  1640. def get_license_info(self):
  1641. img_path = f"./shop_info_screenshot.png" # 截图地址
  1642. has_jindian = self.d.xpath('//*[@text="进店"]').exists
  1643. if has_jindian:
  1644. # 旧版:滚动直到"进店"接近顶部
  1645. for i in range(15):
  1646. if not self.d.xpath('//*[@text="进店"]').exists:
  1647. break
  1648. shop_bounds = self.d.xpath('//*[@text="进店"]').info['bounds']
  1649. element_top = shop_bounds['top']
  1650. print(f"进店到顶部的距离:{element_top}")
  1651. _, screen_h = self.get_screen_size()
  1652. if element_top <= int(screen_h * 0.30):
  1653. self.loggerPdd.info(f"🔍 第{i + 1}次上滑,「进店」上滑到最顶部")
  1654. break
  1655. self.d.swipe_ext("up", scale=0.2)
  1656. time.sleep(self.get_sleep_time())
  1657. else:
  1658. # 新版:点击底部"店铺"tab进入店铺页
  1659. self.loggerPdd.info('无进店按钮,通过底部店铺tab进入店铺页')
  1660. shop_tab = self.d.xpath('//*[@content-desc="店铺"]')
  1661. if not shop_tab.exists:
  1662. shop_tab = self.d.xpath('//*[@text="店铺"]')
  1663. if shop_tab.exists:
  1664. shop_tab.click()
  1665. time.sleep(2)
  1666. license_info = {}
  1667. # 新版 + 旧版:搜索资质证照图标(兼容 support.v7 和 androidx)
  1668. shop_license_xpaths = [
  1669. '(//android.support.v7.widget.RecyclerView[@resource-id="com.xunmeng.pinduoduo:id/pdd"]/android.widget.FrameLayout/android.view.ViewGroup/android.widget.ImageView[@resource-id="com.xunmeng.pinduoduo:id/pdd"])[2]',
  1670. '(//androidx.recyclerview.widget.RecyclerView[@resource-id="com.xunmeng.pinduoduo:id/pdd"]/android.widget.FrameLayout/android.view.ViewGroup/android.widget.ImageView[@resource-id="com.xunmeng.pinduoduo:id/pdd"])[2]',
  1671. ]
  1672. found_license = False
  1673. for xp in shop_license_xpaths:
  1674. if self.d.xpath(xp).exists:
  1675. print(f"存在资质图标: {xp[:60]}...")
  1676. self.d.xpath(xp).click()
  1677. found_license = True
  1678. break
  1679. if not found_license:
  1680. # 兜底:搜索 contentDescription 含"资质"或"证照"的 ImageView
  1681. for n in self.d.xpath('//android.widget.ImageView').all():
  1682. desc = (n.info.get('contentDescription') or '').strip()
  1683. if '资质' in desc or '证照' in desc:
  1684. n.click()
  1685. found_license = True
  1686. break
  1687. if found_license:
  1688. print(f"点击资质图标")
  1689. time.sleep(3)
  1690. self.d.screenshot(img_path)
  1691. self.loggerPdd.info(f"截图资质成功:{img_path}")
  1692. ocr_res = self.get_baidu_ocr_jgh_res(img_path)
  1693. if ocr_res:
  1694. for key in ocr_res:
  1695. if '企业名称' in key:
  1696. license_info['business_license_company'] = ocr_res[key]
  1697. if '经营地址' in key:
  1698. license_info['business_license_address'] = ocr_res[key]
  1699. if '注册地址' in key:
  1700. license_info['business_license_address'] = ocr_res[key]
  1701. if '信用代码' in key:
  1702. license_info['qualification_number'] = ocr_res[key]
  1703. if license_info.get('business_license_address'):
  1704. license_info['province'], license_info['city'] = self.infer_region_from_address(license_info['business_license_address'])
  1705. # 从资质页返回
  1706. if self.d.xpath('//*[@content-desc="返回"]').exists:
  1707. self.d.xpath('//*[@content-desc="返回"]').click()
  1708. elif not has_jindian:
  1709. # 新版:从店铺页返回详情页
  1710. self.d.press('back')
  1711. else:
  1712. print(f"不存在shop资质")
  1713. # 新版:从店铺页返回
  1714. if not has_jindian and not found_license:
  1715. self.d.press('back')
  1716. time.sleep(self.get_sleep_time())
  1717. return license_info
  1718. @staticmethod
  1719. def _norm_region_name(name):
  1720. if name is None:
  1721. return ""
  1722. text = str(name).strip()
  1723. if not text:
  1724. return ""
  1725. return re.sub(r'(省|市|自治区|特别行政区)$', '', text)
  1726. def build_address_region_index(self, file_path):
  1727. pairs = []
  1728. try:
  1729. with open(file_path, 'r', encoding='utf-8') as f:
  1730. data = json.load(f)
  1731. for province in data:
  1732. p_name = str(province.get("name") or "").strip()
  1733. if not p_name:
  1734. continue
  1735. p_candidates = {p_name, self._norm_region_name(p_name)}
  1736. cities = province.get("sons") or []
  1737. if not cities:
  1738. pairs.append({
  1739. "province": p_name,
  1740. "city": "",
  1741. "province_candidates": p_candidates,
  1742. "city_candidates": set()
  1743. })
  1744. continue
  1745. for city in cities:
  1746. c_name = str(city.get("name") or "").strip()
  1747. c_candidates = {c_name, self._norm_region_name(c_name)} if c_name else set()
  1748. pairs.append({
  1749. "province": p_name,
  1750. "city": c_name,
  1751. "province_candidates": p_candidates,
  1752. "city_candidates": c_candidates
  1753. })
  1754. except Exception as e:
  1755. print(f"构建地址省市索引失败: {e}")
  1756. return pairs
  1757. def infer_region_from_address(self, address):
  1758. text = str(address or "").strip()
  1759. if not text:
  1760. return "", ""
  1761. for item in self.address_region_index:
  1762. if any(k and k in text for k in item["province_candidates"]):
  1763. city = item["city"]
  1764. if city and any(k and k in text for k in item["city_candidates"]):
  1765. return item["province"], city
  1766. for item in self.address_region_index:
  1767. if any(k and k in text for k in item["province_candidates"]):
  1768. return item["province"], item["city"]
  1769. return "", ""
  1770. def get_shop_name(self):
  1771. # 功能:优先从当前详情页直接提取店铺名,失败时再进入店铺页兜底提取。
  1772. """
  1773. 获取店铺名
  1774. 兼容多版本:进店锚点 → 文案搜索 → 底部店铺tab → 滚回顶部重试
  1775. :return:
  1776. """
  1777. try:
  1778. shop_keywords = ['大药房', '旗舰店', '专卖店', '药房', '药店', '官方店', '专营店', '健康']
  1779. xpath_v1 = '//*[@text="进店"]/preceding-sibling::android.widget.LinearLayout/android.widget.TextView'
  1780. xpath_v2 = '//*[@text="进店"]/preceding-sibling::android.view.ViewGroup/android.widget.LinearLayout/android.widget.TextView'
  1781. def _try_direct():
  1782. """尝试直接从详情页读取店铺名"""
  1783. if self.d.xpath(xpath_v1).exists:
  1784. return self.d.xpath(xpath_v1).text, 'v1进店锚点'
  1785. if self.d.xpath(xpath_v2).exists:
  1786. return self.d.xpath(xpath_v2).text, 'v2进店锚点'
  1787. for kw in shop_keywords:
  1788. for n in self.d.xpath(f'//android.widget.TextView[contains(@text, "{kw}")]').all():
  1789. txt = (n.info.get('text') or '').strip()
  1790. b = n.info.get('bounds', {})
  1791. if len(txt) < 25 and b.get('top', 0) > 300:
  1792. return txt, f'文案搜索({kw})'
  1793. return None, None
  1794. # 第一次尝试
  1795. shop_name, method = _try_direct()
  1796. if shop_name:
  1797. self.loggerPdd.info(f'获取到店铺名({method}): {shop_name}')
  1798. return shop_name
  1799. # 滚回顶部再试(截图等操作可能把页面滚走了)
  1800. self.loggerPdd.info('首轮未获取到店铺名,滚回顶部重试')
  1801. for _ in range(3):
  1802. self.d.swipe_ext("down", scale=0.5)
  1803. time.sleep(0.5)
  1804. shop_name, method = _try_direct()
  1805. if shop_name:
  1806. self.loggerPdd.info(f'获取到店铺名(滚回后-{method}): {shop_name}')
  1807. return shop_name
  1808. # 方式3:点击底部"店铺"tab进入店铺页
  1809. shop_tab = self.d.xpath('//*[@content-desc="店铺"]')
  1810. if not shop_tab.exists:
  1811. shop_tab = self.d.xpath('//*[@text="店铺"]')
  1812. if shop_tab.exists:
  1813. shop_tab.click()
  1814. time.sleep(2)
  1815. for kw in shop_keywords:
  1816. for n in self.d.xpath(f'//android.widget.TextView[contains(@text, "{kw}")]').all():
  1817. txt = (n.info.get('text') or '').strip()
  1818. b = n.info.get('bounds', {})
  1819. if len(txt) < 25 and b.get('top', 0) < 600:
  1820. self.loggerPdd.info(f'获取到店铺名(店铺页): {txt}')
  1821. self.swipe_back(1)
  1822. return txt
  1823. self.swipe_back(1)
  1824. self.loggerPdd.info('所有方式均未获取到店铺名')
  1825. return ''
  1826. except Exception as e:
  1827. print(f'获取店铺名出错:{e}')
  1828. self.loggerPdd.error(f'获取店铺名出错:{e}')
  1829. return None
  1830. def save_to_shop_database(self, data):
  1831. # 功能:把当前商品采集结果落库;只有 commit 成功后才计入采集数量。
  1832. print(f'保存店铺数据到店铺数据库:{data}')
  1833. shop = str(data.get('shop') or '').strip()
  1834. if not shop:
  1835. print("保存店铺数据失败:shop 为空")
  1836. return False
  1837. # 数据库部分字段为 NOT NULL,统一做非空兜底,避免写入 None 触发 1048。
  1838. contact_address = str(data.get('contact_address') or '').strip()
  1839. qualification_number = str(data.get('qualification_number') or '').strip()
  1840. business_license_company = str(data.get('business_license_company') or '').strip()
  1841. business_license_address = str(data.get('business_license_address') or '').strip()
  1842. shop_url = str(data.get('store_url') or '').strip()
  1843. scrape_date = str(data.get('scrape_date') or self.get_current_date()).strip()
  1844. platform = str(data.get('platform') or '3').strip()
  1845. province = str(data.get('province_name') or data.get('province') or '').strip()
  1846. city = str(data.get('city_name') or data.get('city') or '').strip()
  1847. create_time = data.get('create_time') or datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  1848. update_time = data.get('update_time') or datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  1849. max_retries = 5
  1850. # 数据库偶发抖动时允许短重试,但只有 commit 成功后才算真正采集到一条数据。
  1851. for attempt in range(max_retries):
  1852. conn = None
  1853. try:
  1854. conn = get_mysql()
  1855. with conn.cursor() as cur:
  1856. add_sql = """
  1857. INSERT INTO retrieve_scrape_shop_info (
  1858. shop, contact_address, qualification_number, business_license_company,
  1859. business_license_address, shop_url, scrape_date, platform,
  1860. province,city, create_time, update_time
  1861. ) VALUES (
  1862. %s, %s, %s, %s, %s,
  1863. %s, %s, %s, %s, %s,
  1864. %s, %s
  1865. )
  1866. """
  1867. cur.execute(add_sql, (
  1868. shop,
  1869. contact_address,
  1870. qualification_number,
  1871. business_license_company,
  1872. business_license_address,
  1873. shop_url,
  1874. scrape_date,
  1875. platform,
  1876. province,
  1877. city,
  1878. create_time,
  1879. update_time,
  1880. ))
  1881. conn.commit()
  1882. print(f"存入数据库成功")
  1883. return True
  1884. except Exception as e:
  1885. print(f'保存数据库异常 (尝试 {attempt + 1}/{max_retries}): {e}')
  1886. if conn:
  1887. conn.rollback()
  1888. conn.close()
  1889. if attempt == max_retries - 1:
  1890. print("达到最大重试次数,保存失败")
  1891. return False
  1892. time.sleep(2)
  1893. def save_to_database(self, data):
  1894. # 功能:把当前商品采集结果落库;只有 commit 成功后才计入采集数量。
  1895. print(f'保存数据到数据库:{data}')
  1896. max_retries = 5
  1897. # 数据库偶发抖动时允许短重试,但只有 commit 成功后才算真正采集到一条数据。
  1898. for attempt in range(max_retries):
  1899. conn = None
  1900. try:
  1901. conn = get_mysql()
  1902. with conn.cursor() as cur:
  1903. add_sql = """
  1904. INSERT INTO retrieve_scrape_data (
  1905. enterprise_id, platform_id, platform_item_id, province_id, city_id,
  1906. province_name, city_name, area_info, product_brand, product_name, product_specs, search_name,
  1907. collect_config_info, one_box_price, manufacture_date, expiry_date, manufacturer, approval_number,
  1908. is_sold_out, online_posting_count, continuous_listing_count, link_url,
  1909. store_name, store_url, shipment_province_id, shipment_province_name,
  1910. shipment_city_id, shipment_city_name, company_name, qualification_number,
  1911. scrape_date, min_price, number, sales, inventory, snapshot_url,collect_equipment_account_id,insert_time,update_time,collect_round,collect_region_id
  1912. ) VALUES (
  1913. %s, %s, %s, %s, %s,
  1914. %s, %s, %s, %s, %s, %s, %s,
  1915. %s, %s, %s, %s, %s, %s,
  1916. %s, %s, %s, %s,
  1917. %s, %s, %s, %s,
  1918. %s, %s, %s, %s,%s,%s,%s,
  1919. %s, %s, %s, %s, %s, %s, %s, %s
  1920. )
  1921. """
  1922. cur.execute(add_sql, (
  1923. data['enterprise_id'],
  1924. data['platform_id'],
  1925. data['platform_item_id'],
  1926. data['province_id'],
  1927. data['city_id'],
  1928. data['province_name'],
  1929. data['city_name'],
  1930. data['area_info'],
  1931. data['product_brand'],
  1932. data['product_name'],
  1933. data['product_specs'],
  1934. data['search_name'],
  1935. data['collect_config_info'],
  1936. data['one_box_price'],
  1937. data['manufacture_date'],
  1938. data['expiry_date'],
  1939. data['manufacturer'],
  1940. data['approval_number'],
  1941. data['is_sold_out'],
  1942. data['online_posting_count'],
  1943. data['continuous_listing_count'],
  1944. data['link_url'],
  1945. data['store_name'],
  1946. data['store_url'],
  1947. data['shipment_province_id'],
  1948. data['shipment_province_name'],
  1949. data['shipment_city_id'],
  1950. data['shipment_city_name'],
  1951. data['company_name'],
  1952. data['qualification_number'],
  1953. data['scrape_date'],
  1954. data['min_price'],
  1955. data['number'],
  1956. data['sales'],
  1957. data['inventory'],
  1958. data['snapshot_url'],
  1959. data.get('collect_equipment_account_id',0),
  1960. data['insert_time'],
  1961. data['update_time'],
  1962. data['collect_round'],
  1963. data['collect_region_id'],
  1964. ))
  1965. conn.commit()
  1966. self.max_counts += 1
  1967. print(f"存入数据库成功,当前已采集 {self.max_counts} 条")
  1968. return True
  1969. except Exception as e:
  1970. print(f'保存数据库异常 (尝试 {attempt + 1}/{max_retries}): {e}')
  1971. if conn:
  1972. conn.rollback()
  1973. conn.close()
  1974. if attempt == max_retries - 1:
  1975. print("达到最大重试次数,保存失败")
  1976. return False
  1977. time.sleep(2)
  1978. def click_target_product_by_search_key(self, fuzzy_match=False, timeout=10):
  1979. # 功能:在列表页重新定位当前搜索词对应的商品,常用于异常恢复后的重新对焦。
  1980. """
  1981. 动态匹配self.search_key对应的商品并点击
  1982. :param fuzzy_match: 是否模糊匹配(应对商品名带额外后缀/前缀的情况) 不模糊匹配
  1983. :param timeout: 等待元素出现的超时时间(秒)
  1984. :return: 点击是否成功(bool)
  1985. """
  1986. try:
  1987. # 1. 定义定位条件(动态使用self.search_key)
  1988. # 异常恢复后需要重新找到"当前任务真正想点的那一个商品",
  1989. # 这里支持精确和模糊两种定位策略。
  1990. if fuzzy_match:
  1991. # 模糊匹配:包含search_key即可(推荐,适配搜索结果商品名略有差异)
  1992. locator = self.d(textContains=self.search_key)
  1993. print(f"🔍 模糊匹配商品:包含「{self.search_key}」的元素")
  1994. else:
  1995. # 精确匹配:商品名与search_key完全一致
  1996. locator = self.d(text=self.search_key)
  1997. print(f"🔍 精确匹配商品:「{self.search_key}」")
  1998. # 2. 等待元素出现(核心:避免元素未加载就点击)
  1999. if locator.wait(timeout=timeout):
  2000. print(f"✅ 找到匹配的商品,准备点击")
  2001. # 执行点击(优先点击可点击的元素)
  2002. locator.click()
  2003. print(f"✅ 成功点击「{self.search_key}」对应的商品")
  2004. # 点击后等待页面加载
  2005. time.sleep(self.get_sleep_time())
  2006. return True
  2007. else:
  2008. print(f"❌ 滑动后仍未找到「{self.search_key}」对应的商品")
  2009. return False
  2010. except Exception as e:
  2011. print(f"❌ 点击「{self.search_key}」对应商品时异常:{e}")
  2012. return False
  2013. def swipe_down(self):
  2014. # 功能:执行带随机性的向下滑动,兼顾页面恢复、回找搜索框和设备适配。
  2015. """
  2016. 下滑(模拟真人操作,抗风控+设备适配+容错)
  2017. 核心:起点在屏幕上方,终点在屏幕下方(和上滑相反)
  2018. :return: None
  2019. """
  2020. try:
  2021. # 1. 获取屏幕尺寸(兼容不同设备,给默认值避免获取失败)
  2022. screen_width = self.d.info.get('displayWidth', 1080) # 默认1080px宽度
  2023. screen_height = self.d.info.get('displayHeight', 2400) # 默认2400px高度
  2024. # 2. 随机滑动时长(0.1~0.3秒,避免固定值被风控,且不设0秒)
  2025. duration_rate = random.uniform(0.1, 0.3)
  2026. # 3. 计算滑动坐标(用屏幕比例,适配所有设备)
  2027. start_x = screen_width // 2 # 水平居中(和上滑一致,符合真人操作习惯)
  2028. start_y = screen_height * 0.2 # 起点:屏幕20%高度(上方偏下)
  2029. end_y = screen_height * 0.8 # 终点:屏幕80%高度(下方偏上)
  2030. # 强制确保起点y < 终点y(必为向下滑,避免逻辑错误)
  2031. start_y, end_y = min(start_y, end_y - 10), max(end_y, start_y + 10)
  2032. # 4. 核心向下滑动操作
  2033. self.d.swipe(start_x, start_y, start_x, end_y, duration=duration_rate)
  2034. # 滑动后全局等待(确保页面加载,避免元素定位失败)
  2035. time.sleep(self.get_sleep_time())
  2036. except Exception as e:
  2037. # 异常捕获:避免设备断开/滑动失败导致程序崩溃
  2038. print(f"向下滑动失败:{e}")
  2039. # 兜底方案:用屏幕比例坐标重试
  2040. sw, sh = self.get_screen_size()
  2041. self.d.swipe(sw // 2, int(sh * 0.2), sw // 2, int(sh * 0.8), duration=0.2)
  2042. time.sleep(self.get_sleep_time())
  2043. def swipe_up(self):
  2044. # 功能:执行向上滑动,用于翻页或继续向下浏览详情。
  2045. """
  2046. 上滑
  2047. :return:
  2048. """
  2049. screen_width = self.d.info['displayWidth']
  2050. screen_height = self.d.info['displayHeight']
  2051. duration_rate = random.uniform(0, 0.3)
  2052. self.d.swipe(screen_width // 2, screen_height - 100, screen_width // 2, 100, duration=duration_rate)
  2053. no = random.uniform(0, 1)
  2054. if no > 0.85:
  2055. # 有的时候卡着 再稍微往上滑一点点
  2056. self.d.swipe_ext("up", 0.1)
  2057. time.sleep(self.get_sleep_time())
  2058. def swipe_back(self, no):
  2059. # 功能:按指定次数执行返回,但只有当前不在列表页时才真正后退。
  2060. """
  2061. 返回
  2062. :param no: 回退次数
  2063. :return:
  2064. """
  2065. for idx in range(no):
  2066. if self.distinct_target(): # 已经在列表页
  2067. print(f'已在列表页,停止返回')
  2068. return True
  2069. self.d.press('back')
  2070. time.sleep(self.get_sleep_time())
  2071. def drug_price(self):
  2072. # 功能:直接从详情页读取价格,作为规格弹窗取价失败时的兜底方案。
  2073. """
  2074. 获取药品价格
  2075. :return:
  2076. """
  2077. try:
  2078. xpath = '//*[@text="¥"]/following-sibling::android.widget.TextView[1]'
  2079. price_str = self.d.xpath(xpath).text
  2080. price = float(re.search(r'[\d\.]+', price_str).group())
  2081. print(f'获取到价格:{price}')
  2082. return float(price)
  2083. except Exception as e:
  2084. print(f'提取价格出错-->{e}')
  2085. return None
  2086. def drug_price_ex(self):
  2087. # 功能:优先从规格选择弹窗里同时提取价格和"已选规格"文本。
  2088. price_str = '' # 价格初始化
  2089. ext = '' # 初始化已选择的信息
  2090. price = ''
  2091. # 阶段 1:先尝试打开规格/品规弹窗,因为后续价格和规格文本都依赖这个弹窗内容。
  2092. # 这是点击进入品规的按钮
  2093. button_xpath_1 = '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[2]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.view.ViewGroup[last()]'
  2094. button_xpath_2 = '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[2]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[1]/android.view.ViewGroup[last()]'
  2095. button_xpath_3 = '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.LinearLayout/android.widget.LinearLayout/android.widget.LinearLayout[2]/android.widget.LinearLayout/android.view.ViewGroup'
  2096. # 调试
  2097. # test_button = self.d.xpath(button_xpath_1).exists
  2098. # print(test_button)
  2099. # test_button_2 = self.d.xpath(button_xpath_2).exists
  2100. # print(test_button_2)
  2101. # time.sleep(1000)
  2102. # if self.d.xpath('//*[@text="发起拼单"]').exists:
  2103. # self.d.xpath('//*[@text="发起拼单"]').click()
  2104. # elif self.d.xpath('//*[@text="去复诊开药"]').exists:
  2105. # self.d.xpath('//*[@text="去复诊开药"]').click()
  2106. if self.d.xpath(button_xpath_1).exists:
  2107. self.d.xpath(button_xpath_1).click()
  2108. elif self.d.xpath(button_xpath_2).exists:
  2109. self.d.xpath(button_xpath_2).click()
  2110. elif self.d.xpath(button_xpath_3).exists:
  2111. self.d.xpath(button_xpath_3).click()
  2112. else:
  2113. print("button1 and button_2 and button_3 all not exist")
  2114. return price, ext
  2115. # 阶段 2:根据不同弹窗布局选择对应的 XPath 解析策略。
  2116. select_xpath_1 = '//*[@resource-id="android:id/content"]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.TextView[last()]'
  2117. select_xpath_2 = '//*[@resource-id="android:id/content"]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.TextView[last()]'
  2118. select_xpath_3 = '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.view.ViewGroup[2]/android.widget.LinearLayout[1]/android.view.ViewGroup[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.view.ViewGroup[1]/android.widget.TextView[last()]'
  2119. select_xpath_3_2 = '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.view.ViewGroup[2]/android.widget.LinearLayout[1]/android.view.ViewGroup[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.view.ViewGroup[1]/android.widget.TextView[last()-1]'
  2120. price_xpath_1 = '//*[@resource-id="android:id/content"]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.TextView[1]'
  2121. price_xpath_2 = '//*[@resource-id="android:id/content"]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.TextView[1]'
  2122. price_xpath_3 = '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.view.ViewGroup[2]/android.widget.LinearLayout[1]/android.view.ViewGroup[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.view.ViewGroup[1]//android.widget.TextView[1]'
  2123. # 新版规格选项路径(androidx RecyclerView,兼容新版拼多多弹窗)
  2124. scroll_xpath_2 = '//*[@resource-id="android:id/content"]//android.widget.ScrollView[1]/android.widget.LinearLayout/androidx.recyclerview.widget.RecyclerView/android.widget.LinearLayout/android.view.ViewGroup[1]'
  2125. recycler_view_xpath_2 = '//*[@resource-id="android:id/content"]//androidx.recyclerview.widget.RecyclerView[1]/android.widget.LinearLayout/android.view.ViewGroup[1]'
  2126. if self.d.xpath(select_xpath_1).exists:
  2127. text1 = self.d.xpath(select_xpath_1).text
  2128. print(f"select_xpath_1--text1={text1}")
  2129. # 这里先判断是否已经有默认规格,是为了减少额外点击;
  2130. # 如果已经存在"已选"文本,后续可以直接读取价格和规格。
  2131. if '已选' in text1:
  2132. if self.d.xpath(price_xpath_1).exists:
  2133. price_str = self.d.xpath(price_xpath_1).text
  2134. print(f"select_xpath_1--price_str-1={price_str}")
  2135. else:
  2136. print("select_xpath_1--price_xpath_1-1 not exist")
  2137. ext = text1
  2138. elif '请选择' in text1:
  2139. # 调用 click() 的目的是补齐一次规格选择动作,
  2140. # 调用后价格文本和"已选规格"文案才会稳定刷新出来。
  2141. # 需要再下面点击选择
  2142. scroll_xpath_1 = '//*[@resource-id="android:id/content"]//android.widget.ScrollView[1]/android.widget.LinearLayout[1]/android.support.v7.widget.RecyclerView[1]/android.widget.LinearLayout[last()]/android.view.ViewGroup[1]/android.view.ViewGroup[last()]'
  2143. scroll_xpath_2 = ''
  2144. if self.d.xpath(scroll_xpath_1).exists:
  2145. self.d.xpath(scroll_xpath_1).click()
  2146. time.sleep(2) # 延时2秒钟,选择了之后价格会刷新
  2147. if self.d.xpath(select_xpath_1).exists:
  2148. text2 = self.d.xpath(select_xpath_1).text
  2149. if '已选' in text2:
  2150. print(f"select_xpath_1--已选择2:text2={text2}")
  2151. if self.d.xpath(price_xpath_1).exists:
  2152. price_str = self.d.xpath(price_xpath_1).text
  2153. print(f"select_xpath_1--price_str-2={price_str}")
  2154. else:
  2155. print("select_xpath_1--price_xpath_1-2 not exist")
  2156. ext = text2
  2157. else:
  2158. print("select_xpath_1--scroll_xpath_1 not exist")
  2159. elif self.d.xpath(select_xpath_2).exists:
  2160. text1 = self.d.xpath(select_xpath_2).text
  2161. print(f"xpath2--text1={text1}")
  2162. if '已选' in text1:
  2163. ext = text1
  2164. if self.d.xpath(price_xpath_2).exists:
  2165. price_str = self.d.xpath(price_xpath_2).text
  2166. print(f"select_xpath_2--price_str-2={price_str}")
  2167. else:
  2168. print("select_xpath_2--price_xpath_2-1 not exist")
  2169. elif '请选择' in text1:
  2170. # 当前布局下如果不先选择一个规格,后续既拿不到准确价格,也无法计算盒数。
  2171. print('come in here')
  2172. # 需要再下面点击选择
  2173. scroll_xpath_1 = '//*[@resource-id="android:id/content"]//android.widget.ScrollView[1]/android.widget.LinearLayout[1]/android.support.v7.widget.RecyclerView[1]/android.widget.LinearLayout[last()]/android.view.ViewGroup[1]/android.view.ViewGroup[1]'
  2174. hit_scroll = False
  2175. if self.d.xpath(scroll_xpath_1).exists:
  2176. print("scroll_xpath_1 exists")
  2177. self.d.xpath(scroll_xpath_1).click()
  2178. hit_scroll = True
  2179. elif self.d.xpath(scroll_xpath_2).exists:
  2180. print("scroll_xpath_2 exists")
  2181. self.d.xpath(scroll_xpath_2).click()
  2182. hit_scroll = True
  2183. if hit_scroll:
  2184. time.sleep(2) # 延时2秒钟,选择了之后价格可能会刷新
  2185. if self.d.xpath(select_xpath_2).exists:
  2186. text2 = self.d.xpath(select_xpath_2).text
  2187. if '已选' in text2:
  2188. ext = text2
  2189. print(f"select_xpath_2--已选择2:text2={text2}")
  2190. if self.d.xpath(price_xpath_2).exists:
  2191. price_str = self.d.xpath(price_xpath_2).text
  2192. print(f"select_xpath_2--price_str-2={price_str}")
  2193. else:
  2194. print("select_xpath_2--price_xpath_2-2 not exist")
  2195. else:
  2196. print("scroll_xpath_1 and scroll_xpath_2 not exists")
  2197. else:
  2198. print("not exist 请选择 or 已选")
  2199. elif self.d.xpath(select_xpath_3).exists:
  2200. text1 = self.d.xpath(select_xpath_3).text
  2201. print(f"xpath3--text1-1={text1}")
  2202. if ('请选择' not in text1) and ('已选' not in text1):
  2203. text1 = self.d.xpath(select_xpath_3_2).text
  2204. print(f"xpath3--text1-2={text1}")
  2205. if '已选' in text1:
  2206. ext = text1
  2207. if self.d.xpath(price_xpath_3).exists:
  2208. price_str = self.d.xpath(price_xpath_3).text
  2209. print(f"select_xpath_3--price_str-3-3-1={price_str}")
  2210. else:
  2211. print("select_xpath_3--price_xpath_3-3-1 not exist")
  2212. elif '请选择' in text1:
  2213. # 这一支兼容另一类规格弹窗结构,核心目标仍然是先拿到"已选"文本。
  2214. print('come in here')
  2215. # 需要再下面点击选择
  2216. scroll_xpath_1 = '//*[@resource-id="android:id/content"]//android.widget.ScrollView[1]/android.widget.LinearLayout[1]/android.support.v7.widget.RecyclerView[1]/android.widget.LinearLayout[last()]/android.view.ViewGroup[1]/android.view.ViewGroup[1]'
  2217. recycler_view_xpath = '//*[@resource-id="android:id/content"]//android.support.v7.widget.RecyclerView[1]/android.widget.LinearLayout[1]/android.widget.LinearLayout[last()]/android.view.ViewGroup[1]/android.view.ViewGroup[1]'
  2218. hit_scroll = False
  2219. if self.d.xpath(scroll_xpath_1).exists:
  2220. print("scroll_xpath_1 exists")
  2221. self.d.xpath(scroll_xpath_1).click()
  2222. hit_scroll = True
  2223. elif self.d.xpath(recycler_view_xpath).exists:
  2224. self.d.xpath(recycler_view_xpath).click()
  2225. hit_scroll = True
  2226. elif self.d.xpath(scroll_xpath_2).exists:
  2227. print("scroll_xpath_2 exists")
  2228. self.d.xpath(scroll_xpath_2).click()
  2229. hit_scroll = True
  2230. elif self.d.xpath(recycler_view_xpath_2).exists:
  2231. print("recycler_view_xpath_2 exists")
  2232. self.d.xpath(recycler_view_xpath_2).click()
  2233. hit_scroll = True
  2234. if hit_scroll:
  2235. time.sleep(2) # 延时2秒钟,选择了之后价格可能会刷新
  2236. if self.d.xpath(select_xpath_3).exists:
  2237. text2 = self.d.xpath(select_xpath_3).text
  2238. if '已选' in text2:
  2239. ext = text2
  2240. print(f"select_xpath_3--已选择2:text2={text2}")
  2241. if self.d.xpath(price_xpath_3).exists:
  2242. price_str = self.d.xpath(price_xpath_3).text
  2243. print(f"select_xpath_3--price_str-3-2={price_str}")
  2244. else:
  2245. print("select_xpath_3--price_xpath_3-3-2 not exist")
  2246. else:
  2247. print("scroll_xpath_1, recycler_view_xpath, scroll_xpath_2, recycler_view_xpath_2 all not exists")
  2248. else:
  2249. print(f"xpath3--text1-不包含请选择和已选择")
  2250. else:
  2251. print("select_xpath_1 and select_xpath_2 and select_xpath_3 all not exist")
  2252. # 阶段 3:从界面文案中抽取纯价格值,供后续去重和单盒价格计算。
  2253. if price_str:
  2254. # price = float(re.search('[\d\.]+', price_str).group())
  2255. match = re.search(r'¥([\d\.]+)', price_str)
  2256. if match:
  2257. price = float(match.group(1))
  2258. else:
  2259. price = ''
  2260. # price = float(re.search(r'¥([\d\.]+)', price_str).group(1))
  2261. print(f'获取到价格:{price}')
  2262. print(f"ext={ext}")
  2263. # 调用 swipe_back() 的目的是把页面从规格弹窗恢复回商品详情页,
  2264. # 后续提取店铺名、链接和说明书都依赖当前仍停留在详情页。
  2265. self.swipe_back(1) #
  2266. return price, ext
  2267. def restart_uiautomator_services(self, device_id):
  2268. # 功能:重启设备上的 atx-agent/uiautomator 服务,恢复自动化控制能力。
  2269. """
  2270. 重启atx的uiautomator 服务
  2271. :param device_id:
  2272. :return:
  2273. """
  2274. stop_uiautomator_services = f'adb -s {device_id} shell /data/local/tmp/atx-agent server -d --stop'
  2275. start_uiautomator_services = f'adb -s {device_id} shell /data/local/tmp/atx-agent server -d'
  2276. subprocess.run(stop_uiautomator_services, capture_output=True, text=True, shell=True)
  2277. time.sleep(self.get_sleep_time())
  2278. subprocess.run(start_uiautomator_services, capture_output=True, text=True, shell=True)
  2279. time.sleep(self.get_sleep_time())
  2280. def connect_devices(self, device_id):
  2281. # 功能:建立 USB 设备连接,并把自动化服务重置到可用状态。
  2282. """
  2283. 连接设备
  2284. :return:
  2285. """
  2286. try:
  2287. self.d = u2.connect_usb(device_id)
  2288. # 设置隐形等待时间
  2289. # self.d.implicitly_wait(5)
  2290. # 连上设备后主动重启 atx-agent,减少长时间运行后的控件失效问题。
  2291. self.restart_uiautomator_services(device_id)
  2292. print(f'[{self.program_start_time}]连接到设备:{device_id}')
  2293. except Exception as e:
  2294. print(f'{device_id} 连接错误: {e}')
  2295. raise Exception(e)
  2296. # 验证码 WebView XPath — 所有验证码相关页面都有这个元素
  2297. CAPTCHA_WEBVIEW = '//android.webkit.WebView[@text="安全验证"]'
  2298. def check_and_solve_captcha(self):
  2299. """检测验证码 WebView 并调用 test_captcha.solve 解决,成功返回 True"""
  2300. if not self.d.xpath(self.CAPTCHA_WEBVIEW).exists:
  2301. return False
  2302. logging.info("检测到验证码页面(WebView 安全验证),开始解决...")
  2303. result = captcha_solve(self.d)
  2304. if result:
  2305. logging.info("验证码已解决,休息30分钟...")
  2306. time.sleep(1800)
  2307. return result
  2308. def get_baidu_ocr_res(self, img):
  2309. try:
  2310. # img地址
  2311. print(f'开始识别图片:{img}')
  2312. request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_license"
  2313. f = open(img, 'rb')
  2314. img = base64.b64encode(f.read())
  2315. params = {"image": img}
  2316. request_url = request_url + "?access_token=" + get_access_token()
  2317. headers = {'content-type': 'application/x-www-form-urlencoded'}
  2318. response = requests.post(request_url, data=params, headers=headers)
  2319. if response:
  2320. res = response.json()
  2321. new_dic = dict()
  2322. for ite in res['words_result'].keys():
  2323. new_dic[ite] = res['words_result'][ite]['words']
  2324. print('资质数据信息', new_dic)
  2325. return new_dic
  2326. else:
  2327. return None
  2328. except:
  2329. return None
  2330. def get_baidu_ocr_jgh_res(self, img):
  2331. try:
  2332. # img地址
  2333. print(f'开始识别图片:{img}')
  2334. request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/smart_struct"
  2335. f = open(img, 'rb')
  2336. img = base64.b64encode(f.read())
  2337. params = {"image": img}
  2338. request_url = request_url + "?access_token=" + get_access_token()
  2339. headers = {'content-type': 'application/x-www-form-urlencoded'}
  2340. response = requests.post(request_url, data=params, headers=headers)
  2341. if response:
  2342. res = response.json()
  2343. print(f"获取店铺资质信息ocr返回:{res}")
  2344. new_dic = dict()
  2345. data = res['words_result']['struct_info']['group']
  2346. for ite in data:
  2347. new_dic[ite['key'][0]['word']] = ite['value'][0]['word']
  2348. print(f'ocr资质数据信息:{new_dic}')
  2349. return new_dic
  2350. else:
  2351. return None
  2352. except:
  2353. return None
  2354. def get_ocr_res(self, img):
  2355. # 功能:对截图做去水印后调用百度 OCR,返回识别出的文字结果列表。
  2356. try:
  2357. image = self.remove_watermark(img)
  2358. res_image = self.client.basicGeneral(image)
  2359. data = res_image.get('words_result', '')
  2360. print(f'百度api返回结果:{data}')
  2361. return data
  2362. except:
  2363. return None
  2364. def get_title(self):
  2365. # 功能:从商品详情页提取当前标题,作为第一层匹配和落库名称来源。
  2366. try:
  2367. print('开始提取标题')
  2368. time.sleep(self.get_sleep_time())
  2369. title_xpath = '//*[@resource-id="com.xunmeng.pinduoduo:id/tv_title"]'
  2370. if self.d.xpath(title_xpath).exists:
  2371. title = self.d.xpath(title_xpath).info['contentDescription'].strip()
  2372. else:
  2373. # 标题没找到 → 检测是否是验证码页面
  2374. self.check_and_solve_captcha()
  2375. return None
  2376. # title = self.d.xpath('//*[@resource-id="com.xunmeng.pinduoduo:id/tv_title"]').info['contentDescription'].strip()
  2377. print(f'提取到标题:{title}')
  2378. return title
  2379. except Exception as e:
  2380. print(f'获取标题出错:{e}')
  2381. return None
  2382. # 从里面匹配出药品名和规格
  2383. # drugs_name
  2384. # specifications
  2385. # match = re.search(r'([^\d]+)([\d\D]+)', title)
  2386. # match = re.search(r'(\[[^\]]+\])(.+?)(\d+.*)', title)
  2387. # if match:
  2388. # drugs_name = match.group(1).strip() + match.group(2).strip()
  2389. # specifications = match.group(3).strip()
  2390. # print("药品名:", drugs_name)
  2391. # print("规格:", specifications)
  2392. # print('完整药名:', drugs_name + specifications)
  2393. # return drugs_name, specifications
  2394. # else:
  2395. # print("没有匹配到预期格式")
  2396. def enter_shop(self):
  2397. # 功能:进入店铺页,供后续读取店铺或资质信息时使用。
  2398. """
  2399. 进店,方便提取资质环境
  2400. :return:
  2401. """
  2402. # self.d.xpath('//*[@text="进店"]').click()
  2403. self.d.xpath('//*[@text="店铺"]').click()
  2404. time.sleep(self.get_sleep_time())
  2405. #店铺去重
  2406. def shop_is_exists(self, data):
  2407. # 功能:按店铺去重校验,避免同类数据重复入库。
  2408. # 1. 验证必要字段
  2409. # 先校验去重所需字段是否齐全,避免把不完整的数据带到 SQL 条件里。
  2410. required_keys = ['shop']
  2411. if not all(key in data for key in required_keys):
  2412. missing = [key for key in required_keys if key not in data]
  2413. print(f"缺少必要字段: {', '.join(missing)}")
  2414. return None
  2415. shop_value = data.get('shop')
  2416. if not shop_value or not str(shop_value).strip():
  2417. print("shop 字段为空,无法执行去重查询")
  2418. return False
  2419. conn = None
  2420. try:
  2421. conn = get_mysql()
  2422. with conn.cursor() as cur:
  2423. query_sql = """
  2424. SELECT * FROM {}
  2425. WHERE shop = %s
  2426. LIMIT 1
  2427. """.format(self.shop_table_name)
  2428. cur.execute(query_sql, (
  2429. data['shop']
  2430. ))
  2431. result = cur.fetchone()
  2432. return bool(result) # 如果存在返回True,否则False
  2433. except Exception as e:
  2434. print(f"MySQL 错误: {str(e)}")
  2435. finally:
  2436. if conn:
  2437. conn.close()
  2438. def get_province_city(self,data):
  2439. """
  2440. 从 retrieve_scrape_shop_info 表中查询已存在的 province 和 city,
  2441. 并赋值给 data['province_name'] 和 data['city_name']
  2442. """
  2443. print("获取店铺营业公司对应的省份和城市")
  2444. shop_name = data.get('shop')
  2445. if not shop_name:
  2446. print("shop 字段为空,无法执行查询")
  2447. return
  2448. conn = None
  2449. try:
  2450. conn = get_mysql()
  2451. with conn.cursor() as cur:
  2452. # 查询 shop_info_middle 表,获取 province 和 city
  2453. sql = "SELECT province, city, business_license_company FROM retrieve_scrape_shop_info WHERE shop = %s AND platform = 3 LIMIT 1"
  2454. cur.execute(sql, (shop_name,))
  2455. result = cur.fetchone()
  2456. if result:
  2457. province, city, company = result
  2458. data['province_name'] = province if province else ''
  2459. data['city_name'] = city if city else ''
  2460. data['company_name'] = company if company else ''
  2461. print(f"店铺 {shop_name} 对应的省份和城市为: {province}, {city}, 公司: {company}")
  2462. else:
  2463. print(f"未在 shop_info_middle 表中找到店铺:{shop_name}")
  2464. # 可根据业务需求设置默认值或保持原样
  2465. data['province_name'] = ''
  2466. data['city_name'] = ''
  2467. data['company_name'] = ''
  2468. except Exception as e:
  2469. print(f"查询省市信息失败: {str(e)}")
  2470. # 异常时也可设置默认空值,避免后续代码因缺少键而报错
  2471. data['province_name'] = ''
  2472. data['city_name'] = ''
  2473. finally:
  2474. if conn:
  2475. conn.close()
  2476. def data_is_exists(self, data):
  2477. # 功能:按价格、店铺、日期、平台,账户,轮次做去重校验,避免同类数据重复入库。
  2478. # 1. 验证必要字段
  2479. # 先校验去重所需字段是否齐全,避免把不完整的数据带到 SQL 条件里。
  2480. required_keys = ['min_price', 'shop', 'scrape_date', 'platform']
  2481. if not all(key in data for key in required_keys):
  2482. missing = [key for key in required_keys if key not in data]
  2483. print(f"缺少必要字段: {', '.join(missing)}")
  2484. return None
  2485. conn = None
  2486. try:
  2487. conn = get_mysql()
  2488. with conn.cursor() as cur:
  2489. query_sql = """
  2490. SELECT * FROM {}
  2491. WHERE min_price = %s
  2492. AND store_name = %s
  2493. AND scrape_date = %s
  2494. AND platform_id = %s AND collect_equipment_account_id = %s
  2495. AND collect_round = %s
  2496. """.format(self.table_name)
  2497. cur.execute(query_sql, (
  2498. data['min_price'],
  2499. data['shop'],
  2500. data['scrape_date'],
  2501. data['platform'], data.get('collect_equipment_account_id', 0),
  2502. data.get('collect_round', 0),
  2503. ))
  2504. result = cur.fetchone()
  2505. return bool(result) # 如果存在返回True,否则False
  2506. except Exception as e:
  2507. print(f"MySQL 错误: {str(e)}")
  2508. finally:
  2509. if conn:
  2510. conn.close()
  2511. def get_instructions_data(self):
  2512. # 功能:在详情页中提取说明书/商品参数区域的关键字段,整理成统一字典。
  2513. """
  2514. 确定有详情页之后之后,提取所有的详情页数据
  2515. :return:
  2516. """
  2517. # 先把页面滚到说明书/参数区域附近,再开始解析键值对。
  2518. for i in range(8):
  2519. if self.d.xpath('//*[@text="品牌"]').exists or self.d.xpath('//*[@text="药品通用名"]').exists:
  2520. self.d.swipe_ext("up", scale=0.1)
  2521. print('开始采集详情数据')
  2522. break
  2523. self.d.swipe_ext("up", scale=0.5)
  2524. time.sleep(self.get_sleep_time())
  2525. # 阶段 2:进入"查看全部"区域,把折叠的参数信息完整展开。
  2526. # 点击查看全部
  2527. if self.d.xpath('//*[@text="品牌"]').exists:
  2528. self.d.xpath('//*[@text="品牌"]').click()
  2529. else:
  2530. self.d.xpath('//*[@text="药品通用名"]').click()
  2531. time.sleep(self.get_sleep_time())
  2532. attr = dict()
  2533. # 阶段 3:批量解析键值对文本,构造说明书字段字典。
  2534. # # 获取详情页信息
  2535. xpath = '//*[starts-with(@text,"商品参数")]/parent::*/parent::*/following-sibling::*/*/*/android.view.ViewGroup//android.widget.TextView'
  2536. ddd = self.d.xpath(xpath).all()
  2537. for i in range(0, len(ddd), 2):
  2538. group = ddd[i:i + 2]
  2539. attr[group[0].text] = group[1].text
  2540. # 截图获取未获取到的数据
  2541. # if not all(i in ['有效期', '生产企业', '批准文号', '药品规格', '产品规格'] for i in attr.keys()):
  2542. if not all(i in ['有效期', '生产企业', '批准文号', '药品规格'] for i in attr.keys()):
  2543. # 首轮解析拿不到关键字段时再补一次较短滑动,兼容参数区未完整展示的情况。
  2544. self.d.swipe_ext("up", 0.4)
  2545. time.sleep(self.get_sleep_time())
  2546. xpath = '//*[starts-with(@text,"商品参数")]/parent::*/parent::*/following-sibling::*/*/*/android.view.ViewGroup//android.widget.TextView'
  2547. ddd = self.d.xpath(xpath).all()
  2548. for i in range(0, len(ddd), 2):
  2549. group = ddd[i:i + 2]
  2550. attr[group[0].text] = group[1].text
  2551. print(f'当前说明书规格参数:{attr}')
  2552. res_data = {
  2553. # "有效期": attr.get('有效期',''),
  2554. # "生产单位": attr['生产企业'],
  2555. # "批准文号": attr['批准文号'],
  2556. # "产品规格": attr.get('药品规格') if attr.get('药品规格', '') else attr.get('药品规格')
  2557. "有效期": attr.get('有效期', ''),
  2558. "生产单位": attr.get('生产企业', ''),
  2559. "批准文号": attr.get('批准文号', ''),
  2560. "产品规格": attr.get('药品规格', ''),
  2561. "发货地": attr.get('发货地', '')
  2562. }
  2563. print(f'当前规格参数字典数据:{res_data}')
  2564. return res_data
  2565. def has_instructions(self):
  2566. # 功能:判断当前详情页能否找到说明书/商品详情区域。
  2567. """
  2568. 是否有详情页
  2569. :return:如果有详情页返回True,否则返回False
  2570. """
  2571. # 没有说明书的无法采集具体数据
  2572. max_attempts = 12 # 最大尝试次数
  2573. attempt = 0 # 当前尝试次数
  2574. while attempt < max_attempts:
  2575. time.sleep(0.5)
  2576. xpath = '//*[@text="商品详情"]'
  2577. is_has_instructions = self.d.xpath(xpath).exists
  2578. if is_has_instructions:
  2579. return True # 如果找到"商品详情",则返回True
  2580. self.d.swipe_ext("up", 0.3)
  2581. attempt += 1
  2582. return False # 如果尝试次数达到最大次数,则返回False
  2583. def distinct_target(self):
  2584. # 功能:判断当前页面是否已经回到商品列表页。
  2585. # 这里同时检查多个锚点,是为了兼容拼多多不同活动页和不同 UI 版本。
  2586. if self.is_pdd_home_page():
  2587. return False
  2588. search_camera = self.d.xpath('//*[@content-desc="拍照搜索"]').exists
  2589. filter_bar = self.d.xpath('//*[@text="筛选"]').exists
  2590. repeat_buy = self.d.xpath('//*[@text="618大促"]').exists
  2591. promo_banner = self.d.xpath('//*[@text="回头客常拼"]').exists
  2592. subsidy = self.d.xpath('//*[@text="百亿补贴"]').exists
  2593. list_page_xpaths = [
  2594. '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[2]/android.view.ViewGroup[1]/android.widget.LinearLayout[1]//android.support.v7.widget.RecyclerView[1]',
  2595. '//android.support.v7.widget.RecyclerView',
  2596. '//androidx.recyclerview.widget.RecyclerView',
  2597. ]
  2598. list_container = any(self.d.xpath(xpath).exists for xpath in list_page_xpaths)
  2599. result = False
  2600. if filter_bar and (list_container or repeat_buy or promo_banner or search_camera):
  2601. result = True
  2602. elif list_container and (filter_bar or repeat_buy or promo_banner or subsidy):
  2603. result = True
  2604. print(
  2605. "distinct_target -> "
  2606. f"filter_bar={filter_bar}, repeat_buy={repeat_buy}, promo_banner={promo_banner}, "
  2607. f"search_camera={search_camera}, list_container={list_container}, result={result}"
  2608. )
  2609. return result
  2610. def enter_target_page(self):
  2611. # 功能:进入搜索页、输入关键字并恢复排序/页位,为主循环建立起始页面。
  2612. # 阶段 1:进入搜索框并提交当前任务的搜索词。
  2613. # 注意:back_to_pdd_home_page + focus_search_box 已由 prepare_entry_before_enter_target 完成,这里不再重复。
  2614. search_entry_candidates = [
  2615. '//*[contains(@text, "搜索")]',
  2616. '//*[contains(@content-desc, "搜索")]',
  2617. '//*[@resource-id="android:id/content"]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]'
  2618. '/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]'
  2619. '/android.widget.LinearLayout[1]',
  2620. ]
  2621. # 多轮重试:避免"按 back 误退到桌面"导致搜索框始终找不到。
  2622. for attempt in range(4):
  2623. if self.d(className='android.widget.EditText').wait(timeout=2):
  2624. break
  2625. if not self.is_pdd_foreground():
  2626. logging.info("enter_target_page: pdd不在前台,尝试重新拉起APP")
  2627. self.start_app()
  2628. time.sleep(self.get_sleep_time())
  2629. clicked_search_entry = False
  2630. for entry_xpath in search_entry_candidates:
  2631. if self.d.xpath(entry_xpath).exists:
  2632. self.d.xpath(entry_xpath).click()
  2633. clicked_search_entry = True
  2634. time.sleep(self.get_sleep_time())
  2635. if self.d(className='android.widget.EditText').wait(timeout=2):
  2636. break
  2637. if self.d(className='android.widget.EditText').wait(timeout=1):
  2638. break
  2639. # 兜底:点击顶部中间区域,兼容节点层级变化但视觉位置不变的机型。
  2640. if not clicked_search_entry:
  2641. try:
  2642. screen_width = self.d.info.get('displayWidth', 1080)
  2643. screen_height = self.d.info.get('displayHeight', 2400)
  2644. self.d.click(screen_width // 2, int(screen_height * 0.08))
  2645. time.sleep(self.get_sleep_time())
  2646. except Exception as click_error:
  2647. logging.info(f"enter_target_page: 顶部兜底点击失败: {click_error}")
  2648. if self.d(className='android.widget.EditText').wait(timeout=1):
  2649. break
  2650. logging.info(f"enter_target_page: 第 {attempt + 1}/4 次仍未找到搜索输入框,继续重试")
  2651. if not self.d(className='android.widget.EditText').wait(timeout=2):
  2652. current_package = (self.d.app_current() or {}).get("package", "")
  2653. raise RuntimeError(f"enter_target_page: search input not found, current_package={current_package}")
  2654. self.d(className='android.widget.EditText').click()
  2655. time.sleep(self.get_sleep_time())
  2656. self.d.send_keys(self.search_key, clear=True)
  2657. time.sleep(self.get_sleep_time())
  2658. if self.d.xpath('//*[@text="搜索"]').exists:
  2659. self.d.xpath('//*[@text="搜索"]').click()
  2660. else:
  2661. self.d.press("enter")
  2662. time.sleep(self.get_sleep_time())
  2663. # 阶段 2:如果任务要求排序,则在首次进入结果页后先切到目标排序方式。
  2664. # 排序只在进入列表后的第一次执行,避免恢复进度时重复切换排序方向。
  2665. # if self.sort and self.sort_key == 0:
  2666. # self.li_or_lo(self.sort)
  2667. # progress = self.wr_re("读", self.device_id)
  2668. progress = None
  2669. # 阶段 3:如有历史页码,则把列表大致恢复到目标位置。
  2670. # 进度恢复逻辑目前停用,但保留按页滑动的入口,便于后续重新启用断点续跑。
  2671. # if not progress and self.page > 0:
  2672. # self.scroll_to_target_page(self.page)
  2673. def get_clipboard(self):
  2674. # 功能:读取设备剪贴板内容,并去掉空值和首尾空白。
  2675. self.loggerPdd.info(f"Clipboard content:{self.d.clipboard}") # 打印调试信息
  2676. clipboard_content = self.d.clipboard
  2677. if clipboard_content is None:
  2678. return ''
  2679. return clipboard_content.strip()
  2680. def get_product_link(self):
  2681. # 功能:通过商品详情页的分享入口复制商品链接。
  2682. product_link = ''
  2683. print('开始获取商品链接')
  2684. content_frame = self.d.xpath('//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]').exists
  2685. print(content_frame)
  2686. relative_layout = self.d.xpath(
  2687. '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]').exists
  2688. print(relative_layout)
  2689. relative_layout2 = self.d.xpath(
  2690. '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]').exists
  2691. print(relative_layout2)
  2692. Frame_Layout = self.d.xpath(
  2693. '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[2]').exists
  2694. print(Frame_Layout)
  2695. ImageView = self.d.xpath(
  2696. '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[2]/android.view.View[1]').exists
  2697. print(ImageView)
  2698. ImageView2 = self.d.xpath(
  2699. '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[3]/android.view.View[1]').exists
  2700. print(ImageView2)
  2701. # 多种可能的"分享"按钮
  2702. # 分享入口在不同商品页布局里位置不稳定,因此保留多套候选 XPath。
  2703. dots_xpaths = [
  2704. # '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[2]/android.view.View[1]',
  2705. '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[last()]/android.view.View[1]',
  2706. # '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[2]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[2]/android.view.View[1]',
  2707. # '//*[@resource-id="android:id/content"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[2]/android.widget.RelativeLayout[2]/android.widget.FrameLayout[3]/android.widget.ImageView[1]',
  2708. ]
  2709. # 阶段 1:遍历候选分享入口,找到当前布局下可点击的"更多/分享"按钮。
  2710. max_retry = 5 # 最多尝试次数
  2711. # 分享面板偶尔会因为动画或按钮未露出而失败,因此允许多次重试。
  2712. for idx in range(1, max_retry + 1):
  2713. if product_link: # 已经拿到则退出
  2714. break
  2715. for xp in dots_xpaths:
  2716. if self.d.xpath(xp).exists:
  2717. # print(f'{idx}-进入分享点点点')
  2718. self.loggerPdd.info(f'{idx}-进入分享点点点')
  2719. # 调用 click() 的目的是打开分享面板;
  2720. # 后续 slide_link() 和"复制链接"点击都依赖分享面板已经展开。
  2721. self.d.xpath(xp).click()
  2722. time.sleep(1)
  2723. self.loggerPdd.info('开始滑动')
  2724. # 这里先调用 slide_link(),是为了把"复制链接"按钮滑到当前可见区域。
  2725. self.slide_link()
  2726. time.sleep(0.2)
  2727. # 调用 click_exists() 的目的是直接触发系统复制动作,
  2728. # 调用后 get_clipboard() 才有机会读到最新商品链接。
  2729. self.d.xpath('//*[@text="复制链接"]').click_exists()
  2730. time.sleep(1)
  2731. product_link = self.get_clipboard()
  2732. time.sleep(0.5)
  2733. self.loggerPdd.info(f'{idx}-商品链接:{product_link}')
  2734. break # 找到并执行后跳出内层循环
  2735. if not product_link and idx < max_retry:
  2736. time.sleep(0.5) # 最后一次不需要再等待
  2737. # time.sleep(100000)
  2738. return product_link
  2739. def integrate_data_v2(self):
  2740. # 功能:在单个商品详情页内完成价格、链接、店铺、说明书、去重和落库的完整聚合流程。
  2741. """
  2742. 基于入口配置统一校验标题、品牌和品规,替代内部大量硬编码分支。
  2743. """
  2744. # 阶段 1:先拿价格和标题,并在最早阶段过滤无关商品。
  2745. # 价格优先走规格弹窗,因为这里还能顺便拿到已选规格文本。
  2746. min_price, ext = self.drug_price_ex()
  2747. title_info = self.get_title()
  2748. if not title_info:
  2749. print('标题获取为空')
  2750. return
  2751. # ========== 盒数提取(放在标题判断之后) ==========
  2752. from box_script import extract_quantity_and_unit
  2753. quantity, unit = extract_quantity_and_unit(ext)
  2754. if quantity:
  2755. print(f"✅ 提取到数量: {quantity}{unit}")
  2756. one_box_price = min_price / quantity if min_price else 0
  2757. else:
  2758. print(f"⚠️ 未提取到数量,ext={ext}")
  2759. one_box_price = 0
  2760. # =============================================
  2761. # 先只按标题/品牌做一次粗过滤,尽早淘汰无关商品。
  2762. if not self.is_link_useful(title_info):
  2763. self.unrelated_data += 1
  2764. return
  2765. # 规格弹窗提价失败时,再回退到详情页直接取价。
  2766. if not min_price:
  2767. min_price = self.drug_price()
  2768. if not min_price:
  2769. print('提取价格出错,回退到列表页')
  2770. self.unrelated_data += 1
  2771. return
  2772. # 阶段 2:补齐商品链接和店铺信息,这两类字段是后续落库和去重的关键上下文。
  2773. product_link = self.get_product_link()
  2774. time.sleep(2)
  2775. oss_url = ''
  2776. try:
  2777. result = self.screenshot_and_upload_oss()
  2778. if result:
  2779. oss_url = result
  2780. print(f"OSS快照上传成功: {oss_url}")
  2781. else:
  2782. print("OSS快照上传失败(返回空)")
  2783. except Exception as e:
  2784. print(f"OSS快照异常: {e}")
  2785. oss_url = ''
  2786. # 有的页面店铺信息不在首屏,这里按配置决定是否直接读取还是先滑动到店铺区域。
  2787. if self.direct_shop_lookup:
  2788. shop = self.get_shop_name()
  2789. else:
  2790. # 先检查首屏是否已有店铺信息(进店按钮 或 店铺名关键词 或 底部店铺tab)
  2791. has_shop_anchor = (
  2792. self.d(textStartsWith="进店").exists
  2793. or self.d.xpath('//*[@content-desc="店铺"]').exists
  2794. or any(
  2795. self.d.xpath(f'//android.widget.TextView[contains(@text, "{kw}")]').exists
  2796. for kw in ['大药房', '旗舰店', '专卖店', '药房']
  2797. )
  2798. )
  2799. if not has_shop_anchor:
  2800. for _ in range(3):
  2801. self.d.swipe_ext("up", scale=0.3)
  2802. time.sleep(self.get_sleep_time())
  2803. if (
  2804. self.d(textStartsWith="进店").exists
  2805. or self.d.xpath('//*[@content-desc="店铺"]').exists
  2806. or any(
  2807. self.d.xpath(f'//android.widget.TextView[contains(@text, "{kw}")]').exists
  2808. for kw in ['大药房', '旗舰店']
  2809. )
  2810. ):
  2811. print('可以开始获取店铺名')
  2812. break
  2813. shop = self.get_shop_name()
  2814. if not shop:
  2815. print('当前店铺名称为空')
  2816. self.unrelated_data += 1
  2817. return
  2818. scrape_date = self.get_current_date()
  2819. dup_data = {
  2820. 'min_price': min_price,
  2821. 'shop': shop,
  2822. 'scrape_date': scrape_date,
  2823. 'platform': '3'
  2824. }
  2825. # 同一天同店铺同价格的数据视为重复,避免重复入库。
  2826. if self.data_is_exists(dup_data):
  2827. print('存在相同数据不入库')
  2828. self.back_to_list_page()
  2829. return
  2830. shop_data = {
  2831. 'shop': shop,
  2832. 'store_url': product_link,
  2833. 'scrape_date': scrape_date,
  2834. 'platform': 3,
  2835. 'create_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
  2836. 'update_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  2837. }
  2838. province_name = ''
  2839. city_name = ''
  2840. company_name = ''
  2841. # 插入店铺数据
  2842. if self.shop_is_exists(shop_data):
  2843. print("店铺数据已存在,进行省市回填")
  2844. self.get_province_city(shop_data)
  2845. province_name = shop_data['province_name']
  2846. city_name = shop_data['city_name']
  2847. company_name = shop_data.get('company_name', '')
  2848. else:
  2849. # 获取产品详情页的店铺资质
  2850. shop_info = self.get_license_info()
  2851. print(f"店铺数据不存在,获取店铺资质信息:{shop_info}")
  2852. print(f"店铺数据不存在,插入{self.shop_table_name}店铺表")
  2853. if shop_info:
  2854. shop_data.update(shop_info)
  2855. print(f"组合店铺数据:{shop_data}")
  2856. self.save_to_shop_database(shop_data)
  2857. # 从合并后的 shop_data 提取字段,供后续 save_data 写入 retrieve_scrape_data
  2858. province_name = shop_data.get('province', '')
  2859. city_name = shop_data.get('city', '')
  2860. company_name = shop_data.get('business_license_company', '')
  2861. # 阶段 3:确认是否存在说明书页,并在有说明书时补提取规格、生产单位和批准文号。
  2862. is_has_instructions = self.has_instructions()
  2863. self.loggerPdd.info(f'是否有说明书:{is_has_instructions}')
  2864. manufacture_date = ''
  2865. shipmentProvinceName = ''
  2866. credit_code = ext
  2867. # 说明书页不是每个商品都有;没有时允许继续落库,只是相关字段留空。
  2868. province_id, city_id = self._resolve_region_ids(province_name, city_name)
  2869. if is_has_instructions:
  2870. try:
  2871. instructions_info = self.get_instructions_data()
  2872. expiry_date = instructions_info['有效期'].strip('。')
  2873. manufacturer = instructions_info['生产单位'].strip('。')
  2874. approval_number = instructions_info['批准文号'].strip('。')
  2875. specifications = instructions_info['产品规格'].strip('。')
  2876. shipmentProvinceName = instructions_info.get('发货地', '').strip('。')
  2877. except Exception as e:
  2878. print(f'获取详情页规格参数出错:{e}')
  2879. return
  2880. else:
  2881. expiry_date = ''
  2882. manufacturer = ''
  2883. approval_number = ''
  2884. specifications = ''
  2885. # 二次校验把说明书里的规格也纳入判断,避免标题模糊匹配带来误采。
  2886. if not self.is_link_useful(title_info, specifications):
  2887. self.unrelated_data += 1
  2888. return
  2889. self.unrelated_data = 0
  2890. # 不再依赖盒数处理脚本,单盒价格默认回退为 0。
  2891. one_box_price = 0
  2892. # 阶段 4:把当前详情页提取结果整理成统一落库结构。
  2893. save_data = {
  2894. 'enterprise_id': self.enterprise_id,
  2895. 'platform_id': self.platform,
  2896. 'platform_item_id': '',
  2897. 'province_id': province_id,
  2898. 'city_id': city_id,
  2899. 'province_name': province_name,
  2900. 'city_name': city_name,
  2901. 'area_info': "",
  2902. 'product_brand': self.brand,
  2903. 'product_name': title_info,
  2904. 'product_specs': specifications,
  2905. 'search_name': self.search_key,
  2906. 'collect_config_info': self.collect_config_info,
  2907. 'one_box_price': one_box_price,
  2908. 'manufacture_date': manufacture_date,
  2909. 'expiry_date': expiry_date,
  2910. 'manufacturer': manufacturer,
  2911. 'approval_number': approval_number,
  2912. 'is_sold_out': 0,
  2913. 'online_posting_count': 1,
  2914. 'continuous_listing_count': 1,
  2915. 'link_url': product_link,
  2916. 'store_name': shop,
  2917. 'store_url': '',
  2918. 'shipment_province_id': 0,
  2919. 'shipment_province_name': shipmentProvinceName,
  2920. 'shipment_city_id': 0,
  2921. 'shipment_city_name': "",
  2922. 'company_name': company_name,
  2923. 'qualification_number': "",
  2924. 'scrape_date': scrape_date,
  2925. 'min_price': min_price,
  2926. 'number': 1,
  2927. 'sales': "",
  2928. 'inventory': "",
  2929. 'snapshot_url': oss_url or '',
  2930. 'insert_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
  2931. 'update_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
  2932. 'collect_equipment_account_id': self.collect_equipment_account_id,
  2933. 'collect_region_id': self.collect_region_id,
  2934. 'collect_round': self.collect_round,
  2935. }
  2936. # 调用 save_to_database() 的目的是把当前已经校验通过的数据立即持久化,
  2937. # 避免后续页面跳转、返回或异常中断导致采集结果丢失。
  2938. self.save_to_database(save_data)
  2939. return True
  2940. def main(self, device_id, search_key_length, keyword_idx):
  2941. # 功能:执行单设备的完整采集主循环,直到达到结束页、采集上限或异常退出条件。
  2942. completed_normally = False
  2943. stop_by_max_count = False
  2944. spider_no = 0
  2945. current_page = self.page
  2946. consecutive_empty_pages = 0
  2947. # 阶段 1:建立设备连接,准备进入搜索页面。
  2948. self.connect_devices(device_id)
  2949. time.sleep(self.get_sleep_time())
  2950. # 统一入口准备:按需重启,然后回到主页面并点出搜索框。
  2951. if self.is_pdd_foreground():
  2952. logging.info("当前在拼多多可操作页面,执行统一入口准备(回主页面+点搜索框)")
  2953. self.prepare_entry_before_enter_target(force_restart=False)
  2954. else:
  2955. logging.info("当前不在拼多多可操作页面,先重启,再执行统一入口准备")
  2956. self.prepare_entry_before_enter_target(force_restart=True)
  2957. self.enter_target_page()
  2958. # 阶段 2:向调度系统上报"执行中",然后开始按页扫描商品列表。
  2959. # 上报状态
  2960. # 进入主循环前先上报"执行中",让调度系统能看到设备已经开始跑任务。
  2961. report_api(self.task_id, platform=self.platform, username=getattr(self, 'username', ''),
  2962. page=self.page, is_finished=0)
  2963. # ========== 新增:启动心跳上报线程 ==========
  2964. self._heartbeat_running = True
  2965. def heartbeat_worker():
  2966. while self._heartbeat_running:
  2967. time.sleep(HEARTBEAT_INTERVAL_SECONDS)
  2968. if self._heartbeat_running:
  2969. report_heartbeat(self.task_id, getattr(self, 'page', 0), device_id=self.device_id)
  2970. heartbeat_thread = threading.Thread(target=heartbeat_worker, daemon=True)
  2971. heartbeat_thread.start()
  2972. # ==========================================
  2973. try:
  2974. for idx in range(300):
  2975. print(f'第{current_page}页')
  2976. # self.wr_re("写", self.device_id, self.sort, current_page)
  2977. if spider_no > 30:
  2978. time.sleep(300)
  2979. spider_no = 0
  2980. # 连续命中太多无关商品时,认为当前搜索结果已偏离目标,主动收尾。
  2981. if self.unrelated_data > 15:
  2982. print(f'[{self.program_start_time}]----{self.search_key}----连续超过15个不达标的数据则停止采集')
  2983. print(
  2984. f"[程序启动时间:{self.program_start_time}-----程序结束时间:{self.app_current_time()}]----搜索关键词:{self.search_key}----点击了{self.click_counts}个商品")
  2985. completed_normally = self.finish_task_normally(
  2986. current_page,
  2987. '连续超过15个不达标的数据,结束采集'
  2988. )
  2989. break
  2990. # 达到采集上限后不再继续翻页,直接走正常结束分支。
  2991. if self.is_max_count_reached():
  2992. completed_normally = self.finish_task_with_max_count(current_page)
  2993. # 向下滑
  2994. self.swipe_down()
  2995. time.sleep(self.get_sleep_time())
  2996. # 点击搜索框
  2997. click_success = self.click_target_product_by_search_key(fuzzy_match=False)
  2998. if not click_success:
  2999. print(f"关键词「{self.search_key}」商品点击失败")
  3000. break
  3001. print("点击搜索框")
  3002. self.d(className='android.widget.EditText').click()
  3003. time.sleep(self.get_sleep_time())
  3004. break
  3005. # 售罄次数大于4基本就是号废了但是如果下次点击不会出现这种情况就要重置为0
  3006. # 连续多次命中售罄商品时,认为当前账号/结果页已失去采集价值,提前退出。
  3007. if self.sold_out_counts > 4:
  3008. self.finish_task_abnormally(
  3009. current_page,
  3010. "====商品已售罄4次,结束采集(号不能用)",
  3011. finish_status=1
  3012. )
  3013. print(
  3014. f"[程序启动时间:{self.program_start_time}-----程序结束时间:{self.app_current_time()}]----搜索关键词:{self.search_key}----点击了{self.click_counts}个商品")
  3015. break
  3016. # 阶段 3:获取当前页可见商品卡片,并逐个点击进入详情页采集。
  3017. # 检测"官方旗舰店"区域:如果"进店逛逛"和店铺icon同时存在,
  3018. # 说明列表顶部有旗舰店入口,先下滑跳过该区域再取商品列表。
  3019. if self.d.xpath('//*[@text="进店逛逛"]').exists or \
  3020. self.d.xpath('//*[@text="进店"]').exists:
  3021. print('检测到官方旗舰店区域,向下滑动半屏跳过')
  3022. screen_w = self.d.info.get('displayWidth', 1080)
  3023. screen_h = self.d.info.get('displayHeight', 2400)
  3024. self.d.swipe(
  3025. screen_w // 2,
  3026. int(screen_h * 0.7),
  3027. screen_w // 2,
  3028. int(screen_h * 0.2),
  3029. duration=0.4
  3030. )
  3031. time.sleep(self.get_sleep_time())
  3032. drug_lis = self.get_drug_lis(idx)
  3033. print('数量', len(drug_lis))
  3034. if not drug_lis:
  3035. consecutive_empty_pages += 1
  3036. logging.warning(
  3037. f"main: 第 {current_page} 页未识别到商品,连续空页次数={consecutive_empty_pages}"
  3038. )
  3039. if not self.distinct_target():
  3040. logging.warning("main: 当前疑似不在商品列表页,尝试回退恢复列表页")
  3041. recovered = self.back_to_list_page()
  3042. if not recovered and (
  3043. self.is_pdd_home_page()
  3044. or (self.d(className='android.widget.EditText').exists and not self.d.xpath('//*[@text="筛选"]').exists)
  3045. ):
  3046. logging.warning("main: 已落到首页/搜索输入页,直接重新进入搜索结果页")
  3047. self.enter_target_page()
  3048. current_page = self.page
  3049. consecutive_empty_pages = 0
  3050. continue
  3051. time.sleep(self.get_sleep_time())
  3052. drug_lis = self.get_drug_lis(idx)
  3053. print('恢复后数量', len(drug_lis))
  3054. else:
  3055. logging.warning("main: 仍在列表页但商品列表为空,先做一次轻微下滑恢复")
  3056. self.swipe_down()
  3057. time.sleep(self.get_sleep_time())
  3058. drug_lis = self.get_drug_lis(idx)
  3059. print('下滑恢复后数量', len(drug_lis))
  3060. if drug_lis:
  3061. consecutive_empty_pages = 0
  3062. elif consecutive_empty_pages >= 3:
  3063. logging.warning("main: 连续空页达到阈值,重新进入搜索结果页")
  3064. self.enter_target_page()
  3065. current_page = self.page
  3066. consecutive_empty_pages = 0
  3067. continue
  3068. for idd, drug_one in enumerate(drug_lis):
  3069. print(idd + 1, drug_one.info)
  3070. time.sleep(self.get_sleep_time())
  3071. top = drug_one.info['bounds']['top']
  3072. bottom = drug_one.info['bounds']['bottom']
  3073. _, screen_h = self.get_screen_size()
  3074. if bottom <= int(screen_h * 0.93) and top >= int(screen_h * 0.16):
  3075. drug_one.click()
  3076. self.click_counts += 1
  3077. time.sleep(self.get_sleep_time())
  3078. # 先判断是否售罄次数是否大于4
  3079. if self.sold_out_counts >= 4:
  3080. print(
  3081. f"[程序启动时间:{self.program_start_time}-----程序结束时间:{self.app_current_time()}]----搜索关键词:{self.search_key}----点击了{self.click_counts}个商品")
  3082. self.finish_task_abnormally(
  3083. current_page,
  3084. "====这是在第一页有两个,商品已售罄4次,结束采集(号不能用)====",
  3085. finish_status=1
  3086. )
  3087. time.sleep(self.get_sleep_time())
  3088. self.d.press('home')
  3089. stop_by_max_count = True
  3090. break
  3091. # 这里先判断"商品已售罄",是为了尽早放弃无效详情页;
  3092. # 如果不先做这一步,后续详情采集会浪费时间且可能干扰账号状态判断。
  3093. if self.d.xpath('//*[contains(@text, "商品已售罄")]').wait(timeout=5):
  3094. print("======商品已售罄======")
  3095. self.sold_out_counts += 1
  3096. if self.back_to_list_page():
  3097. continue
  3098. # 采集药品信息
  3099. # 进入详情页后的采集与回退是最容易卡死的阶段,需要单独兜底。
  3100. try:
  3101. # 重置商品售罄次数
  3102. self.sold_out_counts = 0
  3103. saved = self.integrate_data_v2()
  3104. # 新加判断逻辑(增加采集速度),如果保存成功数据返回true,然后执行点商品参数的×,否则就执行一次返回
  3105. if saved:
  3106. x_btn = self.d.xpath('//*[@text=""]')
  3107. if x_btn.exists:
  3108. x_btn.click()
  3109. time.sleep(random.uniform(0.5, 1))
  3110. self.d.press("back")
  3111. time.sleep(random.uniform(0.5, 1))
  3112. else:
  3113. self.d.press("back")
  3114. time.sleep(random.uniform(0.5, 0.8))
  3115. # 检测下是否回退到列表页
  3116. if self.back_to_list_page():
  3117. print('回退到列表页', True)
  3118. else:
  3119. print(f'[{self.app_current_time()}] 回退到列表页失败')
  3120. print(
  3121. f"[程序启动时间:{self.program_start_time}-----结束时间:{self.app_current_time()}]----搜索关键词:{self.search_key}----点击了{self.click_counts}个商品")
  3122. self.finish_task_abnormally(current_page, "回退到列表页失败,结束采集")
  3123. stop_by_max_count = True
  3124. break
  3125. time.sleep(self.get_sleep_time())
  3126. spider_no += 1
  3127. if self.is_max_count_reached():
  3128. completed_normally = self.finish_task_with_max_count(current_page)
  3129. stop_by_max_count = True
  3130. break
  3131. except Exception as e:
  3132. self.loggerPdd.error(f'采集药品详情数据出错:{e}')
  3133. if not self.back_to_list_page():
  3134. self.finish_task_abnormally(current_page, '采集药品详情数据出错且无法回到列表页,结束采集')
  3135. stop_by_max_count = True
  3136. break
  3137. else:
  3138. continue
  3139. if drug_lis:
  3140. consecutive_empty_pages = 0
  3141. # 阶段 4:处理翻页前的收尾条件,包括采集上限、结束页和列表到底。
  3142. if stop_by_max_count:
  3143. break
  3144. # 配置了结束页时,以调用方传入的页边界作为最高优先级退出条件。
  3145. if self.end_page is not None and current_page >= self.end_page:
  3146. completed_normally = self.finish_task_normally(
  3147. current_page,
  3148. f"已采集到结束页 {self.end_page},结束任务"
  3149. )
  3150. break
  3151. if self.d(textStartsWith="抱歉,没有更多商品啦~").exists:
  3152. completed_normally = self.finish_task_normally(current_page, '已经到达列表页最底部')
  3153. break
  3154. # 阶段 5:当前页还没触发任何结束条件时,继续滑到下一页。
  3155. print('开始滑入下一页')
  3156. # 修复滑动抖动:使用固定的滑动参数
  3157. screen_width = self.d.info.get('displayWidth', 1080)
  3158. screen_height = self.d.info.get('displayHeight', 2400)
  3159. # 固定滑动参数,不随页数变化
  3160. start_x = screen_width // 2 # 屏幕中心
  3161. start_y = int(screen_height * 0.8) # 从屏幕80%高度开始
  3162. end_y = int(screen_height * 0.2) # 滑动到屏幕20%高度
  3163. self.d.swipe(start_x, start_y, start_x, end_y, duration=random.uniform(0.2, 0.4))
  3164. time.sleep(self.get_sleep_time())
  3165. current_page += 1
  3166. self.page = current_page
  3167. finally:
  3168. # ========== 新增:停止心跳上报线程 ==========
  3169. self._heartbeat_running = False
  3170. # ==========================================
  3171. # 阶段 6:根据最终状态做统一收尾,保证任务一定会走到正常或异常结束分支之一。
  3172. if completed_normally:
  3173. self.clear_progress_file()
  3174. elif not self.finish_reported:
  3175. self.finish_task_abnormally(current_page, "采集流程异常结束")
  3176. return completed_normally
  3177. # pdd
  3178. def main():
  3179. # 功能:启动调度器入口,先立即执行一轮派单,再注册后续轮询。
  3180. interval_seconds = MANUAL_SCHEDULER_INTERVAL_SECONDS if USE_MANUAL_TASKS else SCHEDULER_INTERVAL_SECONDS
  3181. logging.info(f"PDD 调度器启动,轮询间隔 {interval_seconds} 秒")
  3182. dispatch_pending_tasks()
  3183. if USE_MANUAL_TASKS:
  3184. logging.info(f"手动任务模式:启动定时轮询,间隔 {MANUAL_SCHEDULER_INTERVAL_SECONDS} 秒")
  3185. if all_manual_tasks_dispatched() and not has_active_workers():
  3186. logging.info("手动任务模式:全部任务已完成,进程退出")
  3187. return
  3188. schedule_dispatch(MANUAL_SCHEDULER_INTERVAL_SECONDS, manual_scheduled_dispatch_job)
  3189. scheduler_stop_event.wait()
  3190. return
  3191. schedule_dispatch(SCHEDULER_INTERVAL_SECONDS)
  3192. scheduler_stop_event.wait()
  3193. if __name__ == '__main__':
  3194. main()