no_search.py 101 KB

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