aaa_mt.py 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172
  1. import sys
  2. import sys
  3. import logging
  4. import threading
  5. from concurrent.futures import ThreadPoolExecutor
  6. import pymysql
  7. import requests
  8. import base64
  9. import cv2
  10. import uiautomator2 as u2
  11. import time
  12. import subprocess
  13. import re
  14. import random
  15. import datetime
  16. import json
  17. from aip import AipOcr
  18. import threading
  19. from collections import deque
  20. import numpy as np
  21. import secrets
  22. import os
  23. import oss2
  24. import urllib.parse
  25. from config import Config
  26. from logger import setup_logger
  27. import logging
  28. from PIL import Image
  29. from pathlib import Path
  30. from PIL import Image, ImageDraw, ImageFont
  31. import http.client
  32. _DEFAULT_PATH = Path(__file__).with_name("city.json")
  33. import city_name_to_id
  34. setup_logger("mt_spider") # 初始化日志
  35. class SpiderMonitor(threading.Thread):
  36. """全局弹窗监控线程(增强版)"""
  37. def __init__(self, spider_instance):
  38. super().__init__(daemon=True)
  39. self.spider = spider_instance
  40. self.running = True
  41. self.pausing = threading.Event() # 主线程同步事件
  42. self.last_verification_time = 0
  43. self.verification_count = 0
  44. self.MAX_VERIFICATION_RETRY = 10
  45. self.recent_clicks = deque(maxlen=10) # 防重复点击
  46. self.logger = logging.getLogger("SpiderMonitor")
  47. # 可配置化弹窗规则
  48. self.popup_rules = {
  49. "simple": [
  50. ('//*[@text="确定"]', "点击确定"),
  51. ('//*[@text="允许"]', "点击允许"),
  52. ('//*[@text="关闭"]', "点击关闭"),
  53. ('//*[@resource-id="com.sankuai.meituan:id/close"]', "关闭按钮"),
  54. ('//*[@resource-id="com.sankuai.meituan:id/address_center_location_close"]', "关闭按钮"),
  55. ('//*[@resource-id="com.sankuai.meituan:id/location_close"]', "关闭按钮"),
  56. ('//*[@resource-id="com.sankuai.meituan:id/btn_close"]', "关闭按钮"),
  57. ],
  58. "verification": [
  59. '//*[contains(@text, "验证")]',
  60. '//*[contains(@text, "滑块")]',
  61. '//*[contains(@text, "依次点击")]',
  62. '//*[contains(@text, "请点击")]',
  63. '//*[contains(@text, "拖动滑块刚")]', # 这个需要拖动滑块至最右边,然后再截图
  64. '//*[contains(@text, "请输入图片中的内容")]',
  65. '//*[contains(@text, "用最短线连接")]',
  66. '//*[contains(@text, "请按语序依次点击")]',
  67. '//*[contains(@text, "请向右滑动滑块")]',
  68. '//*[contains(@text, "请拖动下方滑块完成拼图")]',
  69. '//*[contains(@resource-id, "captcha")]'
  70. ]
  71. }
  72. def run(self):
  73. while self.running:
  74. try:
  75. handled = self.check_and_handle_popup()
  76. time.sleep(2 if handled else 1)
  77. except Exception as e:
  78. self.logger.exception("监控线程异常: %s", e)
  79. time.sleep(1)
  80. def _is_recent_click(self, xpath):
  81. """防止重复点击同一个弹窗"""
  82. key = f"{xpath}_{int(time.time())}"
  83. if key in self.recent_clicks:
  84. return True
  85. self.recent_clicks.append(key)
  86. return False
  87. def check_and_handle_popup(self):
  88. d = self.spider.d
  89. # 1. 处理简单弹窗
  90. for xpath, desc in self.popup_rules["simple"]:
  91. if d.xpath(xpath).exists and not self._is_recent_click(xpath):
  92. self.logger.info("检测到弹窗: %s", desc)
  93. d.xpath(xpath).click()
  94. return True
  95. # 2. 处理验证码弹窗
  96. for xpath in self.popup_rules["verification"]:
  97. if d.xpath(xpath).exists:
  98. now = time.time()
  99. if now - self.last_verification_time < 30:
  100. return False # 30秒内不重复触发
  101. self.last_verification_time = now
  102. self.verification_count += 1
  103. self.logger.warning("验证码弹窗触发,等待人工处理...")
  104. if self.verification_count > self.MAX_VERIFICATION_RETRY:
  105. self.logger.error("验证码重试超限,终止任务")
  106. self.spider.stop_all()
  107. return True
  108. self.pausing.set() # 通知主线程暂停
  109. # d.toast.show("需要人工处理验证码", 120)
  110. while True:
  111. if not d.xpath(xpath).exists:
  112. self.logger.info("验证码已处理")
  113. # d.toast.show("验证完成", 2)
  114. self.pausing.clear() # 放行主线程
  115. return True
  116. time.sleep(2)
  117. self.logger.warning("验证码超时,重启APP")
  118. self.spider.restart_app()
  119. return True
  120. # 3. 处理广告弹窗(点击右上角)
  121. if d.xpath('//*[contains(@text, "广告")]').exists:
  122. w, h = d.info['displayWidth'], d.info['displayHeight']
  123. d.click(w - 50, 50)
  124. self.logger.info("关闭广告弹窗")
  125. return True
  126. return False
  127. def stop(self):
  128. self.running = False
  129. class MTScreenshot:
  130. def __init__(self, d, oss_config, search_key, title_key, scroll_times=4, compress_quality=7, resize_ratio=0.8):
  131. # 接收外部已连接好的u2设备实例
  132. self.d = d
  133. self.search_key = search_key # 添加这行
  134. self.title_key = title_key
  135. # 启动全局弹窗监控
  136. self.monitor = SpiderMonitor(self)
  137. self.monitor.start()
  138. self.loggerMT = logging.getLogger()
  139. # 日志初始化
  140. self.logger = self._init_logger()
  141. # OSS配置与初始化(核心配置,无冗余)
  142. self.oss_config = oss_config
  143. self.oss_bucket = self._init_oss_bucket()
  144. # 截图核心参数
  145. self.scroll_times = scroll_times
  146. self.compress_quality = compress_quality
  147. self.resize_ratio = resize_ratio
  148. def _init_logger(self):
  149. # 极简日志配置,仅保留必要输出
  150. logger = logging.getLogger("mt_screenshot")
  151. logger.setLevel(logging.INFO)
  152. logger.handlers.clear()
  153. handler = logging.StreamHandler()
  154. handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
  155. logger.addHandler(handler)
  156. return logger
  157. def _init_oss_bucket(self):
  158. # 仅做OSS配置校验和Bucket连接,无额外功能
  159. if not all([self.oss_config.get("access_key_id"),
  160. self.oss_config.get("access_key_secret"),
  161. self.oss_config.get("endpoint"),
  162. self.oss_config.get("bucket_name")]):
  163. self.logger.warning("OSS配置不完整,无法上传")
  164. return None
  165. try:
  166. auth = oss2.Auth(self.oss_config["access_key_id"], self.oss_config["access_key_secret"])
  167. bucket = oss2.Bucket(auth, self.oss_config["endpoint"], self.oss_config["bucket_name"])
  168. bucket.get_bucket_info() # 验证连接
  169. self.logger.info("OSS Bucket连接成功")
  170. return bucket
  171. except Exception as e:
  172. self.logger.error(f"OSS Bucket连接失败: {e}")
  173. return None
  174. def _upload_to_oss(self, local_path):
  175. # 极简上传逻辑,仅返回OSS URL或None
  176. if not self.oss_bucket or not os.path.exists(local_path):
  177. return None
  178. file_name = os.path.basename(local_path)
  179. safe_name = re.sub(r'[^\w\.\-]', '_', file_name)
  180. oss_key = f"{self.oss_config.get('oss_prefix', 'scrape_data/')}{safe_name}"
  181. try:
  182. oss2.resumable_upload(self.oss_bucket, oss_key, local_path)
  183. # 生成并返回完整OSS URL
  184. oss_file_url = f"https://{self.oss_config['bucket_name']}.{self.oss_config['endpoint']}/{urllib.parse.quote(oss_key, safe='/')}"
  185. self.logger.info(f"OSS上传成功: {oss_file_url}")
  186. return oss_file_url
  187. except Exception as e:
  188. self.logger.error(f"OSS上传失败: {e}")
  189. return None
  190. def safe_exec(self, func, *args, **kwargs):
  191. """
  192. 万能安全壳:执行 func 前检查验证码,
  193. 若监控线程已置位 pausing,则一直阻塞直到放行。
  194. """
  195. while self.monitor.pausing.is_set():
  196. time.sleep(1)
  197. # 执行真正逻辑
  198. return func(*args, **kwargs)
  199. def _get_title(self):
  200. # try:
  201. def _inner():
  202. print(f'获取商品title时的搜索关键字:{self.title_key}')
  203. # 初始化
  204. drugs_name = ''
  205. specifications = ''
  206. title = ''
  207. # 循环的获取title为了有时间来处理人机验证
  208. for m in range(1, 6000):
  209. if self.d.xpath(f'//*[contains(@text, "{self.title_key}")]').exists:
  210. title = self.safe_exec(
  211. lambda: self.d.xpath(f'//*[contains(@text, "{self.title_key}")]').text
  212. )
  213. self.loggerMT.info(f"第{m}次获取title成功")
  214. print(f"第{m}次获取title成功")
  215. break
  216. else:
  217. time.sleep(1)
  218. # return drugs_name, specifications
  219. title = title[1:] if title.startswith('0') else title
  220. print(f'获取到药品标题:{title}')
  221. match = re.match(r'(\[[^\]]+\])(.*?)\s*((?:\d+\S*|\(.+))$', title)
  222. if match:
  223. drugs_name = title
  224. specifications = match.group(3).strip()
  225. print("药品名:", drugs_name)
  226. print("规格:", specifications)
  227. # print('完整药名:', drugs_name + specifications)
  228. return drugs_name # , specifications
  229. else:
  230. drugs_name = title
  231. specifications = ''
  232. return drugs_name
  233. # 用 safe_exec 包装内部逻辑,确保验证码阻塞
  234. return self.safe_exec(_inner)
  235. def _merge_screenshots(self, screens):
  236. # 仅拼接截图,无额外功能
  237. if len(screens) == 1:
  238. return screens[0].convert('RGB')
  239. rgb_screens = [s.convert('RGB') for s in screens]
  240. total_width = rgb_screens[0].width
  241. total_height = sum(s.height for s in rgb_screens)
  242. merged_img = Image.new('RGB', (total_width, total_height))
  243. y_offset = 0
  244. for img in rgb_screens:
  245. merged_img.paste(img, (0, y_offset))
  246. y_offset += img.height
  247. return merged_img
  248. def get_oss_url(self):
  249. """核心方法:截图+临时本地保存+上传OSS+上传成功删本地文件+返回OSS URL,可直接赋值给oss_file"""
  250. local_file_path = None
  251. try:
  252. # 1. 提取标题
  253. title = self._get_title()
  254. self.logger.info(f"获取标题: {title[:20]}..." if title else "未获取到标题")
  255. # 2. 生成本地文件路径
  256. timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
  257. safe_title = re.sub(r'[\\/*?:"<>|]', '_', title)
  258. local_dir = "../scrape_data"
  259. os.makedirs(local_dir, exist_ok=True)
  260. local_file_path = os.path.join(local_dir, f"{timestamp}_{safe_title}.jpg")
  261. # 3. 滚动截图
  262. screen_list = [self.d.screenshot()]
  263. w, h = self.d.window_size()
  264. for i in range(self.scroll_times):
  265. # 可能滑动距离太短,截不到店名。原本是0.8
  266. # self.d.swipe(w // 2, h * 0.9, w // 2, h * 0.1, duration=random.uniform(0.6, 1.2))
  267. self.d.swipe(w // 2, h * 0.85, w // 2, h * 0.15, # 滑动到15%
  268. duration=random.uniform(0.8, 1.5))
  269. time.sleep(random.uniform(2.0, 4.0))
  270. screen_list.append(self.d.screenshot())
  271. if self.d(textContains='商家服务').exists:
  272. # 看情况是否需要补滑
  273. break
  274. # 4. 拼接+压缩+保存
  275. merged_img = self._merge_screenshots(screen_list)
  276. if 0.1 < self.resize_ratio < 1.0:
  277. new_size = (int(merged_img.width * self.resize_ratio), int(merged_img.height * self.resize_ratio))
  278. resample_mode = Image.Resampling.LANCZOS if hasattr(Image, 'Resampling') else Image.LANCZOS
  279. merged_img = merged_img.resize(new_size, resample_mode)
  280. # 临时保存到本地
  281. merged_img.save(local_file_path, format='JPEG', quality=self.compress_quality)
  282. merged_img.close() # 释放长图句柄
  283. self.logger.info(f"临时本地保存: {local_file_path}")
  284. # 5. 上传OSS
  285. oss_url = self._upload_to_oss(local_file_path)
  286. # 6. 核心:OSS上传成功后,删除本地临时文件
  287. if oss_url is not None:
  288. try:
  289. self.logger.info(f"✅ OSS上传成功,已删除本地临时文件: {local_file_path}")
  290. except Exception as e:
  291. self.logger.warning(f"⚠️ OSS上传成功,但删除本地文件失败: {e}")
  292. return oss_url
  293. except Exception as e:
  294. self.logger.error(f"截图/上传失败: {e}")
  295. return None
  296. def get_access_token():
  297. AppKey = "tRK2RhyItCSh6BzyT4CNVXQa"
  298. AppSrcret = "TDgKiPo94i2mOM1sDqOuDnlcK1bG66jh"
  299. token_url = 'https://aip.baidubce.com/oauth/2.0/token'
  300. url = f"{token_url}?grant_type=client_credentials&client_id={AppKey}&client_secret={AppSrcret}"
  301. payload = ""
  302. headers = {
  303. 'Content-Type': 'application/json',
  304. 'Accept': 'application/json'
  305. }
  306. response = requests.request("POST", url, headers=headers, data=payload)
  307. try:
  308. return response.json()['access_token']
  309. except:
  310. return None
  311. def get_mysql():
  312. # return pymysql.connect(
  313. # host='39.108.116.125', # "localhost", # 修改后的主机
  314. # port=3306, # 3306, # 添加端口号
  315. # user='drug_retrieve', # 'root', # 修改后的用户名
  316. # password='Pem287cwM58jNpe2', # 修改后的密码
  317. # db='drug_retrieve', #
  318. # charset='utf8mb4'
  319. # )
  320. return pymysql.connect(
  321. host='120.24.49.2', # 修改后的主机
  322. port=3306, # 添加端口号
  323. user='drug_retrieve', # 修改后的用户名
  324. password='ksCt3xm6chzdkafj', # 修改后的密码
  325. db='drug_retrieve', # 修改后的数据库名
  326. charset='utf8mb4'
  327. )
  328. class MT:
  329. def __init__(
  330. self,
  331. key,
  332. title_key,
  333. spec_list,
  334. brand,
  335. sort=None,
  336. collect_range=None,
  337. page_range=None,
  338. workflow_retry_limit=None,
  339. workflow_error_action=None,
  340. ):
  341. self.package_name = Config.PACKAGE_NAME
  342. self.access_token = get_access_token()
  343. self.city2province = self.get_city_info()
  344. self.APP_ID = '116857964'
  345. self.API_KEY = '1gAzACJOAr7BeILKqkqPOETh'
  346. self.SECRET_KEY = 'ZNArANb9GwJYgLKg4EfYhukKBfPdl1n3'
  347. self.client = AipOcr(self.APP_ID, self.API_KEY, self.SECRET_KEY)
  348. self.city_to_name = city_name_to_id.build_city_name_to_id(_DEFAULT_PATH)
  349. self.table_name = "retrieve_scrape_data"
  350. self.shop_table_name = "mt_shop_info_middle"
  351. self.loggerMT = logging.getLogger()
  352. self.page = 0
  353. self.search_key = key
  354. self.title_key = title_key
  355. self.spec_list = spec_list
  356. self.brand = brand
  357. self.sort = sort
  358. self.collect_range = self.normalize_collect_range(collect_range)
  359. self.page_range = self.normalize_page_range(page_range)
  360. self.sort_key = 0
  361. self.unrelated_data = 0
  362. self.shop_data_num = 0
  363. self.max_unrelated_data = 15
  364. self.collection_cursor = {"page_no": 1, "item_index": 0}
  365. self.workflow_retry_limit = workflow_retry_limit or {
  366. "start_app": 3,
  367. "open_product_list_page": 3,
  368. "collect_single_product": 3,
  369. }
  370. self.workflow_error_action = workflow_error_action or {
  371. "start_app": "start_app",
  372. "open_product_list_page": "start_app",
  373. "collect_single_product": "back_to_list_page",
  374. }
  375. @staticmethod
  376. def normalize_collect_range(collect_range):
  377. if not collect_range:
  378. return None
  379. start = None
  380. end = None
  381. if isinstance(collect_range, dict):
  382. start = collect_range.get("start")
  383. end = collect_range.get("end")
  384. elif isinstance(collect_range, (list, tuple)) and len(collect_range) >= 2:
  385. start, end = collect_range[0], collect_range[1]
  386. elif isinstance(collect_range, str):
  387. matched = re.match(r"^\s*(\d+(?:\.\d+)?)\s*[-,~]\s*(\d+(?:\.\d+)?)\s*$", collect_range)
  388. if matched:
  389. start, end = matched.group(1), matched.group(2)
  390. try:
  391. start = float(start)
  392. end = float(end)
  393. except (TypeError, ValueError):
  394. return None
  395. if start < 0 or end < 0:
  396. return None
  397. if start > end:
  398. start, end = end, start
  399. return {"start": start, "end": end}
  400. @staticmethod
  401. def normalize_page_range(page_range):
  402. if not page_range:
  403. return None
  404. start = None
  405. end = None
  406. if isinstance(page_range, dict):
  407. start = page_range.get("start")
  408. end = page_range.get("end")
  409. elif isinstance(page_range, (list, tuple)) and len(page_range) >= 2:
  410. start, end = page_range[0], page_range[1]
  411. elif isinstance(page_range, str):
  412. matched = re.match(r"^\s*[\[\(]?\s*(\d+)\s*[,,\-~]\s*(\d+)\s*[\]\)]?\s*$", page_range)
  413. if matched:
  414. start, end = matched.group(1), matched.group(2)
  415. try:
  416. start = int(float(start))
  417. end = int(float(end))
  418. except (TypeError, ValueError):
  419. return None
  420. if start <= 0 or end <= 0:
  421. return None
  422. if start > end:
  423. start, end = end, start
  424. return {"start": start, "end": end}
  425. def stop_app(self):
  426. self.d.app_stop(self.package_name)
  427. time.sleep(1)
  428. def start_app(self):
  429. self.d.app_start(self.package_name)
  430. time.sleep(1)
  431. def restart_app(self):
  432. self.stop_app()
  433. self.start_app()
  434. def li_or_lo(self, key):
  435. if key == "升序":
  436. self.sort_key += 1
  437. self.d.xpath('//*[@text="价格"]').click()
  438. n = self.d.xpath('//*[@text="总价低到高"]')
  439. if n.exists:
  440. n.click()
  441. time.sleep(1)
  442. if key == "降序":
  443. self.sort_key += 1
  444. self.d.xpath('//*[@text="价格"]').click()
  445. time.sleep(2)
  446. self.d.xpath('//*[@text="价格"]').click()
  447. def wr_re(self, mod, device_id, sort=None, page=None):
  448. file_path = f'./ycwj/{device_id}_{self.title_key}.txt'
  449. if mod == "写":
  450. try:
  451. data = {
  452. "page": page if page else "",
  453. "sort": sort if sort else "",
  454. }
  455. os.makedirs(os.path.dirname(file_path), exist_ok=True)
  456. with open(file_path, 'w', encoding='utf-8') as f:
  457. json.dump(data, f, ensure_ascii=False, indent=2)
  458. print(f"进度保存成功:{sort},{page}页")
  459. except Exception as e:
  460. print("保存进度失败")
  461. elif mod == "读":
  462. try:
  463. if not os.path.exists(file_path):
  464. return None
  465. with open(file_path, 'r', encoding='utf-8') as f:
  466. data = json.load(f)
  467. print(self.sort)
  468. if self.sort and self.sort_key == 0:
  469. self.li_or_lo(self.sort)
  470. i = 0
  471. while True:
  472. if i == data['page']:
  473. self.page = data['page']
  474. print("当前页", self.page)
  475. break
  476. else:
  477. i += 1
  478. self.d.drag(300, 1400, 300, 400, 1)
  479. return data
  480. except Exception as e:
  481. print(f"读取进度失败")
  482. return None
  483. return None
  484. # 任何一个spec满足都算有效
  485. def is_link_spec_useful(self, product_title):
  486. if len(self.spec_list) == 0:
  487. return True
  488. for spec in self.spec_list:
  489. if spec in product_title:
  490. return True
  491. return False
  492. # TODO 继续优化这里的判断逻辑,可以考虑搭配config的修改
  493. def is_link_useful(self, product_title):
  494. if self.title_key != "" and self.title_key not in product_title:
  495. print(f"当前商品名称:{product_title} 不包含{self.title_key}关键字")
  496. return False
  497. if self.brand != "" and self.brand not in product_title:
  498. print(f"当前商品名称:{product_title} 不包含{self.brand}品牌")
  499. return False
  500. if not self.is_link_spec_useful(product_title):
  501. print(f"当前商品名称:{product_title} 不包含{self.spec_list}品规")
  502. return False
  503. return True
  504. @staticmethod
  505. def get_sleep_time():
  506. # return random.randint(5, 8)
  507. # return random.randint(1, 2)
  508. return 1
  509. @staticmethod
  510. def get_current_date():
  511. return datetime.datetime.now().strftime('%Y/%m/%d')
  512. @staticmethod
  513. def get_city_info():
  514. """
  515. 获取所有的省市数据
  516. :return:
  517. """
  518. file_path = '../kailin_city.json'
  519. with open(file_path, 'r', encoding='utf-8') as f:
  520. data = json.load(f)
  521. province = {province_one["id"]: province_one for province_one in data['province']}
  522. city2province = dict()
  523. city = data['city']
  524. for city_one in city:
  525. name = city_one['name']
  526. pid = city_one['pid']
  527. if len(str(pid)) > 2:
  528. pid = int(re.match('^\d{2}', str(pid)).group())
  529. city2province[name] = province[pid]['name']
  530. return city2province
  531. def get_shop_name_from_current_page(self):
  532. """
  533. 仅从当前商品详情页读取店铺名,不做任何页面跳转。
  534. """
  535. shop_name = self.get_first_text_by_xpaths([
  536. '//android.widget.ScrollView/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[last()]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[3]/android.widget.FrameLayout[1]/android.widget.TextView',
  537. '//android.widget.ScrollView/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[last()-1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[3]/android.widget.FrameLayout[1]/android.widget.TextView',
  538. ])
  539. if shop_name:
  540. print(f'获取到店铺名:{shop_name}')
  541. return shop_name
  542. def get_shop_name(self):
  543. """
  544. 获取店铺名
  545. :return:
  546. """
  547. shop_name = self.get_shop_name_from_current_page()
  548. if shop_name:
  549. return shop_name
  550. try:
  551. # 点击店铺进入后获取店铺名称
  552. print("点击店铺进入后获取店铺名称")
  553. self.enter_shop()
  554. shop_xpath = '//*[@resource-id="com.sankuai.meituan:id/layout_header_view"]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]//android.widget.FrameLayout[2]/android.widget.FrameLayout[1]/android.widget.TextView'
  555. if self.d.xpath(shop_xpath).exists:
  556. shop_name = self.d.xpath(shop_xpath).text
  557. self.swipe_back(1)
  558. return shop_name
  559. shop_name = ''
  560. return shop_name
  561. except Exception as e:
  562. print(f'获取店铺名出错:{e}')
  563. return ''
  564. def get_qualification_number(self):
  565. """
  566. 获取资质编号
  567. :return:
  568. """
  569. try:
  570. qualification_number_str = self.d.xpath(
  571. '//*[@resource-id="com.sankuai.meituan:id/mil_container"]/android.webkit.WebView[1]/android.webkit.WebView[1]/android.view.View[1]/android.view.View[1]/android.widget.TextView[2]').text
  572. qualification_number = qualification_number_str.strip('资质编号:').strip()
  573. return qualification_number
  574. except:
  575. return None
  576. def get_shop_address(self):
  577. try:
  578. shop_address_xpaths = [
  579. '//*[@resource-id="com.sankuai.meituan:id/wm_sc_drug_shop_content_mrn_container_id_2"]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.widget.ScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.widget.TextView',
  580. '//*[@resource-id="com.sankuai.meituan:id/wm_sc_drug_shop_content_mrn_container_id_2"]/android.widget.FrameLayout[1]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.widget.ScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.widget.TextView',
  581. ]
  582. shop_address = self.get_first_text_by_xpaths(shop_address_xpaths)
  583. print(f'111-获取到店铺地址:{shop_address}')
  584. if '发货时间' in shop_address:
  585. print(f'店铺地址包含发货时间,再次获取店铺地址')
  586. shop_address = self._read_xpath_text(shop_address_xpaths[1])
  587. if shop_address:
  588. print(f'222-获取到店铺地址:{shop_address}')
  589. else:
  590. print(f'222-xpath2获取店铺地址失败')
  591. print(f'333-获取到店铺地址:{shop_address}')
  592. return shop_address
  593. except:
  594. print(f'获取店铺地址出错-get_shop_address')
  595. return None
  596. def execute_db_write(self, sql, params, action_desc, max_retries=5):
  597. for attempt in range(max_retries):
  598. conn = None
  599. try:
  600. conn = get_mysql()
  601. with conn.cursor() as cur:
  602. cur.execute(sql, params)
  603. conn.commit()
  604. print(f"{action_desc}成功")
  605. return True
  606. except Exception as e:
  607. print(f'{action_desc}异常 (尝试 {attempt + 1}/{max_retries}): {e}')
  608. if conn:
  609. conn.rollback()
  610. if attempt == max_retries - 1:
  611. print(f"{action_desc}失败,达到最大重试次数")
  612. return False
  613. time.sleep(2)
  614. finally:
  615. if conn:
  616. conn.close()
  617. def query_exists(self, sql, params, error_desc):
  618. conn = None
  619. try:
  620. conn = get_mysql()
  621. with conn.cursor() as cur:
  622. cur.execute(sql, params)
  623. return bool(cur.fetchone())
  624. except Exception as e:
  625. print(f"{error_desc}错误: {str(e)}")
  626. return None
  627. finally:
  628. if conn:
  629. conn.close()
  630. def save_to_database(self, data):
  631. print(f'保存数据到数据库:{data}')
  632. add_sql = f"""
  633. INSERT INTO {self.table_name} (
  634. enterprise_id, platform_id, platform_item_id, province_id, city_id,
  635. province_name, city_name, area_info, product_name, product_specs,
  636. one_box_price, manufacture_date, expiry_date, manufacturer, approval_number,
  637. is_sold_out, online_posting_count, continuous_listing_count, link_url,
  638. store_name, store_url, shipment_province_id, shipment_province_name,
  639. shipment_city_id, shipment_city_name, company_name, qualification_number,
  640. scrape_date, min_price, number, sales, inventory, snapshot_url, insert_time
  641. ) VALUES (
  642. %s, %s, %s, %s, %s,
  643. %s, %s, %s, %s, %s,
  644. %s, %s, %s, %s, %s,
  645. %s, %s, %s, %s,
  646. %s, %s, %s, %s,
  647. %s, %s, %s, %s,
  648. %s, %s, %s, %s, %s, %s, %s
  649. )
  650. """
  651. params = (
  652. data['enterprise_id'],
  653. data['platform_id'],
  654. data['platform_item_id'],
  655. data['province_id'],
  656. data['city_id'],
  657. data['province_name'],
  658. data['city_name'],
  659. data['area_info'],
  660. data['product_name'],
  661. data['product_specs'],
  662. data['one_box_price'],
  663. data['manufacture_date'],
  664. data['expiry_date'],
  665. data['manufacturer'],
  666. data['approval_number'],
  667. data['is_sold_out'],
  668. data['online_posting_count'],
  669. data['continuous_listing_count'],
  670. data['link_url'],
  671. data['store_name'],
  672. data['store_url'],
  673. data['shipment_province_id'],
  674. data['shipment_province_name'],
  675. data['shipment_city_id'],
  676. data['shipment_city_name'],
  677. data['company_name'],
  678. data['qualification_number'],
  679. data['scrape_date'],
  680. data['min_price'],
  681. data['number'],
  682. data['sales'],
  683. data['inventory'],
  684. data['snapshot_url'],
  685. data['insert_time'],
  686. )
  687. return self.execute_db_write(add_sql, params, "保存商品数据到数据库")
  688. def save_shop_info_to_database(self, data):
  689. print(f'保存店铺数据到数据库:{data}')
  690. add_sql = f"""
  691. INSERT INTO {self.shop_table_name}
  692. (shop, contact_address, qualification_number, business_license_company, business_license_address, scrape_date, platform)
  693. VALUES (%s, %s, %s, %s, %s, %s, %s)
  694. """
  695. params = (
  696. data['shop'],
  697. data['contact_address'],
  698. data['qualification_number'],
  699. data['business_license_company'],
  700. data['business_license_address'],
  701. data['scrape_date'],
  702. data['platform'],
  703. )
  704. return self.execute_db_write(add_sql, params, "保存店铺数据到数据库")
  705. def swipe_back(self, no):
  706. """
  707. 返回
  708. :param no: 回退次数
  709. :return:
  710. """
  711. for idx in range(no):
  712. self.d.press('back')
  713. time.sleep(self.get_sleep_time())
  714. def drug_price(self):
  715. """
  716. 获取药品价格
  717. :return:
  718. """
  719. try:
  720. price_str = self.d.xpath('//*[starts-with(@text,"¥")]').text
  721. price = float(re.search(r'[\d\.]+', price_str).group())
  722. print(f'获取到价格:{price}')
  723. return price
  724. except Exception as e:
  725. print(f'提取价格出错-->{e}')
  726. return None
  727. def drug_sale_num(self):
  728. """
  729. 获取药品销量
  730. :return:
  731. """
  732. try:
  733. sales_element = self.d.xpath('//*[starts-with(@text,"已售")]')
  734. if sales_element.exists:
  735. sales_num_str = self.d.xpath('//*[starts-with(@text,"已售")]').text
  736. sales_num_str = sales_num_str.replace("已售", "").strip()
  737. # price = float(re.search(r'[\d\.]+', price_str).group())
  738. print(f'获取到已售数量:{sales_num_str}')
  739. return sales_num_str
  740. return None
  741. except Exception as e:
  742. print(f'提取已售数量出错-->{e}')
  743. return None
  744. def restart_uiautomator_services(self, device_id):
  745. """
  746. 重启atx的uiautomator 服务
  747. :param device_id:
  748. :return:
  749. """
  750. stop_uiautomator_services = f'adb -s {device_id} shell /data/local/tmp/atx-agent server -d --stop'
  751. start_uiautomator_services = f'adb -s {device_id} shell /data/local/tmp/atx-agent server -d'
  752. subprocess.run(stop_uiautomator_services, capture_output=True, text=True, shell=True)
  753. time.sleep(self.get_sleep_time())
  754. subprocess.run(start_uiautomator_services, capture_output=True, text=True, shell=True)
  755. time.sleep(self.get_sleep_time())
  756. def reconnect_device(self):
  757. """重启 atx-agent 并重新连接设备"""
  758. try:
  759. # 停止 atx-agent
  760. subprocess.run(["adb", "-s", self.device_id, "shell",
  761. "/data/local/tmp/atx-agent", "server", "-d", "--stop"],
  762. capture_output=True, timeout=5)
  763. time.sleep(1)
  764. # 启动 atx-agent
  765. subprocess.run(["adb", "-s", self.device_id, "shell",
  766. "/data/local/tmp/atx-agent", "server", "-d"],
  767. capture_output=True, timeout=5)
  768. time.sleep(2)
  769. # 重新连接 uiautomator2
  770. self.d = u2.connect_usb(self.device_id)
  771. self.restart_uiautomator_services(self.device_id)
  772. self.loggerMT.info("设备重连成功")
  773. return True
  774. except Exception as e:
  775. self.loggerMT.error(f"设备重连失败: {e}")
  776. return False
  777. def connect_devices(self, device_id):
  778. """
  779. 连接设备
  780. :return:
  781. """
  782. try:
  783. self.device_id = device_id
  784. self.d = u2.connect_usb(device_id)
  785. self.restart_uiautomator_services(device_id)
  786. self.oss_config = {
  787. "access_key_id": 'LTAI5tDwjfteBvivYN41r8sJ',
  788. "access_key_secret": 'yowuOGi2nYYnrqGpO3qcz94C4brcPp',
  789. "endpoint": "oss-cn-shenzhen.aliyuncs.com", # 例:oss-cn-beijing.aliyuncs.com
  790. "bucket_name": "zhijiayun-jiansuo",
  791. "oss_prefix": "scrape_data/" # OSS中存放截图的前缀(虚拟文件夹)
  792. }
  793. print(f'连接到设备:{device_id}')
  794. self.loggerMT.info(f'连接到设备:{device_id}')
  795. except Exception as e:
  796. print(f'{device_id} 连接错误: {e}')
  797. self.loggerMT.info(f'{device_id} 连接错误: {e}')
  798. raise Exception(e)
  799. def get_ocr_res(self, img):
  800. try:
  801. # img地址
  802. print(f'开始识别图片:{img}')
  803. request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_license"
  804. f = open(img, 'rb')
  805. img = base64.b64encode(f.read())
  806. params = {"image": img}
  807. request_url = request_url + "?access_token=" + self.access_token
  808. headers = {'content-type': 'application/x-www-form-urlencoded'}
  809. response = requests.post(request_url, data=params, headers=headers)
  810. if response:
  811. res = response.json()
  812. new_dic = dict()
  813. for ite in res['words_result'].keys():
  814. new_dic[ite] = res['words_result'][ite]['words']
  815. print('资质数据信息', new_dic)
  816. return new_dic
  817. else:
  818. return None
  819. except:
  820. return None
  821. def remove_watermark(self, img_path):
  822. """
  823. 图片去水印(将水印部分变成白色背景)并将数据转化为二进制数据
  824. :param img_path: 图片路径
  825. :return: 二进制图片数据
  826. """
  827. img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), -1)
  828. endswith = os.path.splitext(img_path)[1]
  829. new = np.clip(1.4057577998008846 * img - 38.33089999653017, 0, 255).astype(np.uint8)
  830. _, img_binary = cv2.imencode(endswith, new)
  831. return img_binary
  832. def get_ocr_res_image(self, img):
  833. try:
  834. image = self.remove_watermark(img)
  835. # image_file = open(img,'wb')
  836. # image_file.write(image)
  837. # res_image = self.client.basicAccurate(image) # 高精度
  838. res_image = self.client.basicGeneral(image)
  839. data = res_image.get('words_result', '')
  840. print(f'百度api返回结果:{data}')
  841. return data
  842. except:
  843. return None
  844. def screenshot_the_business_license(self, qualification_number):
  845. screenshot_path = 'screenshot1.png'
  846. self.d.screenshot(screenshot_path)
  847. img = cv2.imread(screenshot_path)
  848. # 指定裁剪区域 (left, top, right, bottom)
  849. left = 0
  850. top = 480
  851. right = 720
  852. bottom = 1420
  853. cropped_img = img[top:bottom, left:right]
  854. # 创建目录
  855. SCREENSHOT_DIR = Path('screenshot') # 注意这里的变化和py文件同一级目录即可
  856. SCREENSHOT_DIR.mkdir(parents=True, exist_ok=True)
  857. if qualification_number:
  858. # cropped_screenshot_path = 'D:\\work\\dfwy_spider\\drug_data\\mt\\screenshot\\' + qualification_number + '.png'
  859. cropped_screenshot_path = SCREENSHOT_DIR / f'{qualification_number}.png'
  860. else:
  861. cropped_screenshot_path = 'cropped_screenshot.png'
  862. cv2.imwrite(cropped_screenshot_path, cropped_img)
  863. return cropped_screenshot_path
  864. def screenshot_instruction(self):
  865. # 获取当前时间
  866. current_time = datetime.datetime.now()
  867. # 格式化为时分秒
  868. time_str = current_time.strftime("%H-%M-%S")
  869. # 生成随机的 8 位字符串
  870. random_str = secrets.token_hex(4) # 生成 4 个字节的随机字符串,转换为 8 位十六进制字符串
  871. print(time_str)
  872. screenshot_path = 'instructionscreenshot1-' + time_str + '-' + random_str + '.png'
  873. self.d.screenshot(screenshot_path)
  874. return screenshot_path
  875. def extract_specification(self, text):
  876. """提取药品规格信息"""
  877. # 方法1:简单去除到期信息
  878. pattern = r'^[^【]+'
  879. match = re.search(pattern, text)
  880. if match:
  881. return match.group(0).strip()
  882. return text
  883. # 获取商品title
  884. def get_title(self):
  885. def _inner():
  886. print(f'获取商品title时的搜索关键字:{self.title_key}')
  887. # 初始化
  888. drugs_name = ''
  889. specifications = ''
  890. title = ''
  891. # 循环的获取title为了有时间来处理人机验证
  892. for m in range(1, 6000):
  893. if self.d.xpath(f'//*[contains(@text, "{self.title_key}")]').exists:
  894. title = self.safe_exec(
  895. lambda: self.d.xpath(f'//*[contains(@text, "{self.title_key}")]').text
  896. )
  897. print(f"第{m}次获取title成功")
  898. break
  899. else:
  900. time.sleep(3)
  901. # return drugs_name, specifications
  902. title = title[1:] if title.startswith('0') else title
  903. print(f'获取到药品标题:{title}')
  904. # match = re.match(r'(\[[^\]]+\])(.*?)\s*((?:\d+\S*|\(.+))$', title)
  905. match = re.match(r'^(?:0?)?(?:\[([^\]]+)\])?\s*(.*?)\s*(\d+[^\s]+)$', title)
  906. if match:
  907. # drugs_name = match.group(1).strip() + match.group(2).strip()
  908. drugs_name = title
  909. specifications = match.group(3).strip()
  910. print("药品名:", drugs_name)
  911. print("规格:", specifications)
  912. # 如果品规中包含到期则需要再次的正则处理
  913. if '到期' in specifications:
  914. specifications = self.extract_specification(specifications)
  915. # print('完整药名:', drugs_name + specifications)
  916. return drugs_name, specifications
  917. else:
  918. print("没有匹配到预期格式")
  919. drugs_name = title
  920. specifications = ''
  921. return drugs_name, specifications
  922. # 用 safe_exec 包装内部逻辑,确保验证码阻塞
  923. return self.safe_exec(_inner)
  924. def enter_shop(self):
  925. """
  926. 进店,方便提取资质环境
  927. :return:
  928. """
  929. # self.d.xpath('//*[@text="进店"]').click()
  930. self.d.xpath('//*[@text="店铺"]').click()
  931. time.sleep(self.get_sleep_time())
  932. def enter_shoper(self):
  933. """
  934. 进入商家
  935. :return:
  936. """
  937. is_shoper_exists = 0
  938. for i in range(10):
  939. if self.d.xpath('//*[@text="商家"]').exists:
  940. print(f'第{i}次商家存在')
  941. is_shoper_exists = 1
  942. break
  943. else:
  944. print(f'第{i}次商家不存在')
  945. time.sleep(self.get_sleep_time())
  946. if is_shoper_exists == 1:
  947. self.d.xpath('//*[@text="商家"]').click()
  948. time.sleep(self.get_sleep_time())
  949. return True
  950. else:
  951. return False
  952. # 点击查看商家资质
  953. def scan_shoper_license(self):
  954. exist_shoper = 0
  955. for i in range(10):
  956. if self.d.xpath('//*[@text="查看商家资质"]').exists:
  957. print(f'第{i}次查看商家资质存在')
  958. exist_shoper = 1
  959. break
  960. else:
  961. print(f'第{i}次查看商家资质不存在')
  962. time.sleep(self.get_sleep_time())
  963. if exist_shoper == 1:
  964. self.d.xpath('//*[@text="查看商家资质"]').click()
  965. time.sleep(self.get_sleep_time())
  966. else:
  967. self.swipe_back(1)
  968. # 验证商品的信息是否在数据库中已存在
  969. def data_is_exists(self, data):
  970. """
  971. 检查指定数据是否已存在于数据库表中(仅检查存在性)
  972. 参数:
  973. data: 包含查询条件的字典,键为列名,值为条件值
  974. 返回:
  975. True: 数据存在
  976. False: 数据不存在
  977. None: 检查过程中出错
  978. """
  979. required_keys = ['product', 'min_price', 'shop', 'scrape_date', 'platform']
  980. if not all(key in data for key in required_keys):
  981. missing = [key for key in required_keys if key not in data]
  982. logging.error(f"缺少必要字段: {', '.join(missing)}")
  983. return None
  984. query_sql = f"""
  985. SELECT 1 FROM {self.table_name}
  986. WHERE product_name = %s
  987. AND min_price = %s
  988. AND store_name = %s
  989. AND scrape_date = %s
  990. AND platform_id = %s
  991. LIMIT 1
  992. """
  993. params = (
  994. data['product'],
  995. data['min_price'],
  996. data['shop'],
  997. data['scrape_date'],
  998. data['platform']
  999. )
  1000. return self.query_exists(query_sql, params, "商品查重")
  1001. # 验证店铺信息是否在数据库中已存在
  1002. def shop_is_exists_database(self, shop):
  1003. query_sql = f"""
  1004. SELECT 1 FROM {self.shop_table_name}
  1005. WHERE shop = %s
  1006. LIMIT 1
  1007. """
  1008. return self.query_exists(query_sql, (shop,), "店铺查重")
  1009. def wait_if_verifying(self, monitor, timeout=120):
  1010. """验证码处理期间阻塞主线程"""
  1011. start = time.time()
  1012. while monitor.pausing.is_set() and time.time() - start < timeout:
  1013. time.sleep(1)
  1014. def wait_for_ready(self, monitor, timeout=86400):
  1015. """进入每一页前都先等验证码"""
  1016. start = time.time()
  1017. while monitor.pausing.is_set() and time.time() - start < timeout:
  1018. time.sleep(1)
  1019. # 额外保险:如果验证码突然在这一秒才弹,再主动扫一次
  1020. monitor.check_and_handle_popup()
  1021. def safe_list(self, xpath, monitor):
  1022. """线程安全地拿商品列表"""
  1023. self.wait_for_ready(monitor)
  1024. return self.d.xpath(xpath).all()
  1025. def safe_exec(self, func, *args, **kwargs):
  1026. """
  1027. 万能安全壳:执行 func 前检查验证码,
  1028. 若监控线程已置位 pausing,则一直阻塞直到放行。
  1029. """
  1030. while self.monitor.pausing.is_set():
  1031. time.sleep(1)
  1032. max_retries = 3
  1033. for attempt in range(max_retries):
  1034. try:
  1035. return func(*args, **kwargs)
  1036. except http.client.RemoteDisconnected as e:
  1037. self.loggerMT.error(f"连接断开 (尝试 {attempt + 1}/{max_retries}): {e}")
  1038. if attempt == max_retries - 1:
  1039. raise # 最后一次失败,向上抛出
  1040. # 尝试重连
  1041. if self.reconnect_device():
  1042. self.loggerMT.info("重连成功,准备重试...")
  1043. time.sleep(2) # 等待设备稳定
  1044. continue
  1045. else:
  1046. self.loggerMT.error("重连失败,无法继续")
  1047. raise
  1048. except Exception as e:
  1049. # 其他异常直接抛出
  1050. raise
  1051. # 执行真正逻辑
  1052. return func(*args, **kwargs)
  1053. def get_next_data(self, data, target):
  1054. for i, item in enumerate(data):
  1055. if item['words'] == target:
  1056. if i + 1 < len(data):
  1057. return data[i + 1]['words']
  1058. return None
  1059. def delete_instruction_screenshot(self, screenshot_path):
  1060. # 删除截图文件
  1061. try:
  1062. os.remove(screenshot_path)
  1063. print(f"截图文件已删除:{screenshot_path}")
  1064. except FileNotFoundError:
  1065. print(f"文件未找到,无法删除:{screenshot_path}")
  1066. except Exception as e:
  1067. print(f"删除文件时出错:{e}")
  1068. def get_instructions_data(self):
  1069. """
  1070. 确定有说明书之后,提取所有的说明书数据
  1071. :return:
  1072. """
  1073. self.d.xpath('//*[@text="说明"]').click()
  1074. # time.sleep(random.randint(3, 5))
  1075. time.sleep(0.5)
  1076. if self.d.xpath('//*[@text="查看详细说明"]').exists:
  1077. self.d.xpath('//*[@text="查看详细说明"]').click()
  1078. else:
  1079. view_all_xpath = self.find_xpath_with_swipes(
  1080. ['//*[@text="查看全部"]'],
  1081. swipe_direction='down',
  1082. swipe_scale=0.3,
  1083. max_swipes=8,
  1084. found_desc='查看全部'
  1085. )
  1086. if view_all_xpath:
  1087. self.d.xpath(view_all_xpath).click()
  1088. else:
  1089. res_data = {
  1090. "有效期": '',
  1091. "生产单位": '',
  1092. "批准文号": ''
  1093. }
  1094. self.loggerMT.info('获取到的说明书信息为空。')
  1095. return res_data
  1096. time.sleep(0.5)
  1097. for ii in range(8):
  1098. if self.d.xpath('//*[@text="加载更多"]').exists:
  1099. self.d.xpath('//*[@text="加载更多"]').click()
  1100. time.sleep(0.2)
  1101. break
  1102. else:
  1103. self.d.swipe(200, 1000, 200, 300, 0.3)
  1104. # self.d.swipe_ext("up", scale=0.3)
  1105. for iii in range(10):
  1106. if self.d.xpath('//*[@text="生产单位"]').exists and self.d.xpath('//*[@text="批准文号"]').exists:
  1107. break
  1108. else:
  1109. self.d.swipe(200, 1300, 200, 300, 0.3)
  1110. # self.d.swipe_ext("up", scale=0.3)
  1111. instruction_path = self.screenshot_instruction()
  1112. print(f"instruction_path= {instruction_path}")
  1113. time.sleep(2)
  1114. ocr_res = self.get_ocr_res_image(instruction_path)
  1115. # print(f'ocr_res:{ocr_res}')
  1116. if ocr_res:
  1117. # 获取有效期的下一个数据
  1118. validity = self.get_next_data(ocr_res, '有效期')
  1119. # 获取批准文号的下一个数据
  1120. approval_number = self.get_next_data(ocr_res, '批准文号')
  1121. # 获取生产单位的下一个数据
  1122. manufacturer = self.get_next_data(ocr_res, '生产单位')
  1123. else:
  1124. validity = ''
  1125. approval_number = ''
  1126. manufacturer = ''
  1127. res_data = {
  1128. "有效期": validity,
  1129. "生产单位": manufacturer,
  1130. "批准文号": approval_number
  1131. }
  1132. print(f"res_data={res_data}")
  1133. time.sleep(1)
  1134. self.delete_instruction_screenshot(instruction_path)
  1135. return res_data
  1136. def has_instructions(self):
  1137. """
  1138. 是否有说明书
  1139. :return:
  1140. """
  1141. # 没有说明书的无法采集具体数据
  1142. time.sleep(self.get_sleep_time())
  1143. return bool(self.find_xpath_with_swipes(
  1144. ['//*[@text="说明"]'],
  1145. swipe_direction='down',
  1146. swipe_scale=0.3,
  1147. max_swipes=8,
  1148. found_desc='说明'
  1149. ))
  1150. def has_shop(self):
  1151. """
  1152. 是否有进店按钮
  1153. :return:
  1154. """
  1155. # self.d.swipe_ext('up', 0.1)
  1156. time.sleep(self.get_sleep_time())
  1157. is_has_enter_shop = self.d.xpath('//*[@text="进店"]').exists
  1158. return is_has_enter_shop
  1159. # 获取商品对应的店铺信息
  1160. def get_license_info_ex(self):
  1161. # self.enter_shop()
  1162. self.safe_exec(self.enter_shop)
  1163. # self.enter_shoper()
  1164. result = self.safe_exec(self.enter_shoper)
  1165. if result == False:
  1166. license_info_data = {'contact_address': '', 'qualification_number': '', 'business_license_company': '',
  1167. 'business_license_address': ''}
  1168. return license_info_data
  1169. for i in range(10):
  1170. if self.d.xpath('//*[@text="查看商家资质"]').exists:
  1171. print(f"第{i}次有商家资质")
  1172. break
  1173. else:
  1174. print(f"第{i}次没有商家资质")
  1175. time.sleep(self.get_sleep_time())
  1176. # 获取地址
  1177. # contact_address = self.get_shop_address()
  1178. contact_address = self.safe_exec(self.get_shop_address)
  1179. # time.sleep(50000)
  1180. ###
  1181. # self.scan_shoper_license()
  1182. self.safe_exec(self.scan_shoper_license)
  1183. # 获取资质编码
  1184. # qualification_number = self.get_qualification_number()
  1185. qualification_number = self.safe_exec(self.get_qualification_number)
  1186. # qualification_number 不为None继续下一步
  1187. if qualification_number:
  1188. # 营业执照公司名称
  1189. business_license_company = ''
  1190. # 营业执照地址
  1191. business_license_address = ''
  1192. self.d.click(0.603, 0.27)
  1193. time.sleep(self.get_sleep_time())
  1194. cropped_screenshot_path = self.screenshot_the_business_license(qualification_number)
  1195. print(f'cropped_screenshot_path:{cropped_screenshot_path}')
  1196. # if qualification_number:
  1197. # cropped_screenshot_path = 'D:\\work\\dfwy_spider\\drug_data\\mt\\screenshot\\' + qualification_number + '.png'
  1198. # else:
  1199. # cropped_screenshot_path = 'cropped_screenshot.png'
  1200. # ocr_res = self.get_ocr_res('cropped_screenshot.png')
  1201. ocr_res = self.get_ocr_res(cropped_screenshot_path)
  1202. print(f'ocr_res:{ocr_res}')
  1203. # 获取ocr_res 中的地址、单位名称
  1204. if ocr_res:
  1205. if '单位名称' in ocr_res.keys():
  1206. business_license_company = ocr_res['单位名称']
  1207. if '地址' in ocr_res.keys():
  1208. business_license_address = ocr_res['地址']
  1209. license_info_data = {'contact_address': contact_address, 'qualification_number': qualification_number,
  1210. 'business_license_company': business_license_company,
  1211. 'business_license_address': business_license_address}
  1212. else:
  1213. license_info_data = {'contact_address': contact_address, 'qualification_number': '',
  1214. 'business_license_company': '', 'business_license_address': ''}
  1215. return license_info_data
  1216. def distinct_target(self):
  1217. result = False
  1218. position_xpath = '//*[@resource-id="com.sankuai.meituan:id/container"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[3]'
  1219. position_xpath2 = '//*[@resource-id="com.sankuai.meituan:id/container"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[2]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[3]'
  1220. is_position = self.d.xpath(position_xpath).exists
  1221. is_position2 = self.d.xpath(position_xpath2).exists
  1222. xpath = '//*[@resource-id="com.sankuai.meituan:id/container"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.widget.ScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.support.v7.widget.RecyclerView[1]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.widget.HorizontalScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[last()]'
  1223. xpath2 = '//*[@resource-id="com.sankuai.meituan:id/container"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.widget.ScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.support.v7.widget.RecyclerView[1]/android.widget.FrameLayout[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.widget.HorizontalScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[last()]'
  1224. xpath3 = '//*[@resource-id="com.sankuai.meituan:id/container"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[2]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.support.v7.widget.RecyclerView[1]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.widget.HorizontalScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[last()]'
  1225. xpath4 = '//*[@resource-id="com.sankuai.meituan:id/container"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[2]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.support.v7.widget.RecyclerView[1]/android.widget.FrameLayout[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.widget.HorizontalScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[last()]'
  1226. is_position5 = self.d.xpath(xpath).exists
  1227. is_position6 = self.d.xpath(xpath2).exists
  1228. is_position7 = self.d.xpath(xpath3).exists
  1229. is_position8 = self.d.xpath(xpath4).exists
  1230. # print(f"is_position = {is_position}")
  1231. # print(f"is_position2 = {is_position2}")
  1232. if is_position or is_position2 or is_position5 or is_position6 or is_position7 or is_position8:
  1233. result = True
  1234. if result == False:
  1235. print("---检测没有回到列表页---")
  1236. else:
  1237. print("---检测回到了列表页---")
  1238. return result
  1239. # return is_position
  1240. def enter_target_page(self):
  1241. self.d.xpath('//*[@content-desc="看病买药"]').click()
  1242. time.sleep(self.get_sleep_time())
  1243. self.d.xpath('//*[@resource-id="com.sankuai.meituan:id/vf_search_carousel_text"]').click()
  1244. time.sleep(self.get_sleep_time())
  1245. self.d.xpath(
  1246. '//*[@resource-id="com.sankuai.meituan:id/container"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]').click()
  1247. time.sleep(1)
  1248. self.d.send_keys(self.search_key, clear=True)
  1249. time.sleep(1)
  1250. self.d.xpath('//*[@text="搜索"]').click()
  1251. time.sleep(1)
  1252. self.click_express_send()
  1253. time.sleep(1)
  1254. self.wr_re("读", self.device_id)
  1255. def click_express_send(self):
  1256. # xpath= '//*[@resource-id="com.sankuai.meituan:id/container"]//android.widget.HorizontalScrollView[last()]'
  1257. slide_xpaths = [
  1258. '//*[@resource-id="com.sankuai.meituan:id/container"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.widget.ScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.support.v7.widget.RecyclerView[1]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.widget.HorizontalScrollView[1]',
  1259. '//*[@resource-id="com.sankuai.meituan:id/container"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.widget.ScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.support.v7.widget.RecyclerView[1]/android.widget.FrameLayout[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.widget.HorizontalScrollView[1]',
  1260. '//*[@resource-id="com.sankuai.meituan:id/container"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[2]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.support.v7.widget.RecyclerView[1]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.widget.HorizontalScrollView[1]',
  1261. '//*[@resource-id="com.sankuai.meituan:id/container"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[2]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.support.v7.widget.RecyclerView[1]/android.widget.FrameLayout[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.widget.HorizontalScrollView[1]',
  1262. ]
  1263. for i in range(1, 3):
  1264. matched_slide_xpath = self.get_first_existing_xpath(slide_xpaths)
  1265. if not matched_slide_xpath:
  1266. time.sleep(self.get_sleep_time())
  1267. continue
  1268. bounds = self.d.xpath(matched_slide_xpath).info['bounds']
  1269. top = bounds['top']
  1270. bottom = bounds['bottom']
  1271. print(f'top={top}')
  1272. print(f'bottom={bottom}')
  1273. y = (top + bottom) // 2
  1274. print(f'y={y}')
  1275. self.loggerMT.info(f'开始滑动{i}')
  1276. self.d.swipe(500, y, 100, y, 0.5)
  1277. time.sleep(self.get_sleep_time())
  1278. break
  1279. express_send_xpaths = [
  1280. '//*[@resource-id="com.sankuai.meituan:id/container"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.widget.ScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.support.v7.widget.RecyclerView[1]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.widget.HorizontalScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[last()]',
  1281. '//*[@resource-id="com.sankuai.meituan:id/container"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.widget.ScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.support.v7.widget.RecyclerView[1]/android.widget.FrameLayout[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.widget.HorizontalScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[last()]',
  1282. '//*[@resource-id="com.sankuai.meituan:id/container"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[2]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.support.v7.widget.RecyclerView[1]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.widget.HorizontalScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[last()]',
  1283. '//*[@resource-id="com.sankuai.meituan:id/container"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[2]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.support.v7.widget.RecyclerView[1]/android.widget.FrameLayout[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.widget.HorizontalScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[last()]',
  1284. '//*[@resource-id="com.sankuai.meituan:id/container"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[2]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/androidx.recyclerview.widget.RecyclerView[1]/android.widget.FrameLayout[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[3]/android.view.ViewGroup[1]',
  1285. ]
  1286. self.click_candidate_xpaths(
  1287. express_send_xpaths,
  1288. action_desc="点击快递送",
  1289. max_retries=5,
  1290. sleep_after=self.get_sleep_time(),
  1291. )
  1292. def get_clipboard(self):
  1293. time.sleep(1)
  1294. self.loggerMT.info(f"Clipboard content:{self.d.clipboard}") # 打印调试信息
  1295. clipboard_content = self.d.clipboard
  1296. if clipboard_content is None:
  1297. return ''
  1298. return clipboard_content.strip()
  1299. # return self.d.clipboard.strip()
  1300. def clear_clipboard(self):
  1301. self.d.set_clipboard("", "text/plain")
  1302. def get_product_link(self):
  1303. product_link = ''
  1304. dots_xpaths = [
  1305. '//*[@resource-id="com.sankuai.meituan:id/container"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]/android.view.ViewGroup[3]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.widget.ImageView[1]',
  1306. '//*[@resource-id="com.sankuai.meituan:id/container"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]/android.view.ViewGroup[3]/android.view.ViewGroup[2]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.widget.ImageView[1]',
  1307. '//*[@resource-id="com.sankuai.meituan:id/container"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.FrameLayout[3]/android.widget.FrameLayout[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.widget.ImageView[1]'
  1308. ]
  1309. max_retry = 5 # 最多尝试次数
  1310. for idx in range(1, max_retry + 1):
  1311. if product_link: # 已经拿到则退出
  1312. break
  1313. clicked_xpath = self.click_candidate_xpaths(
  1314. dots_xpaths,
  1315. action_desc=f'{idx}-进入分享点点点',
  1316. max_retries=1,
  1317. sleep_after=0.2,
  1318. )
  1319. if not clicked_xpath:
  1320. print(f'{idx}-分享入口点击失败')
  1321. time.sleep(self.get_sleep_time())
  1322. continue
  1323. self.loggerMT.info(f'{idx}-click_exists')
  1324. self.d.xpath('//*[@text="分享商品"]').click_exists()
  1325. time.sleep(0.2)
  1326. link_xpath = '//*[@text="复制链接"]'
  1327. if self.d.xpath(link_xpath).exists:
  1328. self.loggerMT.info(f'{idx}-link_xpath click')
  1329. self.d.xpath(link_xpath).click()
  1330. time.sleep(1)
  1331. product_link = self.get_clipboard()
  1332. time.sleep(0.5)
  1333. print(f'{idx}-商品链接:{product_link}')
  1334. self.loggerMT.info(f'{idx}-商品链接:{product_link}')
  1335. break
  1336. print(f'{idx}-商品链接:{product_link}')
  1337. self.loggerMT.info(f'{idx}-商品链接:{product_link}')
  1338. product_link = ''
  1339. if not product_link and idx < max_retry:
  1340. time.sleep(0.5) # 最后一次不需要再等待
  1341. return product_link
  1342. def run_parallel_tasks(self, task_map):
  1343. """
  1344. 并行执行相互独立的只读任务。
  1345. 任务本身不能包含点击、滑动、返回等会改变页面状态的操作。
  1346. """
  1347. if not task_map:
  1348. return {}
  1349. results = {}
  1350. with ThreadPoolExecutor(max_workers=len(task_map)) as executor:
  1351. future_map = {
  1352. task_name: executor.submit(self.safe_exec, task_func)
  1353. for task_name, task_func in task_map.items()
  1354. }
  1355. for task_name, future in future_map.items():
  1356. try:
  1357. results[task_name] = future.result()
  1358. except Exception as e:
  1359. print(f'并行采集任务 {task_name} 执行失败: {e}')
  1360. results[task_name] = None
  1361. return results
  1362. def get_available_xpaths(self, xpaths):
  1363. check_tasks = {
  1364. f'xpath_{idx}': (lambda xp=xp: self.d.xpath(xp).exists)
  1365. for idx, xp in enumerate(xpaths)
  1366. }
  1367. exists_results = self.run_parallel_tasks(check_tasks)
  1368. return [
  1369. xpath for idx, xpath in enumerate(xpaths)
  1370. if exists_results.get(f'xpath_{idx}')
  1371. ]
  1372. def get_first_existing_xpath(self, xpaths):
  1373. available_xpaths = self.get_available_xpaths(xpaths)
  1374. if not available_xpaths:
  1375. return None
  1376. return available_xpaths[0]
  1377. def get_first_text_by_xpaths(self, xpaths):
  1378. text_tasks = {
  1379. f'xpath_{idx}': (lambda xp=xp: self._read_xpath_text(xp))
  1380. for idx, xp in enumerate(xpaths)
  1381. }
  1382. text_results = self.run_parallel_tasks(text_tasks)
  1383. for idx, _ in enumerate(xpaths):
  1384. text = text_results.get(f'xpath_{idx}')
  1385. if text:
  1386. return text
  1387. return ''
  1388. def get_first_texts_by_xpath_groups(self, xpath_groups):
  1389. tasks = {}
  1390. group_keys = {}
  1391. for group_name, xpaths in xpath_groups.items():
  1392. group_keys[group_name] = []
  1393. for idx, xpath in enumerate(xpaths):
  1394. task_name = f'{group_name}_{idx}'
  1395. group_keys[group_name].append(task_name)
  1396. tasks[task_name] = (lambda xp=xpath: self._read_xpath_text(xp))
  1397. text_results = self.run_parallel_tasks(tasks)
  1398. grouped_results = {}
  1399. for group_name, task_names in group_keys.items():
  1400. grouped_results[group_name] = ''
  1401. for task_name in task_names:
  1402. text = text_results.get(task_name)
  1403. if text:
  1404. grouped_results[group_name] = text
  1405. break
  1406. return grouped_results
  1407. def _read_xpath_text(self, xpath):
  1408. selector = self.d.xpath(xpath)
  1409. if not selector.exists:
  1410. return ''
  1411. try:
  1412. text = selector.text
  1413. return text.strip() if isinstance(text, str) else text
  1414. except Exception:
  1415. return ''
  1416. def click_candidate_xpaths(self, xpaths, action_desc, max_retries=1, sleep_after=0):
  1417. for attempt in range(1, max_retries + 1):
  1418. available_xpaths = self.get_available_xpaths(xpaths)
  1419. if not available_xpaths:
  1420. print(f'{action_desc}失败,第{attempt}次没有匹配到可点击的xpath')
  1421. time.sleep(self.get_sleep_time())
  1422. continue
  1423. rotate_offset = (attempt - 1) % len(available_xpaths)
  1424. candidate_xpaths = available_xpaths[rotate_offset:] + available_xpaths[:rotate_offset]
  1425. for xpath in candidate_xpaths:
  1426. try:
  1427. self.safe_exec(lambda xp=xpath: self.d.xpath(xp).click())
  1428. print(f'{action_desc}成功')
  1429. if sleep_after:
  1430. time.sleep(sleep_after)
  1431. return xpath
  1432. except Exception as e:
  1433. print(f'{action_desc}点击异常: {e}')
  1434. time.sleep(self.get_sleep_time())
  1435. return None
  1436. def find_xpath_with_swipes(self, xpaths, swipe_direction='down', swipe_scale=0.3, max_swipes=8, found_desc=''):
  1437. for idx in range(max_swipes):
  1438. matched_xpath = self.get_first_existing_xpath(xpaths)
  1439. if matched_xpath:
  1440. if found_desc:
  1441. print(f'第{idx}次找到{found_desc}')
  1442. return matched_xpath
  1443. self.d.swipe_ext(swipe_direction, swipe_scale)
  1444. time.sleep(1)
  1445. matched_xpath = self.get_first_existing_xpath(xpaths)
  1446. if matched_xpath and found_desc:
  1447. print(f'第{max_swipes}次找到{found_desc}')
  1448. return matched_xpath
  1449. def build_dup_data(self, product, min_price, shop, scrape_date):
  1450. return {
  1451. 'product': product,
  1452. 'min_price': min_price,
  1453. 'shop': shop,
  1454. 'scrape_date': scrape_date,
  1455. 'platform': '4',
  1456. }
  1457. def integrate_data(self):
  1458. """
  1459. 整合数据
  1460. :return:
  1461. """
  1462. # title_info = self.get_title() # 药品,规格
  1463. # title_info = self.safe_exec(self.get_title) # 药品,规格
  1464. product, specifications = self.safe_exec(self.get_title) # 药品,规格
  1465. if not product:
  1466. self.swipe_back(1)
  1467. return
  1468. page_data = self.run_parallel_tasks({
  1469. "min_price": self.drug_price,
  1470. "sales_num": self.drug_sale_num,
  1471. "is_self_operated": lambda: self.d.xpath('//*[@text="自营"]').exists,
  1472. })
  1473. min_price = page_data.get("min_price") # 最低价格
  1474. sales_num = page_data.get("sales_num") # 销售数量
  1475. product_link = ''
  1476. if page_data.get("is_self_operated"):
  1477. shop = "美团自营大药房(快递电商)"
  1478. # 爬取日期
  1479. scrape_date = self.get_current_date()
  1480. dup_data = self.build_dup_data(product, min_price, shop, scrape_date)
  1481. print(f'当前数据:{dup_data}')
  1482. if self.data_is_exists(dup_data):
  1483. print('存在相同数据不入库')
  1484. self.back_to_list_page()
  1485. return
  1486. else:
  1487. self.find_xpath_with_swipes(
  1488. ['//*[@text="进店"]'],
  1489. swipe_direction='up',
  1490. swipe_scale=0.3,
  1491. max_swipes=8,
  1492. found_desc='进店'
  1493. )
  1494. shop_page_data = self.run_parallel_tasks({
  1495. "shop": self.get_shop_name_from_current_page,
  1496. "is_has_enter_shop": self.has_shop,
  1497. })
  1498. shop = shop_page_data.get("shop")
  1499. if not shop:
  1500. shop = self.get_shop_name()
  1501. # 爬取日期
  1502. scrape_date = self.get_current_date()
  1503. dup_data = self.build_dup_data(product, min_price, shop, scrape_date)
  1504. print(f'当前数据:{dup_data}')
  1505. if not shop:
  1506. print('未获取到店铺名:开始回退')
  1507. self.back_to_list_page()
  1508. return
  1509. if '自营' in shop:
  1510. self.back_to_list_page()
  1511. return
  1512. db_check_results = self.run_parallel_tasks({
  1513. "dup_exists": lambda: self.data_is_exists(dup_data),
  1514. "shop_exists": lambda: self.shop_is_exists_database(shop),
  1515. })
  1516. if db_check_results.get("dup_exists"):
  1517. print('存在相同数据不入库')
  1518. self.back_to_list_page()
  1519. return
  1520. # 获取店铺信息开始
  1521. is_has_enter_shop = bool(shop_page_data.get("is_has_enter_shop"))
  1522. # 需要判断shop是否已经在数据库中存在,如果存在,则不再进入店铺,直接进入下一个商品
  1523. shop_is_exists = bool(db_check_results.get("shop_exists"))
  1524. # 存在进店 并且店铺的名称不包含美团官方的字样
  1525. print(f"已采集{self.shop_data_num}家店铺数据")
  1526. if is_has_enter_shop and '美团官方' not in shop and '美团自营' not in shop and not shop_is_exists and self.shop_data_num < 500:
  1527. license_info = self.safe_exec(self.get_license_info_ex)
  1528. contact_address = license_info['contact_address']
  1529. qualification_number = license_info['qualification_number']
  1530. business_license_company = license_info['business_license_company']
  1531. business_license_address = license_info['business_license_address']
  1532. save_shop_data = {
  1533. 'shop': shop,
  1534. 'contact_address': contact_address,
  1535. 'qualification_number': qualification_number,
  1536. 'scrape_date': scrape_date,
  1537. 'business_license_company': business_license_company,
  1538. 'business_license_address': business_license_address,
  1539. 'platform': '4'
  1540. }
  1541. self.save_shop_info_to_database(save_shop_data)
  1542. self.shop_data_num += 1
  1543. self.swipe_back(2)
  1544. else:
  1545. print('不采集店铺信息')
  1546. # 获取店铺信息结束
  1547. # 商品链接
  1548. product_link = self.get_product_link()
  1549. print(f'获取到product_link: {product_link}')
  1550. time.sleep(self.get_sleep_time())
  1551. # 生产日期为空
  1552. manufacture_date = ''
  1553. expiry_date = ''
  1554. manufacturer = ''
  1555. approval_number = ''
  1556. # 暂时不获取说明书信息 start
  1557. is_has_instructions = self.safe_exec(self.has_instructions)
  1558. # 说明书等信息
  1559. if is_has_instructions:
  1560. print('开始获取说明书信息')
  1561. instructions_info = self.safe_exec(self.get_instructions_data)
  1562. if instructions_info['有效期'] is not None:
  1563. expiry_date = instructions_info['有效期'].strip('。')
  1564. if instructions_info['生产单位'] is not None:
  1565. manufacturer = instructions_info['生产单位'].strip('。')
  1566. if instructions_info['批准文号'] is not None:
  1567. approval_number = instructions_info['批准文号'].strip('。')
  1568. else:
  1569. expiry_date = "未知"
  1570. manufacturer = None
  1571. approval_number = None
  1572. province_id = 0
  1573. city_id = 0
  1574. city = ''
  1575. province = ''
  1576. if province in self.city_to_name:
  1577. province_id = self.city_to_name[province]
  1578. if city in self.city_to_name:
  1579. city_id = self.city_to_name[city]
  1580. save_data = {
  1581. 'enterprise_id': 3,
  1582. 'platform_id': 4,
  1583. 'platform_item_id': '',
  1584. 'province_id': province_id,
  1585. 'city_id': city_id,
  1586. 'province_name': '',
  1587. 'city_name': '',
  1588. 'area_info': "",
  1589. 'product_name': product,
  1590. 'product_specs': specifications,
  1591. 'one_box_price': 0.00,
  1592. 'manufacture_date': manufacture_date,
  1593. 'expiry_date': expiry_date,
  1594. 'manufacturer': manufacturer,
  1595. 'approval_number': approval_number,
  1596. 'is_sold_out': 0,
  1597. 'online_posting_count': 1,
  1598. 'continuous_listing_count': 1,
  1599. 'link_url': product_link,
  1600. 'store_name': shop,
  1601. 'store_url': '',
  1602. 'shipment_province_id': 0,
  1603. 'shipment_province_name': "",
  1604. 'shipment_city_id': 0,
  1605. 'shipment_city_name': "",
  1606. 'company_name': "",
  1607. 'qualification_number': "",
  1608. 'scrape_date': scrape_date,
  1609. 'min_price': min_price,
  1610. 'number': 0,
  1611. 'sales': sales_num,
  1612. 'inventory': "",
  1613. 'snapshot_url': "",
  1614. 'insert_time': time.strftime('%Y-%m-%d %H:%M:%S'),
  1615. 'update_time': time.strftime('%Y-%m-%d %H:%M:%S'),
  1616. }
  1617. self.save_to_database(save_data)
  1618. def back_to_list_page(self):
  1619. for i in range(5):
  1620. if self.distinct_target():
  1621. return True
  1622. print(f'第{i}次尝试退回到列表页')
  1623. self.swipe_back(1)
  1624. time.sleep(self.get_sleep_time())
  1625. print('页面出错,没有退回到列表页')
  1626. return False
  1627. def reset_collection_cursor(self):
  1628. self.collection_cursor["page_no"] = 1
  1629. self.collection_cursor["item_index"] = 0
  1630. def get_current_page_no(self):
  1631. return self.page + self.collection_cursor["page_no"]
  1632. def jump_to_page(self, target_page):
  1633. current_page = self.get_current_page_no()
  1634. if target_page <= current_page:
  1635. return
  1636. while current_page < target_page:
  1637. if self.d.xpath('//*[@text="已经到底啦"]').exists:
  1638. print(f"列表实际页数不足,当前停留在第{current_page}页,无法跳转到第{target_page}页")
  1639. return
  1640. print(f"跳过第{current_page}页,前往第{current_page + 1}页")
  1641. self.d.drag(300, 1400, 300, 400, 1)
  1642. time.sleep(1)
  1643. self.collection_cursor["page_no"] += 1
  1644. self.collection_cursor["item_index"] = 0
  1645. current_page = self.get_current_page_no()
  1646. def move_to_page_range_start(self):
  1647. if not self.page_range:
  1648. return
  1649. start_page = self.page_range["start"]
  1650. current_page = self.get_current_page_no()
  1651. if current_page < start_page:
  1652. self.jump_to_page(start_page)
  1653. def start_collection_app(self):
  1654. self.sort_key = 0
  1655. self.restart_app()
  1656. def open_product_list_page(self):
  1657. self.safe_exec(self.enter_target_page)
  1658. self.reset_collection_cursor()
  1659. if self.sort and self.sort_key == 0:
  1660. self.li_or_lo(self.sort)
  1661. self.move_to_page_range_start()
  1662. def handle_workflow_error(self, step_name):
  1663. action = self.workflow_error_action.get(step_name)
  1664. if action == "back_to_list_page":
  1665. if not self.back_to_list_page():
  1666. raise RuntimeError("退回列表页失败")
  1667. return "collect_single_product"
  1668. if action == "open_product_list_page":
  1669. return "open_product_list_page"
  1670. if action == "start_app":
  1671. return "start_app"
  1672. raise RuntimeError(f"未配置步骤 {step_name} 的错误处理动作")
  1673. def get_list_items(self):
  1674. for _ in range(10):
  1675. items = self.safe_exec(
  1676. self.d.xpath('//android.support.v7.widget.RecyclerView/android.widget.FrameLayout').all
  1677. )
  1678. if items:
  1679. return items
  1680. time.sleep(1)
  1681. raise RuntimeError("列表页商品加载失败")
  1682. def move_to_next_list_page(self):
  1683. current_page = self.get_current_page_no()
  1684. if self.page_range and current_page >= self.page_range["end"]:
  1685. self.wr_re("写", self.device_id, self.sort, current_page)
  1686. print(f'已完成第{current_page}页采集,达到结束页{self.page_range["end"]},停止采集')
  1687. return False
  1688. if self.d.xpath('//*[@text="已经到底啦"]').exists:
  1689. return False
  1690. self.wr_re("写", self.device_id, self.sort, current_page)
  1691. print(f'当前第{current_page}页采集完成,开始滑动到下一页')
  1692. self.d.drag(300, 1400, 300, 400, 1)
  1693. time.sleep(1)
  1694. self.collection_cursor["page_no"] += 1
  1695. self.collection_cursor["item_index"] = 0
  1696. return True
  1697. def _collect_list_item(self, drug_idx, drug_one):
  1698. bounds = drug_one.info['bounds']
  1699. top = bounds['top']
  1700. bottom = bounds['bottom']
  1701. print(f'当前商品bottom:{bottom}')
  1702. print(f'当前商品top:{top}')
  1703. if not (304 <= top and bottom <= 1475):
  1704. return "skip"
  1705. print(f"这页的第几个商品:{drug_idx}")
  1706. item_text_data = self.get_first_texts_by_xpath_groups({
  1707. "product_title": [
  1708. f'//android.support.v7.widget.RecyclerView/android.widget.FrameLayout[{drug_idx}]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.widget.FrameLayout[1]/android.widget.TextView',
  1709. f'//android.support.v7.widget.RecyclerView/android.widget.FrameLayout[{drug_idx}]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.widget.FrameLayout[1]/android.widget.TextView',
  1710. ],
  1711. "price_str": [
  1712. f'//android.support.v7.widget.RecyclerView/android.widget.FrameLayout[{drug_idx}]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.widget.FrameLayout[1]/android.widget.TextView',
  1713. f'//android.support.v7.widget.RecyclerView/android.widget.FrameLayout[{drug_idx}]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.widget.FrameLayout[1]/android.widget.TextView',
  1714. f'//android.support.v7.widget.RecyclerView/android.widget.FrameLayout[{drug_idx}]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.widget.FrameLayout[1]/android.widget.TextView',
  1715. f'//android.support.v7.widget.RecyclerView/android.widget.FrameLayout[{drug_idx}]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.widget.FrameLayout[1]/android.widget.TextView',
  1716. ],
  1717. "shop_name": [
  1718. f'//android.support.v7.widget.RecyclerView/android.widget.FrameLayout[{drug_idx}]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[2]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.widget.FrameLayout[last()]/android.widget.TextView[1]',
  1719. f'//android.support.v7.widget.RecyclerView/android.widget.FrameLayout[{drug_idx}]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[2]/android.view.ViewGroup[2]/android.view.ViewGroup[2]/android.view.ViewGroup[1]/android.widget.FrameLayout[last()]/android.widget.TextView[1]',
  1720. ],
  1721. })
  1722. product_title = item_text_data.get("product_title", "")
  1723. if not product_title:
  1724. print("列表当前商品名称不存在")
  1725. self.unrelated_data += 1
  1726. return "continue"
  1727. product_title = product_title[1:] if product_title.startswith('0') else product_title
  1728. print(f"列表当前商品名称:{product_title}")
  1729. if not self.is_link_useful(product_title):
  1730. print(f"is_link_useful 没通过:{product_title}")
  1731. self.unrelated_data += 1
  1732. return "continue"
  1733. self.unrelated_data = 0
  1734. price = ''
  1735. price_str = item_text_data.get("price_str", "")
  1736. print(f"列表当前商品价格:{price_str}")
  1737. if price_str:
  1738. price = float(re.search(r'[\d\.]+', price_str).group())
  1739. if price != '' and self.collect_range:
  1740. range_start = self.collect_range["start"]
  1741. range_end = self.collect_range["end"]
  1742. if not (range_start <= price <= range_end):
  1743. print(f"price {price} not in range {range_start}-{range_end}, skip")
  1744. return "continue"
  1745. shop_name = item_text_data.get("shop_name", "")
  1746. print(f"列表当前商品店铺名称:{shop_name}")
  1747. if price == '' or shop_name == '':
  1748. print("列表当前商品价格或店铺名称不存在")
  1749. return "continue"
  1750. scrape_date = self.get_current_date()
  1751. dup_data = {
  1752. 'product': product_title,
  1753. 'min_price': price,
  1754. 'shop': shop_name,
  1755. 'scrape_date': scrape_date,
  1756. 'platform': '4',
  1757. }
  1758. if self.data_is_exists(dup_data):
  1759. print('列表存在相同数据不入库')
  1760. return "continue"
  1761. self.safe_exec(drug_one.click)
  1762. print('点击目标药品完毕')
  1763. time.sleep(1)
  1764. self.safe_exec(self.integrate_data)
  1765. print('integrate_data结束')
  1766. time.sleep(1)
  1767. return "collected"
  1768. def collect_single_product(self):
  1769. if self.monitor.verification_count >= self.monitor.MAX_VERIFICATION_RETRY:
  1770. raise RuntimeError("验证码触发过多,暂停程序")
  1771. if self.page_range:
  1772. self.move_to_page_range_start()
  1773. current_page = self.get_current_page_no()
  1774. if current_page > self.page_range["end"]:
  1775. print(f"当前已在第{current_page}页,超过结束页{self.page_range['end']},停止采集")
  1776. return False
  1777. items = self.get_list_items()
  1778. print(f'当前第{self.get_current_page_no()}页,共有{len(items)}个商品')
  1779. while self.collection_cursor["item_index"] < len(items):
  1780. item_index = self.collection_cursor["item_index"]
  1781. self.collection_cursor["item_index"] += 1
  1782. result = self._collect_list_item(item_index + 1, items[item_index])
  1783. if result in {"continue", "collected"}:
  1784. self.back_to_list_page()
  1785. return True
  1786. if not self.move_to_next_list_page():
  1787. print('已经到达列表页最底部')
  1788. return False
  1789. return True
  1790. def execute_workflow_step(self, step_name):
  1791. if step_name == "start_app":
  1792. self.safe_exec(self.start_collection_app)
  1793. return "open_product_list_page"
  1794. if step_name == "open_product_list_page":
  1795. self.safe_exec(self.open_product_list_page)
  1796. return "collect_single_product"
  1797. if step_name == "collect_single_product":
  1798. has_next = self.safe_exec(self.collect_single_product)
  1799. if not has_next:
  1800. return None
  1801. print('目前连续无关数据量: ', self.unrelated_data)
  1802. if self.unrelated_data > self.max_unrelated_data:
  1803. print(f"连续超过{self.max_unrelated_data}个不达标的数据则停止采集")
  1804. return None
  1805. return "collect_single_product"
  1806. raise RuntimeError(f"未知流程步骤: {step_name}")
  1807. def main(self, device_id):
  1808. self.device_id = device_id
  1809. self.connect_devices(device_id)
  1810. time.sleep(self.get_sleep_time())
  1811. self.monitor = SpiderMonitor(self)
  1812. self.monitor.start()
  1813. current_step = "start_app"
  1814. step_failures = {step: 0 for step in self.workflow_retry_limit}
  1815. try:
  1816. while current_step:
  1817. try:
  1818. next_step = self.execute_workflow_step(current_step)
  1819. step_failures[current_step] = 0
  1820. current_step = next_step
  1821. except Exception as e:
  1822. print(f'{current_step} 执行异常: {e}')
  1823. time.sleep(5)
  1824. step_failures[current_step] += 1
  1825. if step_failures[current_step] > self.workflow_retry_limit[current_step]:
  1826. raise
  1827. current_step = self.handle_workflow_error(current_step)
  1828. finally:
  1829. self.monitor.stop()
  1830. self.monitor.join()
  1831. device_list = {
  1832. "U8ONIJJJS4CELVD6": [
  1833. {
  1834. "search_key": "喇叭牌正露丸 100粒",
  1835. "title_key": "正露丸",
  1836. "spec_list": [""],
  1837. "brand": "喇叭牌",
  1838. "sort": "升序",
  1839. "collect_range": [],
  1840. "page_range": [],
  1841. "workflow_retry_limit": {
  1842. "start_app": 3,
  1843. "open_product_list_page": 3,
  1844. "collect_single_product": 3,
  1845. },
  1846. "workflow_error_action": {
  1847. "start_app": "start_app",
  1848. "open_product_list_page": "start_app",
  1849. "collect_single_product": "back_to_list_page",
  1850. },
  1851. },
  1852. ],
  1853. }
  1854. def run_device(device_id):
  1855. """单个设备的采集任务(运行于独立线程)"""
  1856. if device_id not in device_list:
  1857. logging.error(f"设备id没有配置: {device_id}")
  1858. return
  1859. tasks = device_list[device_id]
  1860. logging.info(f"[设备 {device_id}] 开始执行,共 {len(tasks)} 个任务")
  1861. for task in tasks:
  1862. cycle_no = 0
  1863. while True:
  1864. cycle_no += 1
  1865. mt = None
  1866. logging.info(f'[设备 {device_id}] ========== {task["search_key"]} 第 {cycle_no} 轮采集开始 ==========')
  1867. try:
  1868. # 注意:MT类需要从外部导入或定义,此处假设已存在
  1869. mt = MT(
  1870. task["search_key"],
  1871. task["title_key"],
  1872. task["spec_list"],
  1873. task["brand"],
  1874. task.get("sort"),
  1875. task.get("collect_range"),
  1876. task.get("page_range"),
  1877. task.get("workflow_retry_limit"),
  1878. task.get("workflow_error_action"),
  1879. )
  1880. mt.main(device_id)
  1881. logging.info(f'[设备 {device_id}] 关键字 {task["search_key"]} 本轮采集完成')
  1882. break # 成功则跳出重试循环
  1883. except Exception as e:
  1884. logging.exception(f'[设备 {device_id}] 关键字 {task["search_key"]} 采集异常:{e}')
  1885. # 发生异常后继续循环重试
  1886. finally:
  1887. if mt and hasattr(mt, 'close'):
  1888. mt.close()
  1889. logging.info(f"[设备 {device_id}] 所有任务执行完毕")
  1890. def main():
  1891. # 配置日志格式,便于区分不同线程的输出
  1892. logging.basicConfig(
  1893. level=logging.INFO,
  1894. format='%(asctime)s [%(threadName)s] %(levelname)s: %(message)s'
  1895. )
  1896. # 获取需要运行的设备ID列表
  1897. if len(sys.argv) < 2:
  1898. # 无参数时运行所有已配置的设备
  1899. device_ids = list(device_list.keys())
  1900. logging.info(f"未指定设备ID,将运行所有已配置设备: {device_ids}")
  1901. else:
  1902. # 有参数时仅运行指定的设备ID(支持多个)
  1903. device_ids = sys.argv[1:]
  1904. # 验证设备ID是否存在
  1905. invalid_ids = [did for did in device_ids if did not in device_list]
  1906. if invalid_ids:
  1907. logging.error(f"以下设备ID未配置: {invalid_ids}")
  1908. return
  1909. logging.info(f"将运行指定的设备: {device_ids}")
  1910. if not device_ids:
  1911. logging.warning("没有可运行的设备")
  1912. return
  1913. # 使用线程池并发运行多个设备(也可手动创建Thread,线程池更简洁)
  1914. with ThreadPoolExecutor(max_workers=len(device_ids)) as executor:
  1915. # 提交每个设备的任务
  1916. futures = [executor.submit(run_device, did) for did in device_ids]
  1917. # 等待所有完成
  1918. for future in futures:
  1919. future.result() # 如果有异常会向上抛出
  1920. if __name__ == '__main__':
  1921. main()