mt_x.py 124 KB

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