zmyx_recommend.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2022/11/3
  4. import os
  5. import shutil
  6. import sys
  7. import time
  8. import ffmpeg
  9. from appium import webdriver
  10. from appium.webdriver.extensions.android.nativekey import AndroidKey
  11. from appium.webdriver.webdriver import WebDriver
  12. from selenium.common import NoSuchElementException
  13. from selenium.webdriver.common.by import By
  14. sys.path.append(os.getcwd())
  15. from main.common import Common
  16. from main.feishu_lib import Feishu
  17. from main.zmyx_publish import Publish
  18. class ZMYXRecommend:
  19. i = 0
  20. @classmethod
  21. def get_video_info_from_local(cls, 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. print('No video stream found!')
  26. return
  27. width = int(video_stream['width'])
  28. height = int(video_stream['height'])
  29. duration = float(video_stream['duration'])
  30. return width, height, duration
  31. @classmethod
  32. def filter_words(cls, log_type):
  33. try:
  34. filter_words_sheet = Feishu.get_values_batch(log_type, 'zmyx', 'KS1Npq')
  35. filter_words_list = []
  36. for x in filter_words_sheet:
  37. for y in x:
  38. if y is None:
  39. pass
  40. else:
  41. filter_words_list.append(y)
  42. return filter_words_list
  43. except Exception as e:
  44. Common.logger(log_type).error('filter_words异常:{}', e)
  45. @classmethod
  46. def start_wechat(cls, log_type, env):
  47. try:
  48. Common.logger(log_type).info('启动微信')
  49. caps = {
  50. "platformName": "Android", # 手机操作系统 Android / iOS
  51. "deviceName": "a0a65126", # 连接的设备名(模拟器或真机),安卓可以随便写
  52. "platforVersion": "11", # 手机对应的系统版本(Android 11)
  53. "appPackage": "com.tencent.mm", # 被测APP的包名,乐活圈 Android
  54. "appActivity": ".ui.LauncherUI", # 启动的Activity名
  55. "autoGrantPermissions": "true", # 让 appium 自动授权 base 权限,
  56. # 如果 noReset 为 True,则该条不生效(该参数为 Android 独有),对应的值为 True 或 False
  57. "unicodekeyboard": True, # 使用自带输入法,输入中文时填True
  58. "resetkeyboard": True, # 执行完程序恢复原来输入法
  59. "noReset": True, # 不重置APP
  60. "printPageSourceOnFailure": True, # 找不到元素时,appium log 会完整记录当前页面的 pagesource
  61. "newCommandTimeout": 6000, # 初始等待时间
  62. "automationName": "UiAutomator2", # 使用引擎,默认为 Appium,
  63. # 其中 Appium、UiAutomator2、Selendroid、Espresso 用于 Android,XCUITest 用于 iOS
  64. "showChromedriverLog": True,
  65. 'enableWebviewDetailsCollection': True,
  66. 'setWebContentsDebuggingEnabled': True,
  67. 'recreateChromeDriverSessions': True,
  68. # 'chromedriverExecutable': '/Users/wangkun/Downloads/chromedriver_v86/chromedriver',
  69. 'chromedriverExecutable': '/Users/piaoquan/Downloads/chromedriver',
  70. "chromeOptions": {"androidProcess": "com.tencent.mm:appbrand0"},
  71. # "chromeOptions": {"androidProcess": "com.tencent.mm:tools"},
  72. 'browserName': ''
  73. }
  74. driver = webdriver.Remote("http://localhost:4723/wd/hub", caps)
  75. driver.implicitly_wait(20)
  76. # 向下滑动页面,展示出小程序选择面板
  77. for i in range(120):
  78. try:
  79. # 发现微信消息 TAB,代表微信已启动成功
  80. if driver.find_elements(By.ID, 'com.tencent.mm:id/f2s'):
  81. break
  82. # 发现并关闭系统菜单栏
  83. elif driver.find_element(By.ID, 'com.android.systemui:id/dismiss_view'):
  84. Common.logger(log_type).info('发现并关闭系统下拉菜单栏')
  85. driver.find_element(By.ID, 'com.android.systemui:id/dismiss_view').click()
  86. else:
  87. pass
  88. except NoSuchElementException:
  89. time.sleep(1)
  90. Common.logger(log_type).info('下滑,展示小程序选择面板')
  91. size = driver.get_window_size()
  92. driver.swipe(int(size['width'] * 0.5), int(size['height'] * 0.2),
  93. int(size['width'] * 0.5), int(size['height'] * 0.8), 200)
  94. # 打开小程序"众妙音信"
  95. time.sleep(5)
  96. Common.logger(log_type).info('打开小程序"西瓜说事"')
  97. driver.find_elements(By.XPATH, '//*[@text="西瓜说事"]')[-1].click()
  98. cls.get_zmyx_recommend(log_type, driver, env)
  99. cls.quit(log_type, driver)
  100. except Exception as e:
  101. Common.logger(log_type).error('start_wechat异常:{}\n', e)
  102. @classmethod
  103. def quit(cls, log_type, driver: WebDriver):
  104. driver.close()
  105. driver.quit()
  106. Common.logger(log_type).info('退出 APP 成功\n')
  107. @classmethod
  108. def search_element(cls, log_type, driver: WebDriver, element):
  109. try:
  110. windowHandles = driver.window_handles
  111. # 遍历所有的handles,找到当前页面所在的handle:如果pageSource有包含你想要的元素,就是所要找的handle
  112. # 小程序的页面来回切换也需要:遍历所有的handles,切换到元素所在的handle
  113. for handle in windowHandles:
  114. driver.switch_to.window(handle)
  115. time.sleep(1)
  116. if len(driver.find_elements(By.XPATH, element)) != 0:
  117. return driver.find_element(By.XPATH, element)
  118. else:
  119. pass
  120. except Exception as e:
  121. Common.logger(log_type).warning('search_element异常:{}\n', e)
  122. @classmethod
  123. def find_ad(cls, log_type, driver: WebDriver):
  124. Common.logger(log_type).info('切回 NATIVE APP')
  125. # webview = driver.contexts
  126. # Common.logger(log_type).info('contexts:{}', webview)
  127. driver.switch_to.context('NATIVE_APP')
  128. time.sleep(1)
  129. try:
  130. # driver.find_element(By.ID, 'com.tencent.mm:id/hj')
  131. cls.search_element(log_type, driver, 'com.tencent.mm:id/hj')
  132. Common.logger(log_type).info('发现广告')
  133. return True
  134. except NoSuchElementException:
  135. Common.logger(log_type).info('未发现广告,切换到小程序')
  136. webview = driver.contexts
  137. driver.switch_to.context(webview[1])
  138. return False
  139. @classmethod
  140. def close_ad(cls, log_type, driver: WebDriver):
  141. if cls.find_ad(log_type, driver) is True:
  142. while True:
  143. try:
  144. # driver.find_element(By.ID, 'com.tencent.mm:id/ho')
  145. cls.search_element(log_type, driver, 'com.tencent.mm:id/ho')
  146. Common.logger(log_type).info('广告播放完毕,关闭广告')
  147. driver.press_keycode(AndroidKey.BACK)
  148. Common.logger(log_type).info('切换到小程序')
  149. webview = driver.contexts
  150. driver.switch_to.context(webview[1])
  151. return
  152. except NoSuchElementException:
  153. time.sleep(1)
  154. else:
  155. pass
  156. @classmethod
  157. def get_video_url(cls, log_type, driver: WebDriver, play_btn):
  158. try:
  159. if play_btn is None or play_btn == 0:
  160. Common.logger(log_type).info('标题为空\n')
  161. return 0
  162. else:
  163. Common.logger(log_type).info('进入视频详情')
  164. play_btn.click()
  165. # time.sleep(5)
  166. # cls.find_ad(log_type, driver)
  167. # cls.close_ad(log_type, driver)
  168. time.sleep(5)
  169. video_url_element = cls.search_element(log_type, driver, '//wx-video[@class="videoh"]')
  170. if video_url_element is None:
  171. return 0
  172. else:
  173. return video_url_element.get_attribute('src')
  174. except Exception as e:
  175. Common.logger(log_type).error('get_video_url异常:{}\n', e)
  176. @classmethod
  177. def get_zmyx_recommend(cls, log_type, driver: WebDriver, env):
  178. try:
  179. time.sleep(5)
  180. Common.logger(log_type).info('切换到小程序\n')
  181. webview = driver.contexts
  182. driver.switch_to.context(webview[1])
  183. # time.sleep(5)
  184. # Common.logger(log_type).info('切换到"综合"列表\n')
  185. # cls.search_element(log_type, driver, '//*[@class="index--navbar-list"]/*[1]').click()
  186. time.sleep(1)
  187. while True:
  188. cls.i += 1
  189. Common.logger(log_type).info('进入"综合"列表')
  190. cls.search_element(log_type, driver, '//wx-view[@id="top_wait"]')
  191. # try:
  192. title_element = cls.search_element(
  193. log_type, driver, '//wx-view[@class="uls"]/*['+str(cls.i)+']//span/*[1]')
  194. play_btn = cls.search_element(
  195. log_type, driver, '//wx-view[@class="uls"]/*['+str(cls.i)+']//wx-image[@class="wx-image"]')
  196. driver.execute_script(
  197. "arguments[0].scrollIntoView({block:'center',inline:'center'})", title_element)
  198. video_title = title_element.get_attribute('innerHTML').replace('\n', '').replace(' ', '')
  199. play_cnt = cls.search_element(
  200. log_type, driver, '//wx-view[@class="uls"]/*['+str(cls.i)+']//span/*[2]').get_attribute('innerHTML')
  201. cover_url = cls.search_element(
  202. log_type, driver, '//wx-view[@class="uls"]/*['+str(cls.i)+']//wx-image').get_attribute('src')
  203. # except JavascriptException:
  204. # play_btn = 0
  205. # video_title = 0
  206. # play_cnt = 0
  207. # cover_url = 0
  208. Common.logger(log_type).info('第{}条视频:{}', cls.i, video_title)
  209. if video_title == 0 or play_btn == 0 or cover_url == 0:
  210. Common.logger(log_type).info('无效视频\n')
  211. elif video_title in [x for y in Feishu.get_values_batch(log_type, 'zmyx', '19c772') for x in y]:
  212. Common.logger(log_type).info('视频已下载\n')
  213. elif any(word if word in video_title else False for word in cls.filter_words(log_type)) is True:
  214. Common.logger(log_type).info('视频已中过滤词\n')
  215. else:
  216. video_url = cls.get_video_url(log_type, driver, play_btn)
  217. if video_url == 0:
  218. Common.logger(log_type).info('未找到视频播放地址\n')
  219. else:
  220. Common.logger(log_type).info('play_cnt:{}', play_cnt)
  221. Common.logger(log_type).info('video_url:{}\n', video_url)
  222. # 下载视频
  223. Common.download_method(log_type, 'video', video_title, video_url)
  224. # 获取视频时长
  225. video_info = cls.get_video_info_from_local(
  226. "./videos/" + video_title + "/video.mp4")
  227. download_width = str(video_info[0])
  228. download_height = str(video_info[1])
  229. download_duration = video_info[2]
  230. # 视频时长<40s,直接删除
  231. if int(download_duration) < 40:
  232. # 删除视频文件夹
  233. shutil.rmtree("./videos/" + video_title + "/")
  234. Common.logger(log_type).info("时长:{}<40秒,删除成功\n", int(download_duration))
  235. driver.press_keycode(AndroidKey.BACK)
  236. else:
  237. # 下载封面
  238. Common.download_method(log_type, 'cover', video_title, cover_url)
  239. # 保存视频信息至 "./videos/{download_video_title}/info.txt"
  240. with open("./videos/" + video_title
  241. + "/" + "info.txt", "a", encoding="UTF-8") as f_a:
  242. f_a.write("zhongmiaoyinxin" + str(int(time.time())) + "\n" +
  243. str(video_title) + "\n" +
  244. str(int(download_duration)) + "\n" +
  245. str(int(float(
  246. play_cnt.split('万')[0]) * 10000)) + "\n" +
  247. '0' + "\n" +
  248. '0' + "\n" +
  249. '0' + "\n" +
  250. str(download_width) + '*' + str(download_height) + "\n" +
  251. str(int(time.time())) + "\n" +
  252. '众妙音信小程序' + "\n" +
  253. str(cover_url) + "\n" +
  254. str(video_url) + "\n" +
  255. str(cover_url) + "\n" +
  256. "zmyx" + str(int(time.time())))
  257. Common.logger(log_type).info("==========视频信息已保存至info.txt==========")
  258. # 上传视频
  259. Common.logger(log_type).info("开始上传视频:{}".format(video_title))
  260. if env == 'dev':
  261. our_video_id = Publish.upload_and_publish(log_type, env, "width")
  262. our_video_link = "https://testadmin.piaoquantv.com/cms/post-detail/" + str(
  263. our_video_id) + "/info"
  264. else:
  265. our_video_id = Publish.upload_and_publish(log_type, env, "width")
  266. our_video_link = "https://admin.piaoquantv.com/cms/post-detail/" + str(
  267. our_video_id) + "/info"
  268. Common.logger(log_type).info("视频上传完成:{}", video_title)
  269. # 保存视频 ID 到已下载表
  270. Common.logger(log_type).info("保存视频至已下载表:{}", video_title)
  271. # 视频ID工作表,插入首行
  272. Feishu.insert_columns(log_type, "zmyx", "19c772", "ROWS", 1, 2)
  273. # 视频ID工作表,首行写入数据
  274. upload_time = int(time.time())
  275. values = [[time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(upload_time)),
  276. "推荐榜",
  277. video_title,
  278. our_video_link,
  279. play_cnt,
  280. int(download_duration),
  281. str(download_width) + '*' + str(download_height),
  282. cover_url,
  283. video_url]]
  284. time.sleep(1)
  285. Feishu.update_values(log_type, "zmyx", "19c772", "F2:V2", values)
  286. Common.logger(log_type).info("视频:{},下载/上传成功\n", video_title)
  287. driver.press_keycode(AndroidKey.BACK)
  288. if cls.i == 1000:
  289. cls.i = 0
  290. break
  291. except Exception as e:
  292. Common.logger(log_type).error('get_zmyx_recommend异常,重启APP:{}\n', e)
  293. cls.i = 0
  294. cls.quit(log_type, driver)
  295. cls.start_wechat(log_type, env)
  296. if __name__ == '__main__':
  297. ZMYXRecommend.start_wechat('recommend', 'dev')
  298. pass