zmyx_recommend.py 16 KB

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