search_key_mac.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/2/20
  4. import json
  5. import os
  6. import sys
  7. import time
  8. import atomac
  9. sys.path.append(os.getcwd())
  10. from common.common import Common
  11. from common.feishu import Feishu
  12. class SearchKey:
  13. # 启动微信 / 微信指数小程序 ; 关闭微信 / 微信指数小程序
  14. @classmethod
  15. def start_wechat(cls, log_type, crawler):
  16. try:
  17. # 启动应用并获取应用信息
  18. bundle_id = "com.tencent.xinWeChat"
  19. Common.logger(log_type, crawler).info("启动微信")
  20. atomac.launchAppByBundleId(bundle_id)
  21. automator = atomac.getAppRefByBundleId(bundle_id)
  22. time.sleep(1)
  23. # 获取当前应用window
  24. window = automator.windows()[0]
  25. Common.logger(log_type, crawler).info(f"当前应用window:{window.AXTitle}")
  26. # 查找聊天按钮
  27. Common.logger(log_type, crawler).info("查找聊天按钮")
  28. chat_btn = window.findFirstR(AXHelp="微信", AXRole="AXRadioButton")
  29. # print(chat_btn.getAttributes())
  30. # 点击聊天按钮,展开聊天列表
  31. Common.logger(log_type, crawler).info("点击聊天按钮")
  32. chat_btn.Press()
  33. time.sleep(1)
  34. # 查找文件传输助手
  35. Common.logger(log_type, crawler).info("查找文件传输助手")
  36. chat_help = window.findFirstR(AXIdentifier="MMChatsTableCellView_0" ,AXRole="AXCell")
  37. Common.logger(log_type, crawler).info(f"文件传输助手:{chat_help}")
  38. chat_help_position = chat_help.AXPosition
  39. chat_help_size = chat_help.AXSize
  40. chat_help_coor = (abs(chat_help_position[0])+chat_help_size[0]/2, abs(chat_help_position[1])+chat_help_size[1]/2)
  41. Common.logger(log_type, crawler).info(f"文件传输助手坐标:{chat_help_coor}")
  42. Common.logger(log_type, crawler).info("点击文件传输助手")
  43. for i in range(2):
  44. chat_help.clickMouseButtonLeft(chat_help_coor)
  45. time.sleep(1)
  46. Common.logger(log_type, crawler).info("查找微信指数小程序消息")
  47. weixinzhishu = window.findFirstR(AXValue="微信指数", AXRole="AXStaticText")
  48. Common.logger(log_type, crawler).info(f"微信指数小程序:{weixinzhishu}")
  49. weixinzhishu_box = weixinzhishu.AXPosition
  50. weixinzhishu_position = weixinzhishu.AXSize
  51. weixinzhishu_coord = (abs(weixinzhishu_box[0])+weixinzhishu_position[0]/2, abs(weixinzhishu_box[1])+weixinzhishu_position[1])
  52. Common.logger(log_type, crawler).info(f"微信指数小程序坐标:{weixinzhishu_coord}")
  53. Common.logger(log_type, crawler).info("点击微信指数小程序消息")
  54. for i in range(2):
  55. weixinzhishu.clickMouseButtonLeft(weixinzhishu_coord)
  56. time.sleep(1)
  57. close_wechat = window.findFirstR(AXSubrole="AXCloseButton", AXRole="AXButton")
  58. close_wechat.Press()
  59. time.sleep(1)
  60. Common.logger(log_type, crawler).info("关闭微信成功")
  61. Common.logger(log_type, crawler).info("关闭微信指数小程序")
  62. cmd = "ps aux | grep Program.app | grep -v grep | awk '{print $2}' | xargs kill -9"
  63. os.system(cmd)
  64. Common.logger(log_type, crawler).info("微信指数小程序关闭成功")
  65. time.sleep(1)
  66. except Exception as e:
  67. Common.logger(log_type, crawler).info(f"start_wechat:{e}\n")
  68. # 获取微信指数小程序 search_key
  69. @classmethod
  70. def get_wechat_key(cls, log_type, crawler):
  71. chlsfile_path = f"./{crawler}/{crawler}_chlsfiles/"
  72. while True:
  73. if len(os.listdir(chlsfile_path)) == 0:
  74. Common.logger(log_type, crawler).info("chlsfile文件夹空,等待 3 秒")
  75. time.sleep(3)
  76. cls.start_wechat(log_type, crawler)
  77. continue
  78. Common.logger(log_type, crawler).info(f"chlsfile_list:{sorted(os.listdir(chlsfile_path))}")
  79. # 获取最新的 chlsfile
  80. chlsfile = sorted(os.listdir(chlsfile_path))[-1]
  81. # 分离文件名与扩展名
  82. new_file = os.path.splitext(chlsfile)
  83. # 重命名文件后缀
  84. os.rename(os.path.join(chlsfile_path, chlsfile),
  85. os.path.join(chlsfile_path, new_file[0] + ".txt"))
  86. with open(f"{chlsfile_path}{new_file[0]}.txt", encoding='utf-8-sig', errors='ignore') as f:
  87. contents = json.load(f, strict=False)
  88. if "search.weixin.qq.com" not in [text['host'] for text in contents]:
  89. return "未找到wechat_key"
  90. else:
  91. for content in contents:
  92. if content["host"] == "search.weixin.qq.com" and content[
  93. "path"] == "/cgi-bin/wxaweb/wxindexgetusergroup":
  94. # print(f"content:{content}")
  95. text = content['request']['body']['text']
  96. search_key = json.loads(text)['search_key']
  97. openid = json.loads(text)['openid']
  98. wechat_key_dict = {
  99. "search_key": search_key,
  100. "openid": openid,
  101. }
  102. return wechat_key_dict
  103. # 删除 chlsfile 文件
  104. @classmethod
  105. def remove_chlsfile(cls, log_type, crawler):
  106. try:
  107. all_file_path = f"./{crawler}/{crawler}_chlsfiles/"
  108. if not os.path.exists(all_file_path):
  109. os.mkdir(all_file_path)
  110. all_file = os.listdir(all_file_path)
  111. for file in all_file:
  112. os.remove(f"./{crawler}/{crawler}_chlsfiles/{file}")
  113. except Exception as e:
  114. Common.logger(log_type, crawler).error(f"remove_file异常:{e}\n")
  115. # 删除微信指数小程序 search_key
  116. @classmethod
  117. def del_wechat_key(cls, log_type, crawler):
  118. try:
  119. while True:
  120. sheet = Feishu.get_values_batch(log_type, crawler, 'pIW4Bq')
  121. if sheet is None:
  122. Common.logger(log_type, crawler).info(f"wechat_key_sheet:{sheet}, 1秒后重新获取")
  123. time.sleep(1)
  124. continue
  125. if len(sheet) <= 51:
  126. return
  127. else:
  128. Feishu.dimension_range(log_type, crawler, 'pIW4Bq', 'ROWS', 52, 52)
  129. except Exception as e:
  130. Common.logger(log_type, crawler).error(f"del_wechat_key异常:{e}\n")
  131. # 微信指数小程序 search_key 写入飞书
  132. @classmethod
  133. def write_wechat_key(cls, log_type, crawler):
  134. Common.logger(log_type, crawler).info(f"清空 chlsfiles 文件夹")
  135. cls.remove_chlsfile(log_type, crawler)
  136. # Common.logger(log_type, crawler).info('启动微信指数小程序')
  137. # cls.start_wechat(log_type, crawler)
  138. Common.logger(log_type, crawler).info('获取 wechat_key')
  139. while True:
  140. cls.start_wechat(log_type, crawler)
  141. wechat_key_dict = cls.get_wechat_key(log_type, crawler)
  142. if wechat_key_dict is None or wechat_key_dict == "未找到wechat_key":
  143. Common.logger(log_type, crawler).info("未找到wechat_key,重新获取")
  144. time.sleep(1)
  145. continue
  146. for k, v in wechat_key_dict.items():
  147. Common.logger(log_type, crawler).info(f"{k}:{v}")
  148. Feishu.insert_columns(log_type, crawler, 'pIW4Bq', 'ROWS', 1, 2)
  149. time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time())))
  150. values = [[time_str, wechat_key_dict['search_key'], wechat_key_dict['openid']]]
  151. time.sleep(1)
  152. Feishu.update_values(log_type, crawler, 'pIW4Bq', 'A2:Z2', values)
  153. cls.del_wechat_key(log_type, crawler)
  154. Common.logger(log_type, crawler).info("wechat_key写入飞书成功")
  155. Common.del_logs(log_type, crawler)
  156. return
  157. @classmethod
  158. def main(cls, log_type, crawler):
  159. while True:
  160. cls.write_wechat_key(log_type, crawler)
  161. Common.logger('searchkey', 'weixinzhishu').info('休眠10秒\n')
  162. time.sleep(10)
  163. if __name__ == "__main__":
  164. # SearchKey.start_wechat("search", "weixinzhishu")
  165. # SearchKey.del_wechat_key("search", "weixinzhishu")
  166. # SearchKey.write_wechat_key("search", "weixinzhishu")
  167. SearchKey.main("search", "weixinzhishu")
  168. pass