no_search_test0814.py 116 KB

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