mt_x10.py 111 KB

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