start_run_jd.py 5.5 KB

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