search_key.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/2/10
  4. """
  5. 获取微信指数小程序请求参数:search_key
  6. 1. 启动 WinAppDriver.exe
  7. 2. 启动 Charles.exe:
  8. 2.1 选中 Proxy - Windows Proxy
  9. 2.2 选中 Tools - Auto Save - Enable Auto Save
  10. 3. 启动 Python 脚本:
  11. 3.1 cd D:\piaoquan_crawler
  12. 3.2 python .\weixinzhishu\weixinzhishu_main\search_key.py
  13. 每分钟获取最新search_key,写入飞书: https://w42nne6hzg.feishu.cn/sheets/shtcnqhMRUGunIfGnGXMOBYiy4K?sheet=sVL74k
  14. """
  15. import json
  16. import os
  17. import shutil
  18. import sys
  19. import time
  20. import psutil
  21. from appium import webdriver
  22. from pyasn1.type.univ import Integer
  23. from selenium.common import NoSuchElementException, WebDriverException
  24. from selenium.webdriver.common.by import By
  25. sys.path.append(os.getcwd())
  26. from common.common import Common
  27. from common.feishu import Feishu
  28. class Searchkey:
  29. @classmethod
  30. def start_wechat(cls, log_type, crawler):
  31. try:
  32. # Common.logger(log_type, crawler).info('启动"微信"')
  33. desired_caps = {'app': r"C:\Program Files (x86)\Tencent\WeChat\WeChat.exe"}
  34. driver = webdriver.Remote(
  35. command_executor='http://127.0.0.1:4723',
  36. desired_capabilities=desired_caps)
  37. driver.implicitly_wait(10)
  38. # Common.logger(log_type, crawler).info('点击微信指数')
  39. driver.find_elements(By.NAME, '消息')[-1].click()
  40. time.sleep(2)
  41. # cls.kill_pid(log_type, crawler)
  42. # time.sleep(2)
  43. driver.quit()
  44. # time.sleep(2)
  45. # windowHandles = driver.getWindowHandles()
  46. print('关闭微信指数')
  47. new_driver = cls.close_weixinzhishu()
  48. new_driver.find_elements(By.NAME, '关闭')[-1].click()
  49. # print(windowHandles)
  50. # cls.rmtree_WMPFRuntime()
  51. except Exception as e:
  52. Common.logger(log_type, crawler).error(f'start_wechat异常:{e}\n')
  53. @classmethod
  54. def close_weixinzhishu(cls, app_name='微信指数'):
  55. """
  56. *通过名字找到windowsdriver
  57. *通过窗口名称,从桌面对象获取webdriver对象
  58. """
  59. new_caps = {'app': "Root"}
  60. try:
  61. new_driver = webdriver.Remote(command_executor='http://127.0.0.1:4723', desired_capabilities=new_caps)
  62. windowElement = new_driver.find_elements(By.NAME, app_name)
  63. if len(windowElement) != 0:
  64. newWindowHandle = windowElement[0].get_attribute("NativeWindowHandle")
  65. app_caps = {"appTopLevelWindow": newWindowHandle}
  66. app_driver = webdriver.Remote(command_executor='http://127.0.0.1:4723',
  67. desired_capabilities=app_caps)
  68. return app_driver
  69. except NoSuchElementException:
  70. print(f"没有找到对应的名字的窗口:{app_name}")
  71. except WebDriverException:
  72. print("连接winappdriver失败,请检查是否启动")
  73. @classmethod
  74. def kill_pid(cls, log_type, crawler):
  75. try:
  76. os.system('chcp 65001') # 将cmd的显示字符编码从默认的GBK改为UTF-8
  77. list_process = list()
  78. pid_list = psutil.pids()
  79. for sub_pid in pid_list:
  80. try:
  81. process_info = psutil.Process(sub_pid)
  82. print(process_info)
  83. if process_info.name() == 'WeChatAppEx.exe' \
  84. or process_info.name() == 'WeChatOCR.exe' \
  85. or process_info.name() == 'WeChatPlayer.exe' \
  86. or process_info.name() == 'WeChatUtility.exe':
  87. list_process.append(sub_pid)
  88. except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
  89. pass
  90. for pid in list_process:
  91. os.system('taskkill /f /pid ' + str(pid))
  92. except Exception as e:
  93. Common.logger(log_type, crawler).error(f'kill_pid异常:{e}\n')
  94. @classmethod
  95. def rmtree_WMPFRuntime(cls):
  96. WMPFRuntime_path = r"C:\Users\guosh\AppData\Roaming\Tencent\WeChat\XPlugin\Plugins\WMPFRuntime"
  97. shutil.rmtree(WMPFRuntime_path)
  98. if not os.path.exists(WMPFRuntime_path):
  99. os.mkdir(WMPFRuntime_path)
  100. @classmethod
  101. def get_search_key(cls, log_type, crawler):
  102. try:
  103. # charles 抓包文件保存目录
  104. chlsfile_path = f"./{crawler}/{crawler}_chlsfiles/"
  105. if len(os.listdir(chlsfile_path)) == 0:
  106. Common.logger(log_type, crawler).info("chlsfile文件夹为空,等待10s")
  107. cls.start_wechat(log_type, crawler)
  108. time.sleep(10)
  109. cls.get_search_key(log_type, crawler)
  110. else:
  111. Common.logger(log_type, crawler).info(f"chlsfile_list:{sorted(os.listdir(chlsfile_path))}")
  112. # 获取最新的 chlsfile
  113. chlsfile = sorted(os.listdir(chlsfile_path))[-1]
  114. # 分离文件名与扩展名
  115. new_file = os.path.splitext(chlsfile)
  116. # 重命名文件后缀
  117. os.rename(os.path.join(chlsfile_path, chlsfile),
  118. os.path.join(chlsfile_path, new_file[0] + ".txt"))
  119. with open(f"{chlsfile_path}{new_file[0]}.txt", encoding='utf-8-sig', errors='ignore') as f:
  120. contents = json.load(f, strict=False)
  121. if "search.weixin.qq.com" not in [text['host'] for text in contents]:
  122. return "未找到search_key"
  123. else:
  124. for content in contents:
  125. if content["host"] == "search.weixin.qq.com" and content["path"] == "/cgi-bin/wxaweb/wxindexgetusergroup":
  126. # print(f"content:{content}")
  127. text = content['request']['body']['text']
  128. search_key = json.loads(text)['search_key']
  129. openid = json.loads(text)['openid']
  130. return search_key, openid
  131. except Exception as e:
  132. Common.logger(log_type, crawler).exception(f"get_search_key异常:{e}\n")
  133. return None
  134. @classmethod
  135. def remove_file(cls, log_type, crawler):
  136. try:
  137. all_file_path = f"./{crawler}/{crawler}_chlsfiles/"
  138. if not os.path.exists(all_file_path):
  139. os.mkdir(all_file_path)
  140. all_file = os.listdir(f"./{crawler}/{crawler}_chlsfiles/")
  141. for file in all_file:
  142. os.remove(f"./{crawler}/{crawler}_chlsfiles/{file}")
  143. except Exception as e:
  144. Common.logger(log_type, crawler).error(f"remove_file异常:{e}\n")
  145. @classmethod
  146. def del_search_key_from_feishu(cls, log_type, crawler):
  147. try:
  148. sheet = Feishu.get_values_batch(log_type, crawler, 'sVL74k')
  149. if len(sheet) <= 21:
  150. # print('<=20行')
  151. return
  152. else:
  153. Feishu.dimension_range(log_type, crawler, 'sVL74k', 'ROWS', 22, 22)
  154. cls.del_search_key_from_feishu(log_type, crawler)
  155. except Exception as e:
  156. Common.logger(log_type, crawler).error(f"del_search_key_from_feishu异常:{e}\n")
  157. @classmethod
  158. def write_search_key_to_feishu(cls, log_type, crawler):
  159. Common.logger(log_type, crawler).info('清除 chlsfiles 文件夹')
  160. cls.remove_file(log_type, crawler)
  161. Common.logger(log_type, crawler).info('启动微信指数小程序')
  162. cls.start_wechat(log_type, crawler)
  163. Common.logger(log_type, crawler).info('获取 search_key')
  164. while True:
  165. search_key = cls.get_search_key(log_type, crawler)
  166. if search_key is None or search_key == "未找到search_key":
  167. time.sleep(3)
  168. Common.logger(log_type, crawler).info('未找到search_key,重启打开微信指数,获取 search_key')
  169. cls.start_wechat(log_type, crawler)
  170. cls.get_search_key(log_type, crawler)
  171. else:
  172. Common.logger(log_type, crawler).info(f'已获取 search_key,openid:{search_key}')
  173. Feishu.insert_columns(log_type, crawler, 'sVL74k', 'ROWS', 1, 2)
  174. time.sleep(1)
  175. time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time())))
  176. Feishu.update_values(log_type, crawler, 'sVL74k', 'A2:Z2', [[time_str, search_key[0], search_key[-1]]])
  177. cls.del_search_key_from_feishu(log_type, crawler)
  178. Common.logger(log_type, crawler).info(f"search_key:{search_key}写入飞书表成功\n")
  179. return
  180. if __name__ == '__main__':
  181. Searchkey.start_wechat('searchkey', 'weixinzhishu')
  182. # while True:
  183. # Searchkey.write_search_key_to_feishu('searchkey', 'weixinzhishu')
  184. # Common.logger('searchkey', 'weixinzhishu').info('休眠 1 分钟')
  185. # time.sleep(60)