kdjsfq.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2022/12/22
  4. import os
  5. import sys
  6. import time
  7. import ffmpeg
  8. from appium import webdriver
  9. from appium.webdriver.extensions.android.nativekey import AndroidKey
  10. from appium.webdriver.webdriver import WebDriver
  11. from selenium.common import NoSuchElementException
  12. from selenium.webdriver.common.by import By
  13. sys.path.append(os.getcwd())
  14. from main.common import Common
  15. from main.feishu_lib import Feishu
  16. from main.kdjsfq_publish import Publish
  17. class Recommend:
  18. # recommend_feed 翻页参数
  19. i = 0
  20. @classmethod
  21. def get_video_info_from_local(cls, log_type, video_path):
  22. probe = ffmpeg.probe(video_path)
  23. video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
  24. if video_stream is None:
  25. Common.logger(log_type).info('No video Stream found!')
  26. return
  27. width = int(video_stream['width'])
  28. height = int(video_stream['height'])
  29. duration = int(float(video_stream['duration']))
  30. return width, height, duration
  31. @classmethod
  32. def search_elements(cls, log_type, driver: WebDriver, element):
  33. try:
  34. windowHandles = driver.window_handles
  35. for handle in windowHandles:
  36. driver.switch_to.window(handle)
  37. time.sleep(1)
  38. if len(driver.find_elements(By.XPATH, element)) != 0:
  39. return driver.find_elements(By.XPATH, element)
  40. else:
  41. pass
  42. except Exception as e:
  43. Common.logger(log_type).error(f'search_element异常:{e}\n')
  44. @classmethod
  45. def start_wechat(cls, log_type, env):
  46. try:
  47. Common.logger(log_type).info('启动微信')
  48. caps = {
  49. "platformName": "Android", # 手机操作系统 Android / iOS
  50. "deviceName": "a0a65126", # 连接的设备名(模拟器或真机),安卓可以随便写
  51. "platforVersion": "11", # 手机对应的系统版本(Android 11)
  52. "appPackage": "com.tencent.mm", # 被测APP的包名,乐活圈 Android
  53. "appActivity": ".ui.LauncherUI", # 启动的Activity名
  54. "autoGrantPermissions": "true", # 让 appium 自动授权 base 权限,
  55. # 如果 noReset 为 True,则该条不生效(该参数为 Android 独有),对应的值为 True 或 False
  56. "unicodekeyboard": True, # 使用自带输入法,输入中文时填True
  57. "resetkeyboard": True, # 执行完程序恢复原来输入法
  58. "noReset": True, # 不重置APP
  59. "printPageSourceOnFailure": True, # 找不到元素时,appium log 会完整记录当前页面的 pagesource
  60. "newCommandTimeout": 6000, # 初始等待时间
  61. "automationName": "UiAutomator2", # 使用引擎,默认为 Appium,
  62. # 其中 Appium、UiAutomator2、Selendroid、Espresso 用于 Android,XCUITest 用于 iOS
  63. "showChromedriverLog": True,
  64. 'enableWebviewDetailsCollection': True,
  65. 'setWebContentsDebuggingEnabled': True,
  66. 'recreateChromeDriverSessions': True,
  67. # 'chromedriverExecutable': '/Users/wangkun/Downloads/chromedriver/chromedriver_v86/chromedriver',
  68. 'chromedriverExecutable': '/Users/lieyunye/Downloads/chromedriver_v86/chromedriver',
  69. "chromeOptions": {"androidProcess": "com.tencent.mm:appbrand0"},
  70. 'browserName': ''
  71. }
  72. driver = webdriver.Remote("http://localhost:4723/wd/hub", caps)
  73. driver.implicitly_wait(20)
  74. # 向下滑动页面,展示出小程序选择面板
  75. for i in range(120):
  76. try:
  77. # 发现微信消息 TAB,代表微信已启动成功
  78. if driver.find_elements(By.ID, 'com.tencent.mm:id/f2s'):
  79. break
  80. # 发现并关闭系统菜单栏
  81. elif driver.find_element(By.ID, 'com.android.systemui:id/dismiss_view'):
  82. Common.logger(log_type).info('发现并关闭系统下拉菜单栏')
  83. driver.find_element(By.ID, 'com.android.systemui:id/dismiss_view').click()
  84. else:
  85. pass
  86. except NoSuchElementException:
  87. time.sleep(1)
  88. Common.logger(log_type).info('下滑,展示小程序选择面板')
  89. size = driver.get_window_size()
  90. driver.swipe(int(size['width'] * 0.5), int(size['height'] * 0.2),
  91. int(size['width'] * 0.5), int(size['height'] * 0.8), 200)
  92. # 打开小程序"看到就是福气"
  93. time.sleep(3)
  94. Common.logger(log_type).info('打开小程序"看到就是福气"')
  95. driver.find_elements(By.XPATH, '//*[@text="看到就是福气"]')[-1].click()
  96. cls.get_recommend(log_type, driver, env)
  97. cls.quit(log_type, driver)
  98. except Exception as e:
  99. Common.logger(log_type).error(f'start_wechat异常:{e}\n')
  100. cmd = "cd ~ && source .bash_profile && adb kill-server && adb start-server"
  101. os.system(cmd)
  102. @classmethod
  103. def quit(cls, log_type, driver: WebDriver):
  104. driver.quit()
  105. Common.logger(log_type).info('退出微信成功\n')
  106. @classmethod
  107. def get_recommend(cls, log_type, driver: WebDriver, env):
  108. try:
  109. driver.implicitly_wait(15)
  110. Common.logger(log_type).info('切换到小程序\n')
  111. time.sleep(5)
  112. webviews = driver.contexts
  113. driver.switch_to.context(webviews[1])
  114. time.sleep(1)
  115. cls.search_elements(log_type, driver, '//wx-view[contains(text(),"视频")]')[-1].click()
  116. time.sleep(1)
  117. index = 0
  118. while True:
  119. if cls.search_elements(log_type, driver, '//body[@is="pages/max/max"]') is None:
  120. Common.logger(log_type).info('窗口已销毁\n')
  121. else:
  122. Common.logger(log_type).info('获取视频列表\n')
  123. video_elements = cls.search_elements(log_type, driver, '//wx-view[@class="spt-2"]')
  124. if video_elements is None or len(video_elements) == 0:
  125. Common.logger(log_type).info(f'video_elements:{video_elements}')
  126. return
  127. video_elements = video_elements[index:]
  128. if len(video_elements) == 0:
  129. Common.logger(log_type).info('到底啦~~~~~~~~~~~~~\n')
  130. return
  131. for video_element in video_elements:
  132. if video_element is None:
  133. Common.logger(log_type).info('到底啦~\n')
  134. return
  135. cls.i += 1
  136. cls.search_elements(log_type, driver, '//wx-view[@class="spt-2"]')
  137. Common.logger(log_type).info('拖动"视频"列表第{}个至屏幕中间', cls.i)
  138. time.sleep(3)
  139. driver.execute_script(
  140. "arguments[0].scrollIntoView({block:'center',inline:'center'})", video_element)
  141. video_title = cls.search_elements(log_type, driver, '//wx-view[@class="bt"]')[cls.i-1].get_attribute('innerHTML')
  142. cover_url = cls.search_elements(log_type, driver, '//wx-image[@class="spt-img"]')[cls.i-1].get_attribute('src')
  143. Common.logger(log_type).info(f'video_title:{video_title}')
  144. Common.logger(log_type).info(f'cover_url:{cover_url}')
  145. cls.download_publish(log_type, driver, video_element, video_title, cover_url, env)
  146. time.sleep(3)
  147. Common.logger(log_type).info('已抓取完一组视频,休眠10秒\n')
  148. time.sleep(10)
  149. index = index + len(video_elements)
  150. except Exception as e:
  151. Common.logger(log_type).error(f'get_recommend异常,重启APP:{e}\n')
  152. cls.i = 0
  153. cls.quit(log_type, driver)
  154. cls.start_wechat(log_type, env)
  155. @classmethod
  156. def get_video_url(cls, log_type, driver: WebDriver, video_element):
  157. try:
  158. time.sleep(1)
  159. # Common.logger(log_type).info('进入视频详情')
  160. video_element.click()
  161. time.sleep(3)
  162. video_url_element = cls.search_elements(log_type, driver, '//wx-video[@id="myVideo"]')
  163. if video_url_element is None or len(video_url_element) == 0:
  164. Common.logger(log_type).info('未获取到视频 URL')
  165. return 0
  166. else:
  167. return video_url_element[0].get_attribute('src')
  168. except Exception as e:
  169. Common.logger(log_type).error(f'get_video_info异常:{e}\n')
  170. @classmethod
  171. def download_publish(cls, log_type, driver: WebDriver, video_element, video_title, cover_url, env):
  172. try:
  173. if video_title == 0 or cover_url == 0:
  174. Common.logger(log_type).info('无效视频\n')
  175. elif video_title in [x for y in Feishu.get_values_batch(log_type, 'kdjsfq', 'ad3b6d') for x in y]:
  176. Common.logger(log_type).info('视频已下载\n')
  177. else:
  178. video_url = cls.get_video_url(log_type, driver, video_element)
  179. if video_url == 0:
  180. Common.logger(log_type).info('video_url:未获取到\n')
  181. driver.press_keycode(AndroidKey.BACK)
  182. time.sleep(1)
  183. else:
  184. Common.logger(log_type).info(f'video_url:{video_url}')
  185. # 下载视频
  186. Common.download_method(log_type, 'video', video_title, video_url)
  187. # # 获取视频时长
  188. # video_info = cls.get_video_info_from_local(log_type, "./videos/" + video_title + "/video.mp4")
  189. # video_width = str(video_info[0])
  190. # video_height = str(video_info[1])
  191. # duration = video_info[2]
  192. # 下载封面
  193. Common.download_method(log_type, 'cover', video_title, cover_url)
  194. # 保存视频信息至 "./videos/{download_video_title}/info.txt"
  195. with open("./videos/" + video_title
  196. + "/" + "info.txt", "a", encoding="UTF-8") as f_a:
  197. f_a.write("kdjsfq" + str(int(time.time())) + "\n" +
  198. str(video_title) + "\n" +
  199. # str(int(float(duration))) + "\n" +
  200. '100' + "\n" +
  201. '0' + "\n" +
  202. '0' + "\n" +
  203. '0' + "\n" +
  204. '0' + "\n" +
  205. # str(video_width) + '*' + str(video_height) + "\n" +
  206. '1920*1080' + "\n" +
  207. str(int(time.time())) + "\n" +
  208. '看到就是福气小程序' + "\n" +
  209. str(cover_url) + "\n" +
  210. str(video_url) + "\n" +
  211. str(cover_url) + "\n" +
  212. "kandaojiushifuqi" + str(int(time.time())))
  213. Common.logger(log_type).info("==========视频信息已保存至info.txt==========")
  214. # 上传视频
  215. Common.logger(log_type).info(f"开始上传视频:{video_title}")
  216. if env == 'dev':
  217. our_video_id = Publish.upload_and_publish(log_type, env, "play")
  218. our_video_link = "https://testadmin.piaoquantv.com/cms/post-detail/" + str(our_video_id) + "/info"
  219. else:
  220. our_video_id = Publish.upload_and_publish(log_type, env, "play")
  221. our_video_link = "https://admin.piaoquantv.com/cms/post-detail/" + str(our_video_id) + "/info"
  222. Common.logger(log_type).info(f"视频上传完成:{video_title}")
  223. # 保存视频 ID 到已下载表
  224. Common.logger(log_type).info(f"保存视频至已下载表:{video_title}")
  225. # 视频ID工作表,插入首行
  226. Feishu.insert_columns(log_type, "kdjsfq", "ad3b6d", "ROWS", 1, 2)
  227. # 视频ID工作表,首行写入数据
  228. upload_time = int(time.time())
  229. values = [[time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(upload_time)),
  230. "推荐榜",
  231. video_title,
  232. our_video_link,
  233. # int(duration),
  234. # str(video_width) + '*' + str(video_height),
  235. '',
  236. '',
  237. cover_url,
  238. video_url]]
  239. time.sleep(1)
  240. Feishu.update_values(log_type, "kdjsfq", "ad3b6d", "F2:V2", values)
  241. driver.press_keycode(AndroidKey.BACK)
  242. time.sleep(1)
  243. Common.logger(log_type).info(f"视频:{video_title},下载/上传成功\n")
  244. except Exception as e:
  245. Common.logger(log_type).error(f'download_publish异常:{e}\n')
  246. if __name__ == '__main__':
  247. Recommend.start_wechat('recommend', 'dev')