all_in_two.py 103 KB

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