no_search_single_0806.py 90 KB

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