all_in_one.py 102 KB

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