no_search_0723.py 69 KB

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