start_run_jd.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import json
  2. import time
  3. import requests
  4. from commons.Logger import logger
  5. from commons.scheduler import CrawlerScheduler
  6. from commons.conn_mysql import MySQLPoolOn2, MySQLPool39
  7. from spiders.jd.jd_auto_crawl import JdCrawlerV2
  8. import schedule
  9. from commons.feishu_webhook import send_text
  10. import random
  11. from commons.config import JD_DEVICE_ID
  12. platform_name = "京东"
  13. class JdMain:
  14. def __init__(self):
  15. # self.db_online = MySQLPool39()
  16. self.db_online = MySQLPoolOn2()
  17. self.crawl_count = ""
  18. self.task_id = ""
  19. #self.task_dict = self.get_task()
  20. def get_status(self, status):
  21. if status not in (2, 3, 4):
  22. logger.warning(f"未知状态值: {status}, 跳过状态上报")
  23. return
  24. if status == 2:
  25. parmas = {
  26. "collect_task_allocate_id": self.task_id, "status": status, "finish_status": 0,
  27. "start_time": int(time.time())
  28. }
  29. if status == 3:
  30. parmas = {
  31. "collect_task_allocate_id": self.task_id, "status": status, "finish_status": 1,
  32. "real_count": self.crawl_count, "end_time": int(time.time()),
  33. }
  34. if status == 4:
  35. parmas = {
  36. "collect_task_allocate_id": self.task_id, "status": status, "finish_status": 0,
  37. "end_time": int(time.time())}
  38. # url = "http://scheduletest.dfwy.tech/api/collect_equipment_execute/result_report"
  39. url = "http://scheduleapi.findit.ltd/api/collect_equipment_execute/result_report"
  40. try:
  41. res = requests.get(url, params=parmas, timeout=20)
  42. res.raise_for_status()
  43. logger.info("状态上报: %s", res.text)
  44. except Exception as e:
  45. logger.warning(f"状态上报失败: {e}")
  46. def get_task(self):
  47. """获取当前设备绑定的京东待执行任务。"""
  48. sql = """
  49. SELECT t.*
  50. FROM `retrieve_collect_task_allocate` t
  51. INNER JOIN `retrieve_collect_equipment_account` a
  52. ON t.`collect_equipment_account_id` = a.`id`
  53. WHERE a.`device_id` = %s
  54. AND t.`platform` = 2
  55. AND t.`status` = 3
  56. LIMIT 1
  57. """
  58. task_list = self.db_online.select_data(sql, (JD_DEVICE_ID,))
  59. print(task_list)
  60. if not task_list:
  61. return {}
  62. task_dict = task_list[0]
  63. self.task_id = task_dict["id"]
  64. print(task_dict)
  65. return task_dict
  66. def get_task(self):
  67. task_api = "http://192.168.2.246:8080/api/collect_task/pull"
  68. headers = {'X-Crawler-Token':'zhijiayun_crawler_2026'}
  69. params = {
  70. 'platform': 2,
  71. 'username': JD_DEVICE_ID
  72. }
  73. response = requests.get(task_api, params=params,headers=headers)
  74. result = response.json()
  75. if result.get('code') =='success':
  76. return result.get('data').get('task')
  77. logger.info(f'拉取任务:{result}')
  78. print('拉取任务返回',result)
  79. def heartbeat_task(self):
  80. url = "https://scheduleapi.findit.ltd/api/collect_equipment_execute/heartbeat"
  81. params = {
  82. "collect_task_allocate_id": self.task_id,
  83. }
  84. try:
  85. res = requests.get(url, params=params, timeout=20)
  86. logger.info("心跳任务上报成功")
  87. except Exception as e:
  88. logger.info("心跳任务上报失败")
  89. def run(self):
  90. spider_schedule = CrawlerScheduler(JD_DEVICE_ID,2)
  91. spider_schedule.start()
  92. time.sleep(3)
  93. while 1 :
  94. print(f'not spider_schedule.end:{not spider_schedule.end}')
  95. if(not spider_schedule.end):
  96. print('进入工作')
  97. self.task_dict = spider_schedule.get_task()
  98. #self.task_dict = {'id': 4, 'company_id': 0, 'product_name': '藿香正气合剂', 'product_specs': '', 'product_brand': '999', 'product_keyword': '', 'current_page': 0, 'start_offset': 0}
  99. print(self.task_dict)
  100. if not self.task_dict:
  101. logger.info(f"{platform_name}暂无任务")
  102. time.sleep(35)
  103. continue
  104. # self.get_status(2)
  105. self.crawl_count, is_success = JdCrawlerV2(self.task_dict,spider_schedule).run()
  106. spider_schedule.stop()
  107. else:
  108. spider_schedule.start()
  109. print('休息')
  110. time.sleep(35)
  111. time.sleep(30)
  112. # self.heartbeat_task()
  113. # # send_text(
  114. # # f"""{str(time.strftime("%Y-%m-%d %H:%M:%S"))} 通知:\n平台: {platform_name}, 药品: {self.task_dict.get("product_brand") + " " + self.task_dict.get("product_name") + " " + self.task_dict.get("product_specs")}, 爬取数据: {self.crawl_count}条""")
  115. # if is_success:
  116. # self.get_status(3)
  117. # else:
  118. # self.get_status(4)
  119. if __name__ == '__main__':
  120. # task_dict= {"id": 1622, 'collect_task_id': 4596, 'company_id': 8, 'product_name': '小儿氨酚烷胺颗粒',
  121. # 'product_specs': '', 'product_keyword': '', 'product_brand': '可复美', 'sampling_cycle': 1,
  122. # 'sampling_start_time': 1778083200, 'sampling_end_time': 1778342399, 'collect_equipment_account_id': 15,
  123. # 'collect_region_id': 0, 'collect_equipment_id': 25, 'collect_round': 2,"start_page":4,"end_page":10}
  124. # JdCrawlerV2(task_dict).run()
  125. # 每10分钟执行一次
  126. while True:
  127. JdMain().run()
  128. interval_time = random.randint(60, 180)
  129. interval_time = 60
  130. logger.info(f"程序睡眠{interval_time}秒后继续执行")
  131. time.sleep(interval_time)