mt_x3.py 123 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487
  1. import requests
  2. import base64
  3. import cv2
  4. import uiautomator2 as u2
  5. import time
  6. import subprocess
  7. import re
  8. import random
  9. import datetime
  10. import json
  11. from aip import AipOcr
  12. from apscheduler.schedulers.blocking import BlockingScheduler
  13. # from db_mysql import mysqlClient
  14. import threading
  15. from collections import deque
  16. import numpy as np
  17. import secrets
  18. import os
  19. import oss2
  20. import urllib.parse
  21. # import pyperclip
  22. from config import Config
  23. from logger import setup_logger
  24. import logging
  25. # from database import MySQLClient
  26. from PIL import Image
  27. from pathlib import Path
  28. from PIL import Image, ImageDraw, ImageFont
  29. # 配置日志
  30. # logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  31. setup_logger("mt_spider") # 初始化日志
  32. class SpiderMonitor(threading.Thread):
  33. """全局弹窗监控线程(增强版)"""
  34. def __init__(self, spider_instance):
  35. super().__init__(daemon=True)
  36. self.spider = spider_instance
  37. self.running = True
  38. self.pausing = threading.Event() # 主线程同步事件
  39. self.last_verification_time = 0
  40. self.verification_count = 0
  41. self.MAX_VERIFICATION_RETRY = 10
  42. self.recent_clicks = deque(maxlen=10) # 防重复点击
  43. self.logger = logging.getLogger("SpiderMonitor")
  44. # 可配置化弹窗规则
  45. self.popup_rules = {
  46. "simple": [
  47. ('//*[@text="确定"]', "点击确定"),
  48. ('//*[@text="允许"]', "点击允许"),
  49. ('//*[@text="关闭"]', "点击关闭"),
  50. ('//*[@resource-id="com.sankuai.meituan:id/close"]', "关闭按钮"),
  51. ('//*[@resource-id="com.sankuai.meituan:id/address_center_location_close"]', "关闭按钮"),
  52. ('//*[@resource-id="com.sankuai.meituan:id/location_close"]', "关闭按钮"),
  53. ('//*[@resource-id="com.sankuai.meituan:id/btn_close"]', "关闭按钮"),
  54. ],
  55. "verification": [
  56. '//*[contains(@text, "验证")]',
  57. '//*[contains(@text, "滑块")]',
  58. '//*[contains(@text, "依次点击")]',
  59. '//*[contains(@text, "请点击")]',
  60. '//*[contains(@text, "拖动滑块刚")]', # 这个需要拖动滑块至最右边,然后再截图
  61. '//*[contains(@text, "请输入图片中的内容")]',
  62. '//*[contains(@text, "用最短线连接")]',
  63. '//*[contains(@text, "请按语序依次点击")]',
  64. '//*[contains(@text, "请向右滑动滑块")]',
  65. '//*[contains(@text, "请拖动下方滑块完成拼图")]',
  66. '//*[contains(@resource-id, "captcha")]'
  67. ]
  68. }
  69. def run(self):
  70. while self.running:
  71. try:
  72. handled = self.check_and_handle_popup()
  73. time.sleep(2 if handled else 1)
  74. except Exception as e:
  75. self.logger.exception("监控线程异常: %s", e)
  76. time.sleep(3)
  77. def _is_recent_click(self, xpath):
  78. """防止重复点击同一个弹窗"""
  79. key = f"{xpath}_{int(time.time())}"
  80. if key in self.recent_clicks:
  81. return True
  82. self.recent_clicks.append(key)
  83. return False
  84. def check_and_handle_popup(self):
  85. d = self.spider.d
  86. # 1. 处理简单弹窗
  87. for xpath, desc in self.popup_rules["simple"]:
  88. if d.xpath(xpath).exists and not self._is_recent_click(xpath):
  89. self.logger.info("检测到弹窗: %s", desc)
  90. d.xpath(xpath).click()
  91. return True
  92. # 2. 处理验证码弹窗
  93. for xpath in self.popup_rules["verification"]:
  94. if d.xpath(xpath).exists:
  95. now = time.time()
  96. if now - self.last_verification_time < 30:
  97. return False # 30秒内不重复触发
  98. self.last_verification_time = now
  99. self.verification_count += 1
  100. self.logger.warning("验证码弹窗触发,等待人工处理...")
  101. if self.verification_count > self.MAX_VERIFICATION_RETRY:
  102. self.logger.error("验证码重试超限,终止任务")
  103. self.spider.stop_all()
  104. return True
  105. self.pausing.set() # 通知主线程暂停
  106. # d.toast.show("需要人工处理验证码", 120)
  107. # 等待人工处理
  108. start = time.time()
  109. # while time.time() - start < 120*60:
  110. # if not d.xpath(xpath).exists:
  111. # self.logger.info("验证码已处理")
  112. # d.toast.show("验证完成", 2)
  113. # self.pausing.clear() # 放行主线程
  114. # return True
  115. # time.sleep(5)
  116. while True:
  117. if not d.xpath(xpath).exists:
  118. self.logger.info("验证码已处理")
  119. # d.toast.show("验证完成", 2)
  120. self.pausing.clear() # 放行主线程
  121. return True
  122. time.sleep(5)
  123. self.logger.warning("验证码超时,重启APP")
  124. self.spider.restart_app()
  125. return True
  126. # 3. 处理广告弹窗(点击右上角)
  127. if d.xpath('//*[contains(@text, "广告")]').exists:
  128. w, h = d.info['displayWidth'], d.info['displayHeight']
  129. d.click(w - 50, 50)
  130. self.logger.info("关闭广告弹窗")
  131. return True
  132. return False
  133. def stop(self):
  134. self.running = False
  135. class MTScreenshot:
  136. def __init__(self, d, oss_config, search_key, title_key, scroll_times=4, compress_quality=7, resize_ratio=0.8):
  137. # 接收外部已连接好的u2设备实例
  138. self.d = d
  139. self.search_key = search_key # 添加这行
  140. self.title_key = title_key
  141. # 启动全局弹窗监控
  142. self.monitor = SpiderMonitor(self)
  143. self.monitor.start()
  144. self.loggerMT = logging.getLogger()
  145. # 日志初始化
  146. self.logger = self._init_logger()
  147. # OSS配置与初始化(核心配置,无冗余)
  148. self.oss_config = oss_config
  149. self.oss_bucket = self._init_oss_bucket()
  150. # 截图核心参数
  151. self.scroll_times = scroll_times
  152. self.compress_quality = compress_quality
  153. self.resize_ratio = resize_ratio
  154. # self.title_xpaths = [
  155. # '//*[@resource-id="com.jd.lib.productdetail.feature:id/db"]',
  156. # '//*[@resource-id="com.jd.lib.productdetail.feature:id/cx"]',
  157. # '//*[@resource-id="com.jd.lib.productdetail.feature:id/cj"]'
  158. # ]
  159. def _init_logger(self):
  160. # 极简日志配置,仅保留必要输出
  161. logger = logging.getLogger("mt_screenshot")
  162. logger.setLevel(logging.INFO)
  163. logger.handlers.clear()
  164. handler = logging.StreamHandler()
  165. handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
  166. logger.addHandler(handler)
  167. return logger
  168. def _init_oss_bucket(self):
  169. # 仅做OSS配置校验和Bucket连接,无额外功能
  170. if not all([self.oss_config.get("access_key_id"),
  171. self.oss_config.get("access_key_secret"),
  172. self.oss_config.get("endpoint"),
  173. self.oss_config.get("bucket_name")]):
  174. self.logger.warning("OSS配置不完整,无法上传")
  175. return None
  176. try:
  177. auth = oss2.Auth(self.oss_config["access_key_id"], self.oss_config["access_key_secret"])
  178. bucket = oss2.Bucket(auth, self.oss_config["endpoint"], self.oss_config["bucket_name"])
  179. bucket.get_bucket_info() # 验证连接
  180. self.logger.info("OSS Bucket连接成功")
  181. return bucket
  182. except Exception as e:
  183. self.logger.error(f"OSS Bucket连接失败: {e}")
  184. return None
  185. def _upload_to_oss(self, local_path):
  186. # 极简上传逻辑,仅返回OSS URL或None
  187. if not self.oss_bucket or not os.path.exists(local_path):
  188. return None
  189. file_name = os.path.basename(local_path)
  190. safe_name = re.sub(r'[^\w\.\-]', '_', file_name)
  191. oss_key = f"{self.oss_config.get('oss_prefix', 'scrape_data/')}{safe_name}"
  192. try:
  193. oss2.resumable_upload(self.oss_bucket, oss_key, local_path)
  194. # 生成并返回完整OSS URL
  195. oss_file_url = f"https://{self.oss_config['bucket_name']}.{self.oss_config['endpoint']}/{urllib.parse.quote(oss_key, safe='/')}"
  196. self.logger.info(f"OSS上传成功: {oss_file_url}")
  197. return oss_file_url
  198. except Exception as e:
  199. self.logger.error(f"OSS上传失败: {e}")
  200. return None
  201. # def _get_title(self):
  202. # # 仅提取标题,无冗余逻辑
  203. # for xpath in self.title_xpaths:
  204. # elem = self.d.xpath(xpath)
  205. # if elem.exists:
  206. # info = elem.info
  207. # title = (info.get("contentDescription") or info.get("content-desc") or info.get("text") or "").strip()
  208. # return title[:50] # 限制标题长度,避免文件名过长
  209. # return ""
  210. def safe_exec(self, func, *args, **kwargs):
  211. """
  212. 万能安全壳:执行 func 前检查验证码,
  213. 若监控线程已置位 pausing,则一直阻塞直到放行。
  214. """
  215. while self.monitor.pausing.is_set():
  216. time.sleep(1)
  217. # 执行真正逻辑
  218. return func(*args, **kwargs)
  219. def _get_title(self):
  220. # try:
  221. # title = self.d.xpath(
  222. # '//android.widget.ScrollView/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[3]/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.view.ViewGroup[1]/android.widget.FrameLayout[1]/android.widget.TextView').text
  223. # except:
  224. # title = self.d.xpath(
  225. # '//android.widget.ScrollView/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[3]/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.widget.TextView').text
  226. # title = self.d.xpath('//*[contains(@text, "舒肝颗粒")]').text
  227. def _inner():
  228. # elif self.search_key == '三九胃泰颗粒':
  229. # self.search_key = '三九胃泰' #兼容三九胃泰 温胃舒颗粒
  230. print(f'获取商品title时的搜索关键字:{self.title_key}')
  231. # title = self.d.xpath(f'//*[contains(@text, "{self.search_key}")]').text
  232. # 初始化
  233. drugs_name = ''
  234. specifications = ''
  235. title = ''
  236. # 循环的获取title为了有时间来处理人机验证
  237. for m in range(1, 6000):
  238. if self.d.xpath(f'//*[contains(@text, "{self.title_key}")]').exists:
  239. title = self.safe_exec(
  240. lambda: self.d.xpath(f'//*[contains(@text, "{self.title_key}")]').text
  241. )
  242. self.loggerMT.info(f"第{m}次获取title成功")
  243. print(f"第{m}次获取title成功")
  244. break
  245. else:
  246. time.sleep(3)
  247. # return drugs_name, specifications
  248. # drugs_name = ''
  249. # specifications = ''
  250. # try:
  251. # title_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.widget.ScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[3]/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.view.ViewGroup[1]/android.widget.FrameLayout[1]/android.widget.TextView'
  252. # title_xpath_2 = '//*[@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.widget.ScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[3]/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[1]/android.widget.FrameLayout[1]/android.widget.TextView'
  253. # if self.d.xpath(title_xpath).exists:
  254. # title = self.d.xpath(title_xpath).text
  255. # print(f"title_xpath获取的title={title}")
  256. # if temp_search_key not in title:
  257. # return drugs_name, specifications
  258. # elif self.d.xpath(title_xpath_2).exists:
  259. # title = self.d.xpath(title_xpath_2).text
  260. # print(f"title_xpath_2获取的title={title}")
  261. # if temp_search_key not in title:
  262. # return drugs_name, specifications
  263. # else:
  264. # print('title_xpath不存在,请确认')
  265. # return drugs_name, specifications
  266. # # title = self.d.xpath(f'//*[contains(@text, "{temp_search_key}")]').text
  267. # except Exception as e:
  268. # print(f"发生异常: {e}")
  269. # return drugs_name, specifications
  270. # 奇怪:有的时候title取出来的记过第一位会多一个0
  271. # title = self.safe_exec(self.d.xpath(f'//*[contains(@text, "{self.search_key}")]').text)
  272. # title = self.d.xpath('//*[@resource-id="com.sankuai.meituan: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.widget.ScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[3]/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.view.ViewGroup[1]/android.widget.FrameLayout[1]/android.widget.TextView').text
  273. title = title[1:] if title.startswith('0') else title
  274. print(f'获取到药品标题:{title}')
  275. # 从里面匹配出药品名和规格
  276. # drugs_name
  277. # specifications
  278. # match = re.search(r'([^\d]+)([\d\D]+)', title)
  279. if self.search_key == '999赐多康大豆':
  280. return title, '1罐'
  281. if self.search_key == "999感冒清热颗粒":
  282. match = re.search(r'(\[[^\]]+\])(.+?)(\d+.*)', title)
  283. else:
  284. match = re.match(r'(\[[^\]]+\])(.*?)\s*((?:\d+\S*|\(.+))$', title)
  285. if match:
  286. # drugs_name = match.group(1).strip() + match.group(2).strip()
  287. drugs_name = title
  288. specifications = match.group(3).strip()
  289. print("药品名:", drugs_name)
  290. print("规格:", specifications)
  291. # print('完整药名:', drugs_name + specifications)
  292. return drugs_name # , specifications
  293. else:
  294. if title == '999抗病毒口服液10ml*12' or title == '999抗病毒口服液':
  295. drugs_name = title
  296. specifications = '10ml*12支/盒'
  297. return drugs_name # , specifications
  298. elif title == '999抗病毒口服液10ml*10':
  299. drugs_name = title
  300. specifications = '10ml*10支/盒'
  301. return drugs_name # , specifications
  302. elif title == '999小柴胡颗粒':
  303. drugs_name = title
  304. specifications = '10g*9袋/盒'
  305. return drugs_name # , specifications
  306. elif title == '999养胃舒颗粒':
  307. drugs_name = title
  308. specifications = '10g*10袋/盒'
  309. return drugs_name # , specifications
  310. elif title == '三九胃泰胶囊':
  311. drugs_name = title
  312. specifications = '0.5g*24粒/盒'
  313. return drugs_name # , specifications
  314. elif title == '999补脾益肠丸':
  315. drugs_name = title
  316. specifications = '6g*9袋/盒'
  317. return drugs_name # , specifications
  318. elif title == '999感冒灵颗粒':
  319. drugs_name = title
  320. specifications = '10g*9袋/盒'
  321. return drugs_name # , specifications
  322. elif title == '999感冒灵胶囊':
  323. drugs_name = title
  324. specifications = '0.5g*12粒/盒'
  325. return drugs_name # , specifications
  326. else:
  327. print("没有匹配到预期格式")
  328. drugs_name = title
  329. specifications = ''
  330. return drugs_name # , specifications
  331. # 用 safe_exec 包装内部逻辑,确保验证码阻塞
  332. return self.safe_exec(_inner)
  333. def _merge_screenshots(self, screens):
  334. # 仅拼接截图,无额外功能
  335. if len(screens) == 1:
  336. return screens[0].convert('RGB')
  337. rgb_screens = [s.convert('RGB') for s in screens]
  338. total_width = rgb_screens[0].width
  339. total_height = sum(s.height for s in rgb_screens)
  340. merged_img = Image.new('RGB', (total_width, total_height))
  341. y_offset = 0
  342. for img in rgb_screens:
  343. merged_img.paste(img, (0, y_offset))
  344. y_offset += img.height
  345. return merged_img
  346. def get_oss_url(self):
  347. """核心方法:截图+临时本地保存+上传OSS+上传成功删本地文件+返回OSS URL,可直接赋值给oss_file"""
  348. local_file_path = None
  349. try:
  350. # 1. 提取标题
  351. title = self._get_title()
  352. self.logger.info(f"获取标题: {title[:20]}..." if title else "未获取到标题")
  353. # 2. 生成本地文件路径
  354. timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
  355. safe_title = re.sub(r'[\\/*?:"<>|]', '_', title)
  356. local_dir = "../scrape_data"
  357. os.makedirs(local_dir, exist_ok=True)
  358. local_file_path = os.path.join(local_dir, f"{timestamp}_{safe_title}.jpg")
  359. # 3. 滚动截图
  360. screen_list = [self.d.screenshot()]
  361. w, h = self.d.window_size()
  362. for i in range(self.scroll_times):
  363. # 可能滑动距离太短,截不到店名。原本是0.8
  364. # self.d.swipe(w // 2, h * 0.9, w // 2, h * 0.1, duration=random.uniform(0.6, 1.2))
  365. self.d.swipe(w // 2, h * 0.85, w // 2, h * 0.15, # 滑动到15%
  366. duration=random.uniform(0.8, 1.5))
  367. time.sleep(random.uniform(2.0, 4.0))
  368. screen_list.append(self.d.screenshot())
  369. if self.d(textContains='商家服务').exists:
  370. # 看情况是否需要补滑
  371. break
  372. # # ========== 自动处理“是否存储图像”弹窗 ==========
  373. # # 检测弹窗是否存在(根据弹窗的文本/控件ID定位)
  374. # # 通过“是否存储图像”文本定位弹窗
  375. # # if self.d(text="是否存储图像").exists(timeout=2):
  376. # # # 点击“取消”(不需要系统存储截图)
  377. # # self.d(text="取消").click(timeout=2)
  378. # # self.logger.info("已自动关闭“是否存储图像”弹窗")
  379. #
  380. # #出现标题 break
  381. # ========== 滑动截图完成后,滑回初始位置 ==========
  382. # self.logger.info("开始滑回初始位置")
  383. #
  384. # for i in range(self.scroll_times):
  385. # # 反向滑动(与正向滑动方向相反)
  386. # self.d.swipe_ext('down', 0.8)
  387. # time.sleep(random.uniform(1.0, 2.0))
  388. # print(f"第{i+1}次反向滑动,已滑回部分距离")
  389. # self.logger.info("✅ 已滑回初始页面位置")
  390. # 4. 拼接+压缩+保存
  391. merged_img = self._merge_screenshots(screen_list)
  392. if 0.1 < self.resize_ratio < 1.0:
  393. new_size = (int(merged_img.width * self.resize_ratio), int(merged_img.height * self.resize_ratio))
  394. resample_mode = Image.Resampling.LANCZOS if hasattr(Image, 'Resampling') else Image.LANCZOS
  395. merged_img = merged_img.resize(new_size, resample_mode)
  396. # 临时保存到本地
  397. merged_img.save(local_file_path, format='JPEG', quality=self.compress_quality)
  398. merged_img.close() # 释放长图句柄
  399. self.logger.info(f"临时本地保存: {local_file_path}")
  400. # 5. 上传OSS
  401. oss_url = self._upload_to_oss(local_file_path)
  402. # 6. 核心:OSS上传成功后,删除本地临时文件
  403. if oss_url is not None:
  404. try:
  405. # 先不删除,检查还有没有问题
  406. # os.remove(local_file_path)
  407. self.logger.info(f"✅ OSS上传成功,已删除本地临时文件: {local_file_path}")
  408. # 若本地目录为空,可删除目录(按需开启)
  409. # if not os.listdir(local_dir):
  410. # os.rmdir(local_dir)
  411. # self.logger.info(f"本地目录{local_dir}为空,已删除")
  412. except Exception as e:
  413. self.logger.warning(f"⚠️ OSS上传成功,但删除本地文件失败: {e}")
  414. return oss_url
  415. except Exception as e:
  416. self.logger.error(f"截图/上传失败: {e}")
  417. return None
  418. def get_access_token():
  419. AppKey = "tRK2RhyItCSh6BzyT4CNVXQa"
  420. AppSrcret = "TDgKiPo94i2mOM1sDqOuDnlcK1bG66jh"
  421. token_url = 'https://aip.baidubce.com/oauth/2.0/token'
  422. url = f"{token_url}?grant_type=client_credentials&client_id={AppKey}&client_secret={AppSrcret}"
  423. payload = ""
  424. headers = {
  425. 'Content-Type': 'application/json',
  426. 'Accept': 'application/json'
  427. }
  428. response = requests.request("POST", url, headers=headers, data=payload)
  429. try:
  430. return response.json()['access_token']
  431. except:
  432. return None
  433. def get_mysql():
  434. """
  435. 建立并返回一个到数据库的连接对象
  436. """
  437. import pymysql
  438. return pymysql.connect(
  439. host=Config.DB_HOST, # "localhost", # 修改后的主机
  440. port=Config.DB_PORT, # 3306, # 添加端口号
  441. user=Config.DB_USER, # 'root', # 修改后的用户名
  442. password=Config.DB_PASSWORD, # 修改后的密码
  443. db=Config.DB_NAME, # "drug_data", # 修改后的数据库名
  444. charset='utf8mb4'
  445. )
  446. class MT:
  447. def __init__(self, key, title_key,guige,pingpai):
  448. # self.package_name = 'com.sankuai.meituan'
  449. self.package_name = Config.PACKAGE_NAME
  450. self.access_token = get_access_token()
  451. self.city2province = self.get_city_info()
  452. self.APP_ID = '116857964'
  453. self.API_KEY = '1gAzACJOAr7BeILKqkqPOETh'
  454. self.SECRET_KEY = 'ZNArANb9GwJYgLKg4EfYhukKBfPdl1n3'
  455. self.client = AipOcr(self.APP_ID, self.API_KEY, self.SECRET_KEY)
  456. # host = Config.DB_HOST #"localhost"
  457. # user = Config.DB_USER #"root"
  458. # password = Config.DB_PASSWORD #"dfwy2025"
  459. # database = Config.DB_NAME #"drug_data"
  460. # port = Config.DB_PORT#3306
  461. # print(f'数据库配置:host:{host},user:{user},password:{password},database:{database},port:{port}')
  462. self.table_name = Config.DB_TABLE # "mt_drug_middle"
  463. self.shop_table_name = Config.DB_SHOP_TABLE
  464. # print(f'数据库表名:table_name:{self.table_name},shop_table_name:{self.shop_table_name}')
  465. # self.mysql_client = mysqlClient(host, user, password, database, port)
  466. self.loggerMT = logging.getLogger()
  467. self.search_key = key # 参苓健脾胃颗粒 舒肝颗粒 清肺化痰丸 香砂平胃颗粒
  468. self.title_key = title_key
  469. self.guige = guige
  470. self.pingpai = pingpai
  471. self.unrelated_data = 0 # 无关数据数量
  472. self.shop_data_num = 0 # 店铺数据数量
  473. def stop_app(self):
  474. self.d.app_stop(self.package_name)
  475. time.sleep(5)
  476. def start_app(self):
  477. self.d.app_start(self.package_name)
  478. time.sleep(5)
  479. def restart_app(self):
  480. """
  481. 重启app
  482. :return:
  483. """
  484. self.stop_app()
  485. self.start_app()
  486. def pingpai_guige(self, product_title):
  487. if self.pingpai in product_title:
  488. temp_search_key = self.title_key
  489. print("品牌存在:", self.search_key)
  490. if self.title_key in product_title:
  491. if self.pingpai not in product_title or self.title_key not in product_title:
  492. print(f"当前商品名称:{product_title} 不包含关键字:{temp_search_key}")
  493. return True
  494. elif self.guige not in product_title:
  495. print(f"当前商品名称:{product_title} 不包含{self.guige}品规")
  496. return True
  497. else:
  498. return True
  499. else:
  500. print(self.title_key, "不在", product_title)
  501. else:
  502. return False
  503. @staticmethod
  504. def get_sleep_time():
  505. # return random.randint(5, 8)
  506. return random.randint(1, 3)
  507. @staticmethod
  508. def get_current_date():
  509. return datetime.datetime.now().strftime('%Y/%m/%d')
  510. @staticmethod
  511. def get_city_info():
  512. """
  513. 获取所有的省市数据
  514. :return:
  515. """
  516. file_path = '../kailin_city.json'
  517. with open(file_path, 'r', encoding='utf-8') as f:
  518. data = json.load(f)
  519. province = {province_one["id"]: province_one for province_one in data['province']}
  520. city2province = dict()
  521. city = data['city']
  522. for city_one in city:
  523. name = city_one['name']
  524. pid = city_one['pid']
  525. if len(str(pid)) > 2:
  526. pid = int(re.match('^\d{2}', str(pid)).group())
  527. city2province[name] = province[pid]['name']
  528. return city2province
  529. def get_shop_name(self):
  530. """
  531. 获取店铺名
  532. :return:
  533. """
  534. try:
  535. shop_name = self.d.xpath(
  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').text
  537. print(f'获取到店铺名:{shop_name}')
  538. return shop_name
  539. except:
  540. try:
  541. shop_name = self.d.xpath(
  542. '//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').text
  543. print(f'获取到店铺名2:{shop_name}')
  544. return shop_name
  545. except Exception as e:
  546. # 点击店铺曲获取店铺名称
  547. print("点击店铺进入后获取店铺名称")
  548. self.enter_shop()
  549. 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'
  550. if self.d.xpath(shop_xpath).exists:
  551. shop_name = self.d.xpath(shop_xpath).text
  552. self.swipe_back(1)
  553. return shop_name
  554. else:
  555. print(f'获取店铺名出错:{e}')
  556. shop_name = ''
  557. return shop_name
  558. def get_qualification_number(self):
  559. """
  560. 获取资质编号
  561. :return:
  562. """
  563. try:
  564. qualification_number_str = self.d.xpath(
  565. '//*[@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
  566. qualification_number = qualification_number_str.strip('资质编号:').strip()
  567. return qualification_number
  568. except:
  569. return None
  570. def get_shop_address(self):
  571. try:
  572. xpath = '//*[@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'
  573. if self.d.xpath(xpath).exists:
  574. shop_address = self.d.xpath(xpath).text
  575. print(f'111-获取到店铺地址:{shop_address}')
  576. if '发货时间' in shop_address:
  577. print(f'店铺地址包含发货时间,再次获取店铺地址')
  578. xpath2 = '//*[@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'
  579. if self.d.xpath(xpath2).exists:
  580. shop_address = self.d.xpath(xpath2).text
  581. print(f'222-获取到店铺地址:{shop_address}')
  582. else:
  583. print(f'222-xpath2获取店铺地址失败')
  584. else:
  585. shop_address = ''
  586. print(f'333-获取到店铺地址:{shop_address}')
  587. return shop_address
  588. except:
  589. print(f'获取店铺地址出错-get_shop_address')
  590. return None
  591. def enter_detail(self):
  592. self.d.xpath('//*[@resource-id="com.sankuai.meituan:id/recycler"]/android.widget.FrameLayout[1]').click()
  593. time.sleep(self.get_sleep_time())
  594. def save_to_database(self, data):
  595. print(f'保存数据到数据库:{data}')
  596. # 连接数据库
  597. conn = get_mysql()
  598. # 创建游标对象
  599. cur = conn.cursor()
  600. # add_sql = "insert into delete_friend_table(delete_user_name,delete_user_id,delete_content,delete_time) value(%s,%s,%s,%s)"
  601. add_sql = f"""
  602. INSERT INTO {self.table_name}
  603. (product, min_price, manufacture_date, expiry_date, shop, business_license_company, province, city, manufacturer, specification, approval_number, product_link, scrape_date, scrape_province, availability, credit_code, platform, search_key, sales, inventory, snapshot_url)
  604. VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
  605. """
  606. # cur.execute(add_sql, (data['product'], data['min_price'], data['manufacture_date'], data['expiry_date'], data['shop'], data['business_license_company'],data['province'], data['city'], data['manufacturer'], data['specification'], data['approval_number'], data['product_link'], self.get_current_date(), data['scrape_province'], data['availability'], data['credit_code'], data['platform']))
  607. cur.execute(add_sql,
  608. (data['product'], data['min_price'], data['manufacture_date'], data['expiry_date'], data['shop'],
  609. data['business_license_company'], data['province'], data['city'], data['manufacturer'],
  610. data['specification'], data['approval_number'], data['product_link'], data['scrape_date'],
  611. data['scrape_province'], data['availability'], data['credit_code'], data['platform'],
  612. data['search_key'], data['sales'], data['inventory'], data['snapshot_url']))
  613. conn.commit() # 提交数据
  614. # self.mysql_client.insert(self.table_name, data)
  615. print(f"存入数据库成功")
  616. def save_shop_info_to_database(self, data):
  617. print(f'保存店铺数据到数据库:{data}')
  618. # 连接数据库
  619. conn = get_mysql()
  620. # 创建游标对象
  621. cur = conn.cursor()
  622. add_sql = f"""
  623. INSERT INTO {self.shop_table_name}
  624. (shop, contact_address, qualification_number, business_license_company, business_license_address, scrape_date, platform)
  625. VALUES (%s, %s, %s, %s, %s, %s, %s)
  626. """
  627. cur.execute(add_sql, (data['shop'], data['contact_address'], data['qualification_number'],
  628. data['business_license_company'], data['business_license_address'], data['scrape_date'],
  629. data['platform']))
  630. conn.commit() # 提交数据
  631. # self.mysql_client.insert(self.shop_table_name, data)
  632. print(f'存入店铺信息到数据库成功')
  633. def swipe_up(self):
  634. """
  635. 上滑
  636. :return:
  637. """
  638. screen_width = self.d.info['displayWidth']
  639. screen_height = self.d.info['displayHeight']
  640. duration_rate = random.uniform(0, 0.3)
  641. self.d.swipe(screen_width // 2, screen_height - 100, screen_width // 2, 100, duration=duration_rate)
  642. no = random.uniform(0, 1)
  643. if no > 0.85:
  644. # 有的时候卡着 再稍微往上滑一点点
  645. self.d.swipe_ext("up", 0.1)
  646. time.sleep(self.get_sleep_time())
  647. def swipe_back(self, no):
  648. """
  649. 返回
  650. :param no: 回退次数
  651. :return:
  652. """
  653. for idx in range(no):
  654. self.d.press('back')
  655. time.sleep(self.get_sleep_time())
  656. def drug_price(self):
  657. """
  658. 获取药品价格
  659. :return:
  660. """
  661. try:
  662. price_str = self.d.xpath('//*[starts-with(@text,"¥")]').text
  663. price = float(re.search(r'[\d\.]+', price_str).group())
  664. print(f'获取到价格:{price}')
  665. return price
  666. except Exception as e:
  667. print(f'提取价格出错-->{e}')
  668. return None
  669. def drug_sale_num(self):
  670. """
  671. 获取药品销量
  672. :return:
  673. """
  674. try:
  675. sales_element = self.d.xpath('//*[starts-with(@text,"已售")]')
  676. if sales_element.exists:
  677. sales_num_str = self.d.xpath('//*[starts-with(@text,"已售")]').text
  678. sales_num_str = sales_num_str.replace("已售", "").strip()
  679. # price = float(re.search(r'[\d\.]+', price_str).group())
  680. print(f'获取到已售数量:{sales_num_str}')
  681. return sales_num_str
  682. return None
  683. except Exception as e:
  684. print(f'提取已售数量出错-->{e}')
  685. return None
  686. def restart_uiautomator_services(self, device_id):
  687. """
  688. 重启atx的uiautomator 服务
  689. :param device_id:
  690. :return:
  691. """
  692. stop_uiautomator_services = f'adb -s {device_id} shell /data/local/tmp/atx-agent server -d --stop'
  693. start_uiautomator_services = f'adb -s {device_id} shell /data/local/tmp/atx-agent server -d'
  694. # result = subprocess.run(stop_uiautomator_services, capture_output=True, text=True, shell=True)
  695. # print(result.stdout)
  696. subprocess.run(stop_uiautomator_services, capture_output=True, text=True, shell=True)
  697. time.sleep(self.get_sleep_time())
  698. subprocess.run(start_uiautomator_services, capture_output=True, text=True, shell=True)
  699. time.sleep(self.get_sleep_time())
  700. # def connect_devices(self, device_id):
  701. # """
  702. # 连接设备
  703. # :return:
  704. # """
  705. # try:
  706. # self.d = u2.connect_usb(device_id)
  707. # # 设置隐形等待时间
  708. # # self.d.implicitly_wait(5)
  709. # self.restart_uiautomator_services(device_id)
  710. # print(f'连接到设备:{device_id}')
  711. # except Exception as e:
  712. # print(f'{device_id} 连接错误: {e}')
  713. # raise Exception(e)
  714. def connect_devices(self, device_id):
  715. """
  716. 连接设备
  717. :return:
  718. """
  719. try:
  720. self.d = u2.connect_usb(device_id)
  721. self.restart_uiautomator_services(device_id)
  722. self.oss_config = {
  723. "access_key_id": 'LTAI5tDwjfteBvivYN41r8sJ',
  724. "access_key_secret": 'yowuOGi2nYYnrqGpO3qcz94C4brcPp',
  725. "endpoint": "oss-cn-shenzhen.aliyuncs.com", # 例:oss-cn-beijing.aliyuncs.com
  726. "bucket_name": "zhijiayun-jiansuo",
  727. "oss_prefix": "scrape_data/" # OSS中存放截图的前缀(虚拟文件夹)
  728. }
  729. # jd_screenshot_ins = JDScreenshot(
  730. # d=self.d, # 传入你已连接好的设备实例
  731. # oss_config=self.oss_config,
  732. # scroll_times=2, # 可选,自定义滚动次数
  733. # compress_quality=8, # 可选,自定义压缩质量
  734. # resize_ratio=0.9 # 可选,自定义缩放比例
  735. # )
  736. print(f'连接到设备:{device_id}')
  737. self.loggerMT.info(f'连接到设备:{device_id}')
  738. except Exception as e:
  739. print(f'{device_id} 连接错误: {e}')
  740. self.loggerMT.info(f'{device_id} 连接错误: {e}')
  741. raise Exception(e)
  742. def get_ocr_res(self, img):
  743. try:
  744. # img地址
  745. print(f'开始识别图片:{img}')
  746. request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/business_license"
  747. # 二进制方式打开图片文件
  748. f = open(img, 'rb')
  749. img = base64.b64encode(f.read())
  750. params = {"image": img}
  751. # access_token = get_access_token()
  752. request_url = request_url + "?access_token=" + self.access_token
  753. headers = {'content-type': 'application/x-www-form-urlencoded'}
  754. response = requests.post(request_url, data=params, headers=headers)
  755. if response:
  756. res = response.json()
  757. new_dic = dict()
  758. for ite in res['words_result'].keys():
  759. new_dic[ite] = res['words_result'][ite]['words']
  760. print('资质数据信息', new_dic)
  761. return new_dic
  762. else:
  763. return None
  764. except:
  765. return None
  766. def remove_watermark(self, img_path):
  767. """
  768. 图片去水印(将水印部分变成白色背景)并将数据转化为二进制数据
  769. :param img_path: 图片路径
  770. :return: 二进制图片数据
  771. """
  772. img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), -1)
  773. endswith = os.path.splitext(img_path)[1]
  774. new = np.clip(1.4057577998008846 * img - 38.33089999653017, 0, 255).astype(np.uint8)
  775. _, img_binary = cv2.imencode(endswith, new)
  776. return img_binary
  777. def get_ocr_res_image(self, img):
  778. try:
  779. image = self.remove_watermark(img)
  780. # image_file = open(img,'wb')
  781. # image_file.write(image)
  782. # res_image = self.client.basicAccurate(image) # 高精度
  783. res_image = self.client.basicGeneral(image)
  784. # print(f'百度api返回结果:{res_image}')
  785. # print(res_image.get('words_result', ''))
  786. # new_dic = dict()
  787. data = res_image.get('words_result', '')
  788. print(f'百度api返回结果:{data}')
  789. # full_text = ';'.join(item['words'] for item in data)
  790. # address = ''
  791. # for item in data:
  792. # if '企业注册号' in item['words']:
  793. # print('come in 111')
  794. # reg_number = item['words'].split(':', 1)[1].strip()
  795. # elif '企业名称' in item['words']:
  796. # print('come in 222')
  797. # company_name = item['words'].split(':', 1)[1].strip()
  798. # elif '所:' in item['words']:
  799. # print('come in 333')
  800. # address = item['words'].split(':', 1)[1].strip()
  801. # # 输出结果
  802. # print("企业注册号:", reg_number)
  803. # print("企业名称:", company_name)
  804. # print("住所:", address)
  805. return data
  806. except:
  807. return None
  808. def screenshot_the_business_license(self, qualification_number):
  809. screenshot_path = 'screenshot1.png'
  810. self.d.screenshot(screenshot_path)
  811. img = cv2.imread(screenshot_path)
  812. # 指定裁剪区域 (left, top, right, bottom)
  813. left = 0
  814. top = 480
  815. right = 720
  816. bottom = 1420
  817. cropped_img = img[top:bottom, left:right]
  818. # 创建目录
  819. SCREENSHOT_DIR = Path('screenshot') # 注意这里的变化和py文件同一级目录即可
  820. SCREENSHOT_DIR.mkdir(parents=True, exist_ok=True)
  821. if qualification_number:
  822. # cropped_screenshot_path = 'D:\\work\\dfwy_spider\\drug_data\\mt\\screenshot\\' + qualification_number + '.png'
  823. cropped_screenshot_path = SCREENSHOT_DIR / f'{qualification_number}.png'
  824. else:
  825. cropped_screenshot_path = 'cropped_screenshot.png'
  826. cv2.imwrite(cropped_screenshot_path, cropped_img)
  827. return cropped_screenshot_path
  828. def screenshot_instruction(self):
  829. # 获取当前时间
  830. current_time = datetime.datetime.now()
  831. # 格式化为时分秒
  832. time_str = current_time.strftime("%H-%M-%S")
  833. # 生成随机的 8 位字符串
  834. random_str = secrets.token_hex(4) # 生成 4 个字节的随机字符串,转换为 8 位十六进制字符串
  835. print(time_str)
  836. screenshot_path = 'instructionscreenshot1-' + time_str + '-' + random_str + '.png'
  837. self.d.screenshot(screenshot_path)
  838. return screenshot_path
  839. def extract_specification(self, text):
  840. """提取药品规格信息"""
  841. # 方法1:简单去除到期信息
  842. pattern = r'^[^【]+'
  843. match = re.search(pattern, text)
  844. if match:
  845. return match.group(0).strip()
  846. return text
  847. # 获取商品title
  848. def get_title(self):
  849. # try:
  850. # title = self.d.xpath(
  851. # '//android.widget.ScrollView/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[3]/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.view.ViewGroup[1]/android.widget.FrameLayout[1]/android.widget.TextView').text
  852. # except:
  853. # title = self.d.xpath(
  854. # '//android.widget.ScrollView/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[3]/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.widget.TextView').text
  855. # title = self.d.xpath('//*[contains(@text, "舒肝颗粒")]').text
  856. def _inner():
  857. print(f'获取商品title时的搜索关键字:{self.title_key}')
  858. # title = self.d.xpath(f'//*[contains(@text, "{self.search_key}")]').text
  859. # 初始化
  860. drugs_name = ''
  861. specifications = ''
  862. title = ''
  863. # 循环的获取title为了有时间来处理人机验证
  864. for m in range(1, 6000):
  865. if self.d.xpath(f'//*[contains(@text, "{self.title_key}")]').exists:
  866. title = self.safe_exec(
  867. lambda: self.d.xpath(f'//*[contains(@text, "{self.title_key}")]').text
  868. )
  869. print(f"第{m}次获取title成功")
  870. break
  871. else:
  872. time.sleep(3)
  873. # return drugs_name, specifications
  874. title = title[1:] if title.startswith('0') else title
  875. print(f'获取到药品标题:{title}')
  876. # 从里面匹配出药品名和规格
  877. # drugs_name
  878. # specifications
  879. # match = re.search(r'([^\d]+)([\d\D]+)', title)
  880. if self.search_key == '999赐多康大豆':
  881. return title, '1罐'
  882. if self.search_key == "999感冒清热颗粒":
  883. match = re.search(r'(\[[^\]]+\])(.+?)(\d+.*)', title)
  884. else:
  885. match = re.match(r'(\[[^\]]+\])(.*?)\s*((?:\d+\S*|\(.+))$', title)
  886. if match:
  887. # drugs_name = match.group(1).strip() + match.group(2).strip()
  888. drugs_name = title
  889. specifications = match.group(3).strip()
  890. print("药品名:", drugs_name)
  891. print("规格:", specifications)
  892. # 如果品规中包含到期则需要再次的正则处理
  893. if '到期' in specifications:
  894. specifications = self.extract_specification(specifications)
  895. # print('完整药名:', drugs_name + specifications)
  896. return drugs_name, specifications
  897. else:
  898. if title == '999抗病毒口服液10ml*12' or title == '999抗病毒口服液':
  899. drugs_name = title
  900. specifications = '10ml*12支/盒'
  901. return drugs_name, specifications
  902. elif title == '999抗病毒口服液10ml*10':
  903. drugs_name = title
  904. specifications = '10ml*10支/盒'
  905. return drugs_name, specifications
  906. elif title == '999小柴胡颗粒':
  907. drugs_name = title
  908. specifications = '10g*9袋/盒'
  909. return drugs_name, specifications
  910. elif title == '999养胃舒颗粒':
  911. drugs_name = title
  912. specifications = '10g*10袋/盒'
  913. return drugs_name, specifications
  914. elif title == '三九胃泰胶囊':
  915. drugs_name = title
  916. specifications = '0.5g*24粒/盒'
  917. return drugs_name, specifications
  918. elif title == '999补脾益肠丸':
  919. drugs_name = title
  920. specifications = '6g*9袋/盒'
  921. return drugs_name, specifications
  922. elif title == '999复方感冒灵颗粒':
  923. drugs_name = title
  924. specifications = '12.5g*15袋/盒'
  925. return drugs_name, specifications
  926. else:
  927. print("没有匹配到预期格式")
  928. drugs_name = title
  929. specifications = ''
  930. return drugs_name, specifications
  931. # 用 safe_exec 包装内部逻辑,确保验证码阻塞
  932. return self.safe_exec(_inner)
  933. def enter_shop(self):
  934. """
  935. 进店,方便提取资质环境
  936. :return:
  937. """
  938. # self.d.xpath('//*[@text="进店"]').click()
  939. self.d.xpath('//*[@text="店铺"]').click()
  940. time.sleep(self.get_sleep_time())
  941. def enter_shoper(self):
  942. """
  943. 进入商家
  944. :return:
  945. """
  946. is_shoper_exists = 0
  947. for i in range(10):
  948. if self.d.xpath('//*[@text="商家"]').exists:
  949. print(f'第{i}次商家存在')
  950. is_shoper_exists = 1
  951. break
  952. else:
  953. print(f'第{i}次商家不存在')
  954. time.sleep(self.get_sleep_time())
  955. if is_shoper_exists == 1:
  956. self.d.xpath('//*[@text="商家"]').click()
  957. time.sleep(self.get_sleep_time())
  958. return True
  959. else:
  960. return False
  961. # 点击查看商家资质
  962. def scan_shoper_license(self):
  963. exist_shoper = 0
  964. for i in range(10):
  965. if self.d.xpath('//*[@text="查看商家资质"]').exists:
  966. print(f'第{i}次查看商家资质存在')
  967. exist_shoper = 1
  968. break
  969. else:
  970. print(f'第{i}次查看商家资质不存在')
  971. time.sleep(self.get_sleep_time())
  972. if exist_shoper == 1:
  973. self.d.xpath('//*[@text="查看商家资质"]').click()
  974. time.sleep(self.get_sleep_time())
  975. else:
  976. self.swipe_back(1)
  977. # 验证商品的信息是否在数据库中已存在
  978. def data_is_exists(self, data):
  979. """
  980. 检查指定数据是否已存在于数据库表中(仅检查存在性)
  981. 参数:
  982. data: 包含查询条件的字典,键为列名,值为条件值
  983. 返回:
  984. True: 数据存在
  985. False: 数据不存在
  986. None: 检查过程中出错
  987. """
  988. # dup_data = {'product': product, 'min_price': min_price, 'shop': shop, 'scrape_date': scrape_date,
  989. # 'platform': '美团'}
  990. # 1. 验证必要字段
  991. required_keys = ['product', 'min_price', 'shop', 'scrape_date', 'platform']
  992. if not all(key in data for key in required_keys):
  993. missing = [key for key in required_keys if key not in data]
  994. logging.error(f"缺少必要字段: {', '.join(missing)}")
  995. return None
  996. try:
  997. # 连接数据库
  998. conn = get_mysql()
  999. # 创建游标对象
  1000. cur = conn.cursor()
  1001. # query_sql = f"SELECT * FROM {self.table_name} WHERE product = '{data['product']}' AND min_price = '{data['min_price']}' AND shop = '{data['shop']}' AND scrape_date = '{data['scrape_date']}' AND platform = '{data['platform']}'"
  1002. # cur.execute(query_sql)
  1003. query_sql = """
  1004. SELECT * FROM {}
  1005. WHERE product = %s
  1006. AND min_price = %s
  1007. AND shop = %s
  1008. AND scrape_date = %s
  1009. AND platform = %s
  1010. """.format(self.table_name)
  1011. cur.execute(query_sql, (
  1012. data['product'],
  1013. data['min_price'],
  1014. data['shop'],
  1015. data['scrape_date'],
  1016. data['platform']
  1017. ))
  1018. result = cur.fetchone()
  1019. return bool(result) # 如果存在返回True,否则False
  1020. except Exception as e:
  1021. print(f"MySQL 错误: {str(e)}")
  1022. # 验证店铺信息是否在数据库中已存在
  1023. def shop_is_exists_database(self, shop):
  1024. try:
  1025. # 连接数据库
  1026. conn = get_mysql()
  1027. # 创建游标对象
  1028. cur = conn.cursor()
  1029. query_sql = """
  1030. SELECT * FROM {}
  1031. WHERE shop = %s
  1032. """.format(self.shop_table_name)
  1033. cur.execute(query_sql, (
  1034. shop
  1035. ))
  1036. result = cur.fetchone()
  1037. return bool(result) # 如果存在返回True,否则False
  1038. except Exception as e:
  1039. print(f"MySQL 错误: {str(e)}")
  1040. def wait_if_verifying(self, monitor, timeout=120):
  1041. """验证码处理期间阻塞主线程"""
  1042. start = time.time()
  1043. while monitor.pausing.is_set() and time.time() - start < timeout:
  1044. time.sleep(1)
  1045. # def safe_xpath(self, xpath, timeout=10):
  1046. # """线程安全 xpath 查找"""
  1047. # self.wait_if_verifying(self.monitor)
  1048. # return self.d.xpath(xpath).wait(timeout=timeout)
  1049. def wait_for_ready(self, monitor, timeout=86400):
  1050. """进入每一页前都先等验证码"""
  1051. start = time.time()
  1052. while monitor.pausing.is_set() and time.time() - start < timeout:
  1053. time.sleep(1)
  1054. # 额外保险:如果验证码突然在这一秒才弹,再主动扫一次
  1055. monitor.check_and_handle_popup()
  1056. def safe_list(self, xpath, monitor):
  1057. """线程安全地拿商品列表"""
  1058. self.wait_for_ready(monitor)
  1059. return self.d.xpath(xpath).all()
  1060. def safe_exec(self, func, *args, **kwargs):
  1061. """
  1062. 万能安全壳:执行 func 前检查验证码,
  1063. 若监控线程已置位 pausing,则一直阻塞直到放行。
  1064. """
  1065. while self.monitor.pausing.is_set():
  1066. time.sleep(1)
  1067. # 执行真正逻辑
  1068. return func(*args, **kwargs)
  1069. def get_next_data(self, data, target):
  1070. for i, item in enumerate(data):
  1071. if item['words'] == target:
  1072. if i + 1 < len(data):
  1073. return data[i + 1]['words']
  1074. return None
  1075. # ccbiao
  1076. def delete_instruction_screenshot(self, screenshot_path):
  1077. # 删除截图文件
  1078. try:
  1079. os.remove(screenshot_path)
  1080. print(f"截图文件已删除:{screenshot_path}")
  1081. except FileNotFoundError:
  1082. print(f"文件未找到,无法删除:{screenshot_path}")
  1083. except Exception as e:
  1084. print(f"删除文件时出错:{e}")
  1085. '''
  1086. def get_instructions_data(self):
  1087. """
  1088. 确定有说明书之后,提取所有的说明书数据
  1089. :return:
  1090. """
  1091. self.d.xpath('//*[@text="说明"]').click()
  1092. # time.sleep(random.randint(3, 5))
  1093. time.sleep(0.5)
  1094. self.d.xpath('//*[@text="查看详细说明"]').click()
  1095. # time.sleep(random.randint(3, 5))
  1096. time.sleep(0.5)
  1097. self.d.xpath('//*[@text="加载更多"]').click_exists()
  1098. loop_page = 5
  1099. # new_list = list()
  1100. new_list = []
  1101. for i in range(loop_page):
  1102. self.d.xpath('//*[@text="加载更多"]').click_exists()
  1103. time.sleep(0.2)
  1104. if i == 0:
  1105. self.d.swipe(200, 1000, 200, 300, 0.4)
  1106. else:
  1107. self.d.swipe(200, 1000, 200, 62)
  1108. time.sleep(0.2)
  1109. if self.d.xpath('//*[@text="加载更多"]').exists:
  1110. self.d.xpath('//*[@text="加载更多"]').click()
  1111. time.sleep(0.2)
  1112. all_tt = self.d.xpath(
  1113. '//*[@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[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[3]/android.widget.ScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup').all()
  1114. for idx in range(1, len(all_tt) + 1):
  1115. all_tt1 = self.d.xpath(
  1116. f'//*[@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[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[3]/android.widget.ScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[{idx}]//android.widget.TextView').all()
  1117. # print(f'当前说明书列表数据:{all_tt1}')
  1118. for tt in all_tt1:
  1119. if tt.text and tt.text != '展开全文':
  1120. new_list.append(tt.text)
  1121. if i == 0:
  1122. height = 938
  1123. else:
  1124. drug_box = self.d.xpath(
  1125. '//*[@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[2]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[3]/android.widget.ScrollView[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]').info
  1126. bounds = drug_box['bounds']
  1127. height = bounds['bottom'] - bounds['top']
  1128. if height < 938:
  1129. # print('说明书翻页到底部')
  1130. break
  1131. # 展开全文
  1132. new_list = [item for item in new_list if item != '展开全文']
  1133. print(f'当前说明书列表数据:{new_list}')
  1134. # expiry_date_index = next(idx for idx, i in enumerate(new_list) if i == '有效期')
  1135. # manufacturer_index = next(idx for idx, i in enumerate(new_list) if i == '生产单位')
  1136. # approval_number_index = next(idx for idx, i in enumerate(new_list) if i == '批准文号')
  1137. # res_data = {
  1138. # "有效期": new_list[expiry_date_index + 1],
  1139. # "生产单位": new_list[manufacturer_index + 1],
  1140. # "批准文号": new_list[approval_number_index + 1]
  1141. # }
  1142. res_data = {
  1143. "有效期": (new_list[new_list.index("有效期") + 1]) if "有效期" in new_list and new_list.index("有效期") + 1 < len(new_list) else "",
  1144. "生产单位": (new_list[new_list.index("生产单位") + 1]) if "生产单位" in new_list and new_list.index("生产单位") + 1 < len(new_list) else "",
  1145. "批准文号": (new_list[new_list.index("批准文号") + 1]) if "批准文号" in new_list and new_list.index("批准文号") + 1 < len(new_list) else ""
  1146. }
  1147. print(f'当前说明书字典数据:{res_data}')
  1148. return res_data
  1149. '''
  1150. '''
  1151. def get_instructions_data(self):
  1152. """
  1153. 确定有说明书之后,提取所有的说明书数据
  1154. :return:
  1155. """
  1156. self.d.xpath('//*[@text="说明"]').click()
  1157. # time.sleep(random.randint(3, 5))
  1158. time.sleep(0.5)
  1159. self.d.xpath('//*[@text="查看详细说明"]').click()
  1160. # time.sleep(random.randint(3, 5))
  1161. time.sleep(0.5)
  1162. # 1) 先向上滑动一次,触发“加载更多”出现
  1163. self.d.swipe(200, 1000, 200, 300, 0.4)
  1164. time.sleep(0.3)
  1165. # 2) 再进入“出现就点”的循环
  1166. while self.d.xpath('//*[@text="加载更多"]').click_exists(timeout=1):
  1167. time.sleep(0.2)
  1168. self.d.swipe(200, 1000, 200, 300, 0.4)
  1169. # self.d.swipe(200, 1000, 200, 62)
  1170. time.sleep(0.2)
  1171. # 一次性获取所有文本
  1172. texts = [
  1173. node.text.strip()
  1174. # for node in self.d.xpath('//android.widget.TextView').all()
  1175. for node in self.d.xpath('//*[@resource-id="com.sankuai.meituan:id/container"]//android.widget.TextView').all()
  1176. if node.text and node.text.strip() and node.text != '加载更多'
  1177. ]
  1178. print(f'当前说明书列表数据:{texts}')
  1179. # 提取关键字段
  1180. def safe_get(key):
  1181. # try:
  1182. # idx = texts.index(key)
  1183. # return texts[idx + 1] if idx + 1 < len(texts) else ""
  1184. # except ValueError:
  1185. # return ""
  1186. try:
  1187. idx = next(i for i, text in enumerate(texts) if text == key)
  1188. return texts[idx + 1] if idx + 1 < len(texts) else ""
  1189. except StopIteration:
  1190. return ""
  1191. res_data = {
  1192. "有效期": safe_get("有效期"),
  1193. "生产单位": safe_get("生产单位"),
  1194. "批准文号": safe_get("批准文号")
  1195. }
  1196. print(f'当前说明书字典数据:{res_data}')
  1197. return res_data
  1198. '''
  1199. '''
  1200. def get_instructions_data(self):
  1201. """
  1202. 说明书键值对采集:连续两个 TextView 为一对,精确提取
  1203. """
  1204. # 1. 进入说明书
  1205. self.d(text="说明").click()
  1206. time.sleep(0.5)
  1207. self.d(text="查看详细说明").click()
  1208. time.sleep(0.5)
  1209. # self.d(text="加载更多").click_exists(timeout=0.5)
  1210. # 2. 找到说明书最外层 ScrollView(页面主体)
  1211. scroll_view = self.d(resourceId="com.sankuai.meituan:id/container") .child(className="android.widget.ScrollView")
  1212. count = scroll_view.count
  1213. print(f"找到的 ScrollView 数量: {count}")
  1214. if not scroll_view.exists:
  1215. return {"有效期": "", "生产单位": "", "批准文号": ""}
  1216. # 3. 在 ScrollView 内再定位真正包含键值对的容器
  1217. # 绝大多数美团说明书页面对应的是 ScrollView > ViewGroup > 若干 TextView
  1218. kv_container = scroll_view.child(className="android.view.ViewGroup")
  1219. if not kv_container.exists:
  1220. kv_container = scroll_view # 降级:直接对 ScrollView 取子孙 TextView
  1221. # 4. 滑动到底并收集所有 TextView(保留顺序)
  1222. all_texts = []
  1223. max_swipe = 5
  1224. last_length = 0
  1225. for _ in range(max_swipe):
  1226. texts = kv_container.child(className="android.widget.TextView")
  1227. #获取texts中的文本
  1228. print(f'当前说明书列表数据:{texts}')
  1229. current_texts = []
  1230. self.loggerMT.info(f'说明书111')
  1231. for tv in texts:
  1232. try:
  1233. txt = tv.get_text().strip()
  1234. # txt = tv.info['text'].strip()
  1235. except Exception:
  1236. continue
  1237. if txt and txt != "展开全文":
  1238. current_texts.append(txt)
  1239. self.loggerMT.info(f'说明书222')
  1240. print(f'当前说明书列表数据:{current_texts}')
  1241. # 去重
  1242. if current_texts:
  1243. current_texts = [t for t in current_texts if t not in all_texts]
  1244. all_texts.extend(current_texts)
  1245. # 判断是否到底
  1246. # if not scroll_view.info.get("scrollable"):
  1247. # break
  1248. # 判断是否到底
  1249. if len(all_texts) == last_length:
  1250. break
  1251. last_length = len(all_texts)
  1252. # self.d.swipe_ext("up", scale=0.7)
  1253. #向上滑动一次
  1254. self.d.swipe(200, 1000, 200, 300, 0.2)
  1255. time.sleep(0.2)
  1256. if self.d.xpath('//*[@text="加载更多"]').exists:
  1257. self.d.xpath('//*[@text="加载更多"]').click()
  1258. # 5. 成对解析
  1259. res_data = {"有效期": "", "生产单位": "", "批准文号": ""}
  1260. for i in range(len(all_texts) - 1):
  1261. key = all_texts[i]
  1262. val = all_texts[i + 1]
  1263. if key in res_data:
  1264. res_data[key] = val
  1265. print(f'说明书文本共 {len(all_texts)} 条,提取结果: {res_data}')
  1266. # time.sleep(1000000)
  1267. return res_data
  1268. '''
  1269. def get_instructions_data(self):
  1270. """
  1271. 确定有说明书之后,提取所有的说明书数据
  1272. :return:
  1273. """
  1274. self.d.xpath('//*[@text="说明"]').click()
  1275. # time.sleep(random.randint(3, 5))
  1276. time.sleep(0.5)
  1277. if self.d.xpath('//*[@text="查看详细说明"]').exists:
  1278. self.d.xpath('//*[@text="查看详细说明"]').click()
  1279. else:
  1280. for i in range(8):
  1281. if self.d.xpath('//*[@text="查看全部"]').exists:
  1282. print('开始点击查看全部')
  1283. break
  1284. self.d.swipe_ext('down', 0.3)
  1285. time.sleep(1)
  1286. if self.d.xpath('//*[@text="查看全部"]').exists:
  1287. print('开始点击查看全部2')
  1288. break
  1289. if self.d.xpath('//*[@text="查看全部"]').exists:
  1290. self.d.xpath('//*[@text="查看全部"]').click()
  1291. else:
  1292. res_data = {
  1293. "有效期": '',
  1294. "生产单位": '',
  1295. "批准文号": ''
  1296. }
  1297. self.loggerMT.info('获取到的说明书信息为空。')
  1298. return res_data
  1299. # time.sleep(random.randint(3, 5))
  1300. time.sleep(0.5)
  1301. # self.d.xpath('//*[@text="加载更多"]').click_exists()
  1302. # loop_page = 5
  1303. # new_list = list()
  1304. # new_list = []
  1305. for ii in range(8):
  1306. if self.d.xpath('//*[@text="加载更多"]').exists:
  1307. self.d.xpath('//*[@text="加载更多"]').click()
  1308. time.sleep(0.2)
  1309. break
  1310. else:
  1311. self.d.swipe(200, 1000, 200, 300, 0.3)
  1312. # self.d.swipe_ext("up", scale=0.3)
  1313. for iii in range(10):
  1314. if self.d.xpath('//*[@text="生产单位"]').exists and self.d.xpath('//*[@text="批准文号"]').exists:
  1315. break
  1316. else:
  1317. self.d.swipe(200, 1300, 200, 300, 0.3)
  1318. # self.d.swipe_ext("up", scale=0.3)
  1319. instruction_path = self.screenshot_instruction()
  1320. print(f"instruction_path= {instruction_path}")
  1321. time.sleep(2)
  1322. ocr_res = self.get_ocr_res_image(instruction_path)
  1323. # print(f'ocr_res:{ocr_res}')
  1324. if ocr_res:
  1325. # 获取有效期的下一个数据
  1326. validity = self.get_next_data(ocr_res, '有效期')
  1327. # 获取批准文号的下一个数据
  1328. approval_number = self.get_next_data(ocr_res, '批准文号')
  1329. # 获取生产单位的下一个数据
  1330. manufacturer = self.get_next_data(ocr_res, '生产单位')
  1331. else:
  1332. validity = ''
  1333. approval_number = ''
  1334. manufacturer = ''
  1335. # print("有效期:", validity)
  1336. # print("批准文号:", approval_number)
  1337. # print("生产单位:", manufacturer)
  1338. res_data = {
  1339. "有效期": validity,
  1340. "生产单位": manufacturer,
  1341. "批准文号": approval_number
  1342. }
  1343. print(f"res_data={res_data}")
  1344. time.sleep(1)
  1345. self.delete_instruction_screenshot(instruction_path)
  1346. return res_data
  1347. def has_instructions(self):
  1348. """
  1349. 是否有说明书
  1350. :return:
  1351. """
  1352. # 没有说明书的无法采集具体数据
  1353. time.sleep(self.get_sleep_time())
  1354. is_has_instructions = False
  1355. for i in range(8):
  1356. if self.d.xpath('//*[@text="说明"]').exists:
  1357. print(f"第{i}次有说明书1")
  1358. is_has_instructions = True
  1359. break
  1360. self.d.swipe_ext('down', 0.3)
  1361. time.sleep(1)
  1362. # detail_info = self.d.xpath(
  1363. # '//android.widget.ScrollView/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[6]').info
  1364. # bounds = detail_info['bounds']
  1365. # height = bounds['bottom'] - bounds['top']
  1366. # if self.d.xpath('//*[@text="进店"]').exists and height > 100:
  1367. if self.d.xpath('//*[@text="说明"]').exists:
  1368. is_has_instructions = True
  1369. print(f"第{i}次有说明书2")
  1370. break
  1371. # is_has_instructions = self.d.xpath('//*[@text="说明"]').exists
  1372. return is_has_instructions
  1373. def has_shop(self):
  1374. """
  1375. 是否有进店按钮
  1376. :return:
  1377. """
  1378. # self.d.swipe_ext('up', 0.1)
  1379. time.sleep(self.get_sleep_time())
  1380. is_has_enter_shop = self.d.xpath('//*[@text="进店"]').exists
  1381. return is_has_enter_shop
  1382. # 获取商品对应的店铺信息
  1383. def get_license_info_ex(self):
  1384. # self.enter_shop()
  1385. self.safe_exec(self.enter_shop)
  1386. # self.enter_shoper()
  1387. result = self.safe_exec(self.enter_shoper)
  1388. if result == False:
  1389. license_info_data = {'contact_address': '', 'qualification_number': '', 'business_license_company': '',
  1390. 'business_license_address': ''}
  1391. return license_info_data
  1392. for i in range(10):
  1393. if self.d.xpath('//*[@text="查看商家资质"]').exists:
  1394. print(f"第{i}次有商家资质")
  1395. break
  1396. else:
  1397. print(f"第{i}次没有商家资质")
  1398. time.sleep(self.get_sleep_time())
  1399. # 获取地址
  1400. # contact_address = self.get_shop_address()
  1401. contact_address = self.safe_exec(self.get_shop_address)
  1402. # time.sleep(50000)
  1403. ###
  1404. # self.scan_shoper_license()
  1405. self.safe_exec(self.scan_shoper_license)
  1406. # 获取资质编码
  1407. # qualification_number = self.get_qualification_number()
  1408. qualification_number = self.safe_exec(self.get_qualification_number)
  1409. # qualification_number 不为None继续下一步
  1410. if qualification_number:
  1411. # 营业执照公司名称
  1412. business_license_company = ''
  1413. # 营业执照地址
  1414. business_license_address = ''
  1415. self.d.click(0.603, 0.27)
  1416. time.sleep(self.get_sleep_time())
  1417. cropped_screenshot_path = self.screenshot_the_business_license(qualification_number)
  1418. print(f'cropped_screenshot_path:{cropped_screenshot_path}')
  1419. # if qualification_number:
  1420. # cropped_screenshot_path = 'D:\\work\\dfwy_spider\\drug_data\\mt\\screenshot\\' + qualification_number + '.png'
  1421. # else:
  1422. # cropped_screenshot_path = 'cropped_screenshot.png'
  1423. # ocr_res = self.get_ocr_res('cropped_screenshot.png')
  1424. ocr_res = self.get_ocr_res(cropped_screenshot_path)
  1425. print(f'ocr_res:{ocr_res}')
  1426. # 获取ocr_res 中的地址、单位名称
  1427. if ocr_res:
  1428. if '单位名称' in ocr_res.keys():
  1429. business_license_company = ocr_res['单位名称']
  1430. if '地址' in ocr_res.keys():
  1431. business_license_address = ocr_res['地址']
  1432. license_info_data = {'contact_address': contact_address, 'qualification_number': qualification_number,
  1433. 'business_license_company': business_license_company,
  1434. 'business_license_address': business_license_address}
  1435. else:
  1436. license_info_data = {'contact_address': contact_address, 'qualification_number': '',
  1437. 'business_license_company': '', 'business_license_address': ''}
  1438. return license_info_data
  1439. """暂不用该功能
  1440. def get_license_info(self):
  1441. self.enter_shop()
  1442. self.enter_shoper()
  1443. self.scan_shoper_license()
  1444. # 获取资质编码
  1445. qualification_number = self.get_qualification_number()
  1446. if qualification_number:
  1447. table_license_info = self.get_table_license_info(qualification_number)
  1448. if table_license_info:
  1449. return {
  1450. '单位名称': table_license_info[0],
  1451. '地址': table_license_info[1],
  1452. '社会信用代码': table_license_info[2]
  1453. }
  1454. else:
  1455. # operate_no = random.randint(0, 1)
  1456. self.d.click(0.603, 0.27)
  1457. # if operate_no == 0:
  1458. # self.d.xpath('//*[@text="营业执照"]').click()
  1459. # else:
  1460. # self.d.click(0.603, 0.27)
  1461. time.sleep(self.get_sleep_time())
  1462. self.screenshot_the_business_license()
  1463. ocr_res = self.get_ocr_res('cropped_screenshot.png')
  1464. return ocr_res
  1465. # operate_no = random.randint(0, 1)
  1466. self.d.click(0.603, 0.27)
  1467. # if operate_no == 0:
  1468. # self.d.xpath('//*[@text="营业执照"]').click()
  1469. # else:
  1470. # self.d.click(0.603, 0.27)
  1471. time.sleep(self.get_sleep_time())
  1472. self.screenshot_the_business_license()
  1473. ocr_res = self.get_ocr_res('cropped_screenshot.png')
  1474. return ocr_res
  1475. """
  1476. def distinct_target(self):
  1477. result = False
  1478. 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]'
  1479. 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]'
  1480. is_position = self.d.xpath(position_xpath).exists
  1481. is_position2 = self.d.xpath(position_xpath2).exists
  1482. 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()]'
  1483. 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()]'
  1484. 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()]'
  1485. 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()]'
  1486. is_position5 = self.d.xpath(xpath).exists
  1487. is_position6 = self.d.xpath(xpath2).exists
  1488. is_position7 = self.d.xpath(xpath3).exists
  1489. is_position8 = self.d.xpath(xpath4).exists
  1490. # print(f"is_position = {is_position}")
  1491. # print(f"is_position2 = {is_position2}")
  1492. if is_position or is_position2 or is_position5 or is_position6 or is_position7 or is_position8:
  1493. result = True
  1494. if result == False:
  1495. print("---检测没有回到列表页---")
  1496. else:
  1497. print("---检测回到了列表页---")
  1498. return result
  1499. # return is_position
  1500. def enter_target_page(self):
  1501. self.d.xpath('//*[@content-desc="看病买药"]').click()
  1502. time.sleep(self.get_sleep_time())
  1503. self.d.xpath('//*[@resource-id="com.sankuai.meituan:id/vf_search_carousel_text"]').click()
  1504. time.sleep(self.get_sleep_time())
  1505. self.d.xpath(
  1506. '//*[@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()
  1507. time.sleep(self.get_sleep_time())
  1508. self.d.send_keys(self.search_key, clear=True)
  1509. time.sleep(self.get_sleep_time())
  1510. self.d.xpath('//*[@text="搜索"]').click()
  1511. time.sleep(self.get_sleep_time())
  1512. # content_frame = self.d.xpath('//*[@resource-id="com.sankuai.meituan:id/container"]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[2]').exists
  1513. # print(content_frame)
  1514. # position_xpath1 = '//*[@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]'
  1515. # 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]'
  1516. # if self.d.xpath(position_xpath1).exists:
  1517. # print("position_xpath1 exist")
  1518. # elif self.d.xpath(position_xpath2).exists:
  1519. # print("position_xpath2 exist")
  1520. # else:
  1521. # print("position_xpath not exist")
  1522. # time.sleep(10000)
  1523. # 增加点击快递送
  1524. self.click_express_send()
  1525. time.sleep(self.get_sleep_time())
  1526. def click_express_send(self):
  1527. # xpath= '//*[@resource-id="com.sankuai.meituan:id/container"]//android.widget.HorizontalScrollView[last()]'
  1528. slide_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]'
  1529. slide_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]'
  1530. slide_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]'
  1531. slide_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]'
  1532. for i in range(1, 3):
  1533. if self.d.xpath(slide_xpath).exists:
  1534. bounds = self.d.xpath(slide_xpath).info['bounds']
  1535. top = bounds['top']
  1536. bottom = bounds['bottom']
  1537. print(f'top={top}')
  1538. print(f'bottom={bottom}')
  1539. y = (top + bottom) // 2
  1540. print(f'y={y}')
  1541. self.loggerMT.info('开始滑动1')
  1542. self.d.swipe(500, y, 100, y, 0.5)
  1543. time.sleep(self.get_sleep_time())
  1544. break
  1545. elif self.d.xpath(slide_xpath2).exists:
  1546. bounds = self.d.xpath(slide_xpath2).info['bounds']
  1547. top = bounds['top']
  1548. bottom = bounds['bottom']
  1549. print(f'top={top}')
  1550. print(f'bottom={bottom}')
  1551. y = (top + bottom) // 2
  1552. print(f'y={y}')
  1553. self.loggerMT.info('开始滑动2')
  1554. self.d.swipe(500, y, 100, y, 0.5)
  1555. time.sleep(self.get_sleep_time())
  1556. break
  1557. elif self.d.xpath(slide_xpath3).exists:
  1558. bounds = self.d.xpath(slide_xpath3).info['bounds']
  1559. top = bounds['top']
  1560. bottom = bounds['bottom']
  1561. print(f'top={top}')
  1562. print(f'bottom={bottom}')
  1563. y = (top + bottom) // 2
  1564. print(f'y={y}')
  1565. self.loggerMT.info('开始滑动3')
  1566. self.d.swipe(500, y, 100, y, 0.5)
  1567. time.sleep(self.get_sleep_time())
  1568. break
  1569. elif self.d.xpath(slide_xpath4).exists:
  1570. bounds = self.d.xpath(slide_xpath4).info['bounds']
  1571. top = bounds['top']
  1572. bottom = bounds['bottom']
  1573. print(f'top={top}')
  1574. print(f'bottom={bottom}')
  1575. y = (top + bottom) // 2
  1576. print(f'y={y}')
  1577. self.loggerMT.info('开始滑动4')
  1578. self.d.swipe(500, y, 100, y, 0.5)
  1579. time.sleep(self.get_sleep_time())
  1580. break
  1581. max_retry = 5 # 最多尝试次数
  1582. for idx in range(1, max_retry + 1):
  1583. # 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[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()-1]/android.view.ViewGroup[1]/android.view.ViewGroup[1]'
  1584. 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()]'
  1585. 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()]'
  1586. 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()]'
  1587. 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()]'
  1588. # print(f"xpath:{xpath}")
  1589. # scroll_view = self.d(resourceId="com.sankuai.meituan:id/container") .child(className="android.widget.HorizontalScrollView")
  1590. if self.d.xpath(xpath).exists:
  1591. self.d.xpath(xpath).click()
  1592. # time.sleep(self.get_sleep_time())
  1593. print(f"第{idx}次点击xpath快递送成功")
  1594. time.sleep(self.get_sleep_time())
  1595. break
  1596. elif self.d.xpath(xpath2).exists:
  1597. self.d.xpath(xpath2).click()
  1598. # time.sleep(self.get_sleep_time())
  1599. print(f"第{idx}次点击xpath2快递送成功")
  1600. time.sleep(self.get_sleep_time())
  1601. break
  1602. elif self.d.xpath(xpath3).exists:
  1603. self.d.xpath(xpath3).click()
  1604. # time.sleep(self.get_sleep_time())
  1605. print(f"第{idx}次点击xpath3快递送成功")
  1606. time.sleep(self.get_sleep_time())
  1607. break
  1608. elif self.d.xpath(xpath4).exists:
  1609. self.d.xpath(xpath4).click()
  1610. # time.sleep(self.get_sleep_time())
  1611. print(f"第{idx}次点击xpath4快递送成功")
  1612. time.sleep(self.get_sleep_time())
  1613. break
  1614. else:
  1615. print(f"第{idx}次点击xpath或xpath2或xpath3快递送都失败")
  1616. time.sleep(self.get_sleep_time())
  1617. # 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()]'
  1618. # if self.d.xpath(xpath2).exists:
  1619. # self.d.xpath(xpath2).click()
  1620. # print(f"第{idx}次点击xpath2快递送成功")
  1621. # time.sleep(self.get_sleep_time())
  1622. # break
  1623. def get_clipboard(self):
  1624. time.sleep(1)
  1625. self.loggerMT.info(f"Clipboard content:{self.d.clipboard}") # 打印调试信息
  1626. clipboard_content = self.d.clipboard
  1627. if clipboard_content is None:
  1628. return ''
  1629. return clipboard_content.strip()
  1630. # return self.d.clipboard.strip()
  1631. def clear_clipboard(self):
  1632. self.d.set_clipboard("", "text/plain")
  1633. def get_product_link(self):
  1634. product_link = ''
  1635. dots_xpaths = [
  1636. '//*[@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]',
  1637. '//*[@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]',
  1638. '//*[@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]'
  1639. ]
  1640. max_retry = 5 # 最多尝试次数
  1641. for idx in range(1, max_retry + 1):
  1642. if product_link: # 已经拿到则退出
  1643. break
  1644. for xp in dots_xpaths:
  1645. if self.d.xpath(xp).exists:
  1646. print(f'{idx}-进入分享点点点')
  1647. self.loggerMT.info(f'{idx}-进入分享点点点')
  1648. # #先清空剪贴板的内容
  1649. # self.clear_clipboard()
  1650. # print("清空剪贴板内容成功。")
  1651. self.loggerMT.info(f'{idx}-click')
  1652. self.d.xpath(xp).click()
  1653. time.sleep(0.2)
  1654. self.loggerMT.info(f'{idx}-click_exists')
  1655. self.d.xpath('//*[@text="分享商品"]').click_exists()
  1656. time.sleep(0.2)
  1657. link_xpath = '//*[@text="复制链接"]'
  1658. if self.d.xpath(link_xpath).exists:
  1659. self.loggerMT.info(f'{idx}-link_xpath click')
  1660. self.d.xpath(link_xpath).click()
  1661. time.sleep(1)
  1662. product_link = self.get_clipboard()
  1663. time.sleep(0.5)
  1664. print(f'{idx}-商品链接:{product_link}')
  1665. self.loggerMT.info(f'{idx}-商品链接:{product_link}')
  1666. break # 找到并执行后跳出内层循环
  1667. else:
  1668. print(f'{idx}-商品链接:{product_link}')
  1669. self.loggerMT.info(f'{idx}-商品链接:{product_link}')
  1670. product_link = ''
  1671. # self.d.xpath('//*[@text="复制链接"]').click_exists()
  1672. # time.sleep(1)
  1673. # product_link = self.get_clipboard()
  1674. # time.sleep(0.5)
  1675. # print(f'{idx}-商品链接:{product_link}')
  1676. # self.loggerMT.info(f'{idx}-商品链接:{product_link}')
  1677. # break # 找到并执行后跳出内层循环
  1678. if not product_link and idx < max_retry:
  1679. time.sleep(0.5) # 最后一次不需要再等待
  1680. return product_link
  1681. def integrate_data(self):
  1682. """
  1683. 整合数据
  1684. :return:
  1685. """
  1686. # title_info = self.get_title() # 药品,规格
  1687. # title_info = self.safe_exec(self.get_title) # 药品,规格
  1688. product, specifications = self.safe_exec(self.get_title) # 药品,规格
  1689. if not product:
  1690. self.swipe_back(1)
  1691. return
  1692. min_price = self.drug_price() # 最低价格
  1693. sales_num = self.drug_sale_num() # 销售数量
  1694. snapshot_url = '' # 网页快照
  1695. # 在这里截图存放到OSS;#采集图片存放的oss_url;
  1696. mt_screenshot = MTScreenshot(
  1697. d=self.d,
  1698. oss_config=self.oss_config,
  1699. search_key=self.search_key, # 添加这行
  1700. title_key=self.title_key,
  1701. )
  1702. # snapshot_url = mt_screenshot.get_oss_url() #网页快照
  1703. # 判断是否有自营的文本,有的话不需要获取店铺的信息
  1704. product_link = ''
  1705. if self.d.xpath('//*[@text="自营"]').exists:
  1706. shop = "美团自营大药房(快递电商)"
  1707. # 爬取日期
  1708. scrape_date = self.get_current_date()
  1709. # scrape_date = "2025-07-18"
  1710. dup_data = {'product': product, 'min_price': min_price, 'shop': shop, 'scrape_date': scrape_date,
  1711. 'platform': '美团'}
  1712. print(f'当前数据:{dup_data}')
  1713. if self.data_is_exists(dup_data):
  1714. print('存在相同数据不入库')
  1715. self.swipe_back(1)
  1716. return
  1717. else:
  1718. for i in range(8):
  1719. if self.d.xpath('//*[@text="进店"]').exists:
  1720. print('开始获取店铺名1')
  1721. break
  1722. self.d.swipe_ext('up', 0.3)
  1723. time.sleep(1)
  1724. # detail_info = self.d.xpath(
  1725. # '//android.widget.ScrollView/android.view.ViewGroup[1]/android.view.ViewGroup[1]/android.view.ViewGroup[6]').info
  1726. # bounds = detail_info['bounds']
  1727. # height = bounds['bottom'] - bounds['top']
  1728. # if self.d.xpath('//*[@text="进店"]').exists and height > 100:
  1729. if self.d.xpath('//*[@text="进店"]').exists:
  1730. print('开始获取店铺名2')
  1731. break
  1732. shop = self.get_shop_name()
  1733. # 爬取日期
  1734. scrape_date = self.get_current_date()
  1735. # scrape_date = "2025-07-18"
  1736. dup_data = {'product': product, 'min_price': min_price, 'shop': shop, 'scrape_date': scrape_date,
  1737. 'platform': '美团'}
  1738. print(f'当前数据:{dup_data}')
  1739. # 获取店铺信息开始
  1740. # 暂时不获取店铺信息 start
  1741. is_has_enter_shop = self.has_shop()
  1742. # 需要判断shop是否已经在数据库中存在,如果存在,则不再进入店铺,直接进入下一个商品
  1743. shop_is_exists = self.shop_is_exists_database(shop)
  1744. # 存在进店 并且店铺的名称不包含美团官方的字样
  1745. print(f"已采集{self.shop_data_num}家店铺数据")
  1746. if is_has_enter_shop and '美团官方' not in shop and '美团自营' not in shop and not shop_is_exists and self.shop_data_num < 500:
  1747. # license_info = self.get_license_info_ex()
  1748. license_info = self.safe_exec(self.get_license_info_ex)
  1749. contact_address = license_info['contact_address']
  1750. qualification_number = license_info['qualification_number']
  1751. business_license_company = license_info['business_license_company']
  1752. business_license_address = license_info['business_license_address']
  1753. save_shop_data = {
  1754. 'shop': shop,
  1755. 'contact_address': contact_address,
  1756. 'qualification_number': qualification_number,
  1757. 'scrape_date': scrape_date,
  1758. 'business_license_company': business_license_company,
  1759. 'business_license_address': business_license_address,
  1760. 'platform': '美团'
  1761. }
  1762. self.save_shop_info_to_database(save_shop_data)
  1763. self.shop_data_num += 1 # 店铺数据数量+1
  1764. self.swipe_back(2)
  1765. else:
  1766. print('不采集店铺信息')
  1767. # 获取店铺信息结束
  1768. # 暂时不获取店铺信息 end
  1769. if self.data_is_exists(dup_data):
  1770. print('存在相同数据不入库')
  1771. self.swipe_back(1)
  1772. return
  1773. # 商品链接
  1774. product_link = self.get_product_link()
  1775. print(f'获取到product_link: {product_link}')
  1776. if not shop:
  1777. print('未获取到店铺名:开始回退')
  1778. self.swipe_back(1)
  1779. return
  1780. if not shop or '自营' in shop:
  1781. self.swipe_back(1)
  1782. return
  1783. time.sleep(self.get_sleep_time())
  1784. # 生产日期为空
  1785. manufacture_date = ''
  1786. # 执政信息
  1787. # if is_has_enter_shop:
  1788. # license_info = self.get_license_info()
  1789. # business_license_company = license_info["单位名称"]
  1790. # credit_code = license_info['社会信用代码']
  1791. # city_str = license_info['地址']
  1792. # # 先把省份啥的替换掉
  1793. # city_sub_str = re.sub(r'[u4e00-\u9fa5]+省', '', city_str)
  1794. # try:
  1795. # city = re.search(r'[\u4e00-\u9fa5]+?(市|区|县)', city_sub_str).group(0)
  1796. # except:
  1797. # city = city_sub_str
  1798. # try:
  1799. # province = self.city2province[city]
  1800. # except:
  1801. # province = ''
  1802. # self.swipe_back(2)
  1803. # else:
  1804. # business_license_company = ''
  1805. # credit_code = ''
  1806. # city = ''
  1807. # province = ''
  1808. business_license_company = ''
  1809. credit_code = ''
  1810. city = ''
  1811. province = ''
  1812. expiry_date = ''
  1813. manufacturer = ''
  1814. approval_number = ''
  1815. # 暂时不获取说明书信息 start
  1816. # 是否存在说明书
  1817. # is_has_instructions = self.has_instructions()
  1818. is_has_instructions = self.safe_exec(self.has_instructions)
  1819. # 说明书等信息
  1820. if is_has_instructions:
  1821. print('开始获取说明书信息')
  1822. # instructions_info = self.get_instructions_data()
  1823. instructions_info = self.safe_exec(self.get_instructions_data)
  1824. if instructions_info['有效期'] is not None:
  1825. expiry_date = instructions_info['有效期'].strip('。')
  1826. if instructions_info['生产单位'] is not None:
  1827. manufacturer = instructions_info['生产单位'].strip('。')
  1828. if instructions_info['批准文号'] is not None:
  1829. approval_number = instructions_info['批准文号'].strip('。')
  1830. else:
  1831. expiry_date = None
  1832. manufacturer = None
  1833. approval_number = None
  1834. # 暂时不获取说明书信息 end
  1835. self.unrelated_data = 0
  1836. if self.search_key == '999小柴胡颗粒10g*15':
  1837. save_search_key = '999小柴胡颗粒'
  1838. else:
  1839. save_search_key = self.search_key
  1840. # 爬取省份
  1841. scrape_province = '广东' # 这里先默认广东
  1842. # 是否有货
  1843. availability = ''
  1844. save_data = {
  1845. 'product': product,
  1846. 'min_price': min_price,
  1847. 'manufacture_date': manufacture_date,
  1848. 'expiry_date': expiry_date,
  1849. 'shop': shop,
  1850. 'business_license_company': business_license_company,
  1851. 'province': province,
  1852. 'city': city,
  1853. 'manufacturer': manufacturer,
  1854. 'specification': specifications,
  1855. 'approval_number': approval_number,
  1856. 'product_link': product_link,
  1857. 'scrape_date': scrape_date,
  1858. 'scrape_province': scrape_province,
  1859. 'availability': availability,
  1860. 'credit_code': credit_code,
  1861. 'platform': '美团',
  1862. 'search_key': save_search_key,
  1863. 'sales': sales_num,
  1864. 'inventory': '',
  1865. 'snapshot_url': snapshot_url
  1866. }
  1867. self.save_to_database(save_data)
  1868. def back_to_list_page(self):
  1869. for i in range(5):
  1870. # 最外部有个定位按钮
  1871. if self.distinct_target():
  1872. return True
  1873. print(f'第{i}次尝试退回到列表页')
  1874. self.swipe_back(1)
  1875. time.sleep(self.get_sleep_time())
  1876. print('页面出错,没有退回到列表页')
  1877. return False
  1878. # 主函数
  1879. def main(self, device_id, retry_count=0):
  1880. MAX_RETRY = 3 # 最大重试次数
  1881. spider_no = 0
  1882. self.connect_devices(device_id)
  1883. time.sleep(self.get_sleep_time())
  1884. # self.d.toast.show("测试toast", 20)
  1885. # 启动全局弹窗监控
  1886. self.monitor = SpiderMonitor(self)
  1887. self.monitor.start()
  1888. try:
  1889. # 重新开启美团应用
  1890. self.restart_app()
  1891. # 搜索关键字
  1892. # self.enter_target_page()
  1893. self.safe_exec(self.enter_target_page)
  1894. # print('开始滑动')
  1895. # self.d.drag(300, 1400, 300, 400, 1)
  1896. # time.sleep(100000)
  1897. for idx in range(300):
  1898. print(f'第{idx + 1}页')
  1899. if spider_no > 30:
  1900. time.sleep(60)
  1901. spider_no = 0
  1902. print('目前无关数据量: ', self.unrelated_data)
  1903. # 检查是否需要暂停(验证码过多)
  1904. if self.monitor.verification_count >= self.monitor.MAX_VERIFICATION_RETRY:
  1905. print("频繁遇到验证码,暂停程序")
  1906. # self.d.toast("请处理验证码后点击继续", 30)
  1907. # 等待用户点击屏幕继续
  1908. self.d.click(0, 0) # 无效点击,等待用户操作
  1909. self.monitor.verification_count = 0
  1910. if self.unrelated_data > 15:
  1911. print("连续超过15个不达标的数据则停止采集")
  1912. return
  1913. while True:
  1914. if self.d.xpath('//android.support.v7.widget.RecyclerView/android.widget.FrameLayout').exists:
  1915. break
  1916. time.sleep(1)
  1917. drug_lis = self.safe_exec(
  1918. self.d.xpath('//android.support.v7.widget.RecyclerView/android.widget.FrameLayout').all)
  1919. lis_len = len(drug_lis)
  1920. print(f'当前页面共有{lis_len}个商品')
  1921. for idxx, drug_one in enumerate(drug_lis, start=1):
  1922. bounds = drug_one.info['bounds']
  1923. top = bounds['top']
  1924. bottom = bounds['bottom']
  1925. # height = bottom - top
  1926. print(f'当前商品bottom:{bottom}')
  1927. print(f'当前商品top:{top}')
  1928. # if 304 <= top and bottom <= 1475: # 默认高度241的才行
  1929. if 304 <= top and bottom <= 1475: # 默认高度241的才行 1559
  1930. # print('目标-->', drug_one.info)
  1931. # drug_one.click()
  1932. # 获取当前元素中的属性来判断是否要点击进入采集
  1933. print(f"这页的第几个商品:{idxx}")
  1934. product_title = ''
  1935. price = ''
  1936. shop_name = ''
  1937. # 商品名称的xpath
  1938. product_tittle_xpath = f'//android.support.v7.widget.RecyclerView/android.widget.FrameLayout[{idxx}]/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'
  1939. product_tittle_xpath2 = f'//android.support.v7.widget.RecyclerView/android.widget.FrameLayout[{idxx}]/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'
  1940. if self.d.xpath(product_tittle_xpath).exists:
  1941. product_title = self.d.xpath(product_tittle_xpath).text
  1942. product_title = product_title[1:] if product_title.startswith('0') else product_title
  1943. print(f"product_tittle_xpath列表当前商品名称:{product_title}")
  1944. if self.pingpai_guige(product_title) == False:
  1945. continue
  1946. elif self.d.xpath(product_tittle_xpath2).exists:
  1947. product_title = self.d.xpath(product_tittle_xpath2).text
  1948. product_title = product_title[1:] if product_title.startswith('0') else product_title
  1949. print(f"product_tittle_xpath2列表当前商品名称:{product_title}")
  1950. if self.pingpai_guige(product_title) == False:
  1951. continue
  1952. else:
  1953. print(f"列表当前商品名称不存在")
  1954. # 价格
  1955. price_xpath = f'//android.support.v7.widget.RecyclerView/android.widget.FrameLayout[{idxx}]/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'
  1956. price_xpath3 = f'//android.support.v7.widget.RecyclerView/android.widget.FrameLayout[{idxx}]/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'
  1957. price_xpath1 = f'//android.support.v7.widget.RecyclerView/android.widget.FrameLayout[{idxx}]/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'
  1958. if self.d.xpath(price_xpath).exists:
  1959. price_str = self.d.xpath(price_xpath).text
  1960. print(f"price_xpath列表当前商品价格:{price_str}")
  1961. if price_str:
  1962. price = float(re.search(r'[\d\.]+', price_str).group())
  1963. elif self.d.xpath(price_xpath3).exists:
  1964. price_str = self.d.xpath(price_xpath3).text
  1965. print(f"price_xpath3列表当前商品价格:{price_str}")
  1966. if price_str:
  1967. price = float(re.search(r'[\d\.]+', price_str).group())
  1968. elif self.d.xpath(price_xpath1).exists:
  1969. price_str = self.d.xpath(price_xpath1).text
  1970. print(f"price_xpath1列表当前商品价格:{price_str}")
  1971. if price_str:
  1972. price = float(re.search(r'[\d\.]+', price_str).group())
  1973. else:
  1974. price_xpath2 = f'//android.support.v7.widget.RecyclerView/android.widget.FrameLayout[{idxx}]/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'
  1975. if self.d.xpath(price_xpath2).exists:
  1976. price_str = self.d.xpath(price_xpath2).text
  1977. print(f"price_xpath2列表当前商品价格:{price_str}")
  1978. if price_str:
  1979. price = float(re.search(r'[\d\.]+', price_str).group())
  1980. else:
  1981. print(f"列表当前商品价格不存在")
  1982. # price_str = self.d.xpath(f'//android.support.v7.widget.RecyclerView/android.widget.FrameLayout[{idxx}]//*[starts-with(@text,"¥")]').text
  1983. print(f'列表获取到价格:{price}')
  1984. # 店铺名称的xpath
  1985. shop_name_xpath = f'//android.support.v7.widget.RecyclerView/android.widget.FrameLayout[{idxx}]/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]'
  1986. shop_name_xpath2 = f'//android.support.v7.widget.RecyclerView/android.widget.FrameLayout[{idxx}]/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]'
  1987. if self.d.xpath(shop_name_xpath).exists:
  1988. shop_name = self.d.xpath(shop_name_xpath).text
  1989. print(f"shop_name_xpath列表当前商品店铺名称:{shop_name}")
  1990. elif self.d.xpath(shop_name_xpath2).exists:
  1991. shop_name = self.d.xpath(shop_name_xpath2).text
  1992. print(f"shop_name_xpath2列表当前商品店铺名称:{shop_name}")
  1993. else:
  1994. print(f"列表当前商品店铺名称不存在")
  1995. # 如果商品的名称、价格和生产厂家都不存在则直接下一条数据。 跳过一些不是商品的数据。
  1996. if product_title == '' and price == '' and shop_name == '':
  1997. continue
  1998. scrape_date = self.get_current_date()
  1999. if product_title and price and shop_name:
  2000. # 判断数据表中是否存在
  2001. dup_data = {'product': product_title, 'min_price': price, 'shop': shop_name,
  2002. 'scrape_date': scrape_date, 'platform': '美团'}
  2003. if self.data_is_exists(dup_data):
  2004. print('列表存在相同数据不入库')
  2005. continue
  2006. self.safe_exec(drug_one.click)
  2007. print('点击目标药品完毕')
  2008. time.sleep(2)
  2009. # 采集药品信息
  2010. try:
  2011. # self.integrate_data()
  2012. self.safe_exec(self.integrate_data)
  2013. print('integrate_data结束')
  2014. res = self.back_to_list_page()
  2015. if not res:
  2016. print('main 页面出错,退出采集2')
  2017. return
  2018. time.sleep(self.get_sleep_time())
  2019. spider_no += 1
  2020. except Exception as e:
  2021. print(f'采集药品详情数据出错:{e}')
  2022. # 增加阻塞的方法:
  2023. print('在详情页3', True)
  2024. res = self.back_to_list_page()
  2025. if not res:
  2026. print('main 页面出错,退出采集')
  2027. return
  2028. print('已到达搜索列表页3', True)
  2029. if self.d.xpath('//*[@text="已经到底啦"]').exists:
  2030. print('已经到达列表页最底部')
  2031. return
  2032. search_list = self.d.xpath('//android.support.v7.widget.RecyclerView').info
  2033. bounds = search_list['bounds']
  2034. # print('搜索列表高度', 1400 + bounds['top'] - bounds['bottom'])
  2035. # self.d.swipe(200, 1400, 200, 1400 + bounds['top'] - bounds['bottom'])
  2036. # 计算滑动距离
  2037. scroll_distance = bounds['bottom'] - bounds['top'] # 正数
  2038. start_y = 1600
  2039. end_y = start_y - scroll_distance # 向上滑动,y 坐标减小
  2040. # 确保 end_y 不小于 0
  2041. end_y = max(end_y, 304) # 留出一点边距,避免滑出屏幕
  2042. # print('滑动起点 y:', start_y, '终点 y:', end_y)
  2043. # self.d.swipe(200, start_y, 200, end_y, 0.4)
  2044. print('开始滑动')
  2045. self.d.drag(300, 1400, 300, 400, 1)
  2046. # self.safe_exec(self.d.drag, 300, 1400, 300, 400, 1)
  2047. print('滑动结束')
  2048. # print('搜索列表高度', 1400 + bounds['top'] - bounds['bottom'])
  2049. # self.d.swipe(200, 1400, 200, 1400 + bounds['top'] - bounds['bottom'])
  2050. # self.d.swipe(200, 1400, 200, 1400 + bounds['top'] - bounds['bottom'], 0.4)
  2051. time.sleep(self.get_sleep_time())
  2052. finally:
  2053. # 确保监控线程被停止
  2054. self.monitor.stop()
  2055. self.monitor.join()
  2056. def unitest(self):
  2057. # # 创建目录
  2058. # SCREENSHOT_DIR = Path('screenshot') # 注意这里的变化
  2059. # SCREENSHOT_DIR.mkdir(parents=True, exist_ok=True)
  2060. # # 创建测试图片路径
  2061. # qualification_number = '12345'
  2062. # file_path = SCREENSHOT_DIR / f'{qualification_number}.png'
  2063. # # 创建图片
  2064. # img = Image.new('RGB', (300, 200), color='lightblue')
  2065. # draw = ImageDraw.Draw(img)
  2066. # # 添加文字
  2067. # try:
  2068. # font = ImageFont.truetype("arial.ttf", 20)
  2069. # except:
  2070. # font = ImageFont.load_default()
  2071. # draw.text((50, 80), f"测试图片: {qualification_number}", fill='black', font=font)
  2072. # draw.text((50, 110), "保存路径测试", fill='darkred', font=font)
  2073. # draw.text((50, 140), f"目录: {SCREENSHOT_DIR}", fill='green', font=font)
  2074. # # 保存图片
  2075. # img.save(file_path)
  2076. # print(f"✅ 图片已保存到: {file_path.resolve()}")
  2077. # print(f"📁 文件大小: {file_path.stat().st_size} 字节")
  2078. # print(f"📏 图片尺寸: {img.size}")
  2079. # SCREENSHOT_DIR = Path('drug_data/mt/screenshot')
  2080. # # 使用
  2081. # qualification_number = '12345'
  2082. # file_path = SCREENSHOT_DIR / f'{qualification_number}.png'
  2083. # print(f"file_path={file_path}")
  2084. # print("=== 路径信息 ===")
  2085. # print(f"当前工作目录: {Path.cwd()}")
  2086. # print(f"SCREENSHOT_DIR: {SCREENSHOT_DIR}")
  2087. # print(f"file_path: {file_path}")
  2088. # print(f"绝对路径: {file_path.resolve()}")
  2089. # print(f"父目录: {file_path.parent}")
  2090. # print(f"文件名: {file_path.name}")
  2091. # print(f"是否存在: {file_path.exists()}")
  2092. time.sleep(100000)
  2093. """
  2094. 单元测试
  2095. :return:
  2096. """
  2097. save_data = {
  2098. 'product': "[昆中药]舒肝颗粒(低糖型)",
  2099. 'min_price': 14.0,
  2100. 'manufacture_date': '',
  2101. 'expiry_date': '36个月',
  2102. 'shop': '美团自营大药房(快递电商)',
  2103. 'business_license_company': '',
  2104. 'province': '',
  2105. 'city': '',
  2106. 'manufacturer': '昆明中药厂有限公司',
  2107. 'specification': '3g*16袋/盒',
  2108. 'approval_number': '国药准字Z53021161',
  2109. 'product_link': '',
  2110. 'scrape_date': '2025/07/09',
  2111. 'scrape_province': '广东',
  2112. 'availability': '',
  2113. 'credit_code': '',
  2114. 'platform': '美团',
  2115. 'search_key': '',
  2116. 'sales': '',
  2117. 'inventory': '',
  2118. 'snapshot_url': ''
  2119. }
  2120. self.save_to_database(save_data)
  2121. time.sleep(100000)
  2122. pass
  2123. def main():
  2124. keys_list = [
  2125. {"search_key": "天士力养血清脑颗粒4g*15", "title_key": "养血清脑颗粒","规格":"4g*15","品牌":"天士力"},
  2126. # {"search_key":'999蒲地蓝消炎片', "title_key": '蒲地蓝消炎片'},
  2127. # {"search_key": '999感冒灵颗粒', "title_key": '感冒灵颗粒'},
  2128. ]
  2129. device_id = 'IRLZAAQCDMHYWKTS'
  2130. cycle_no = 0 # 轮次计数
  2131. while True:
  2132. cycle_no += 1
  2133. logging.info(f'========== 第 {cycle_no} 轮采集开始 ==========')
  2134. for idx, ele in enumerate(keys_list, 1):
  2135. logging.info(f'[{idx}/{len(keys_list)}] 开始采集关键字:{ele}')
  2136. try:
  2137. mt = MT(ele["search_key"], ele["title_key"],ele["规格"],ele["品牌"]) # 用当前关键字实例化
  2138. # mt.unitest()
  2139. mt.main(device_id) # 执行一次完整采集
  2140. logging.info(f'关键字 {ele} 本轮采集完成')
  2141. except Exception as e:
  2142. # 发生异常直接跳过该关键字,继续下一轮
  2143. logging.exception(f'关键字 {ele} 采集异常:{e}')
  2144. finally:
  2145. # 关闭当前 MT 实例资源(如有需要)
  2146. if hasattr(mt, 'close'):
  2147. mt.close()
  2148. # logging.info('本轮全部关键字采集完成,等待 2 小时后下一轮...')
  2149. # time.sleep(1 * 3600) # 2 小时 = 7200 秒
  2150. # keys = '小柴胡颗粒' # 参苓健脾胃颗粒 舒肝颗粒 清肺化痰丸 香砂平胃颗粒 小柴胡颗粒
  2151. # mt = MT(keys) # 参苓健脾胃颗粒 舒肝颗粒 清肺化痰丸 香砂平胃颗粒
  2152. # # mt.main('95b2c764')
  2153. # mt.main('fcb3c749')
  2154. if __name__ == '__main__':
  2155. main()
  2156. # scheduler = BlockingScheduler()
  2157. # scheduler.add_job(main, 'cron', hour=21, minute=30, misfire_grace_time=120)
  2158. # try:
  2159. # scheduler.start()
  2160. # except (KeyboardInterrupt, SystemExit):
  2161. # pass