jxxf_recommend.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2022/10/22
  4. import os
  5. import shutil
  6. import sys
  7. import time
  8. import ffmpeg
  9. from appium import webdriver
  10. from appium.webdriver.common.touch_action import TouchAction
  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.publish import Publish
  18. class Recommend:
  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. # num_frames = int(video_stream['nb_frames'])
  30. # fps = int(video_stream['r_frame_rate'].split('/')[0]) / int(video_stream['r_frame_rate'].split('/')[1])
  31. duration = float(video_stream['duration'])
  32. return width, height, duration
  33. @classmethod
  34. def filter_words(cls, log_type):
  35. try:
  36. filter_words_sheet = Feishu.get_values_batch(log_type, 'jxxf', '9Ws66h')
  37. filter_words_list = []
  38. for x in filter_words_sheet:
  39. for y in x:
  40. if y is None:
  41. pass
  42. else:
  43. filter_words_list.append(y)
  44. return filter_words_list
  45. except Exception as e:
  46. Common.logger(log_type).error('filter_words异常:{}', e)
  47. @classmethod
  48. def start_wechat(cls, log_type, env):
  49. try:
  50. Common.logger(log_type).info('启动微信')
  51. caps = {
  52. "platformName": "Android", # 手机操作系统 Android / iOS
  53. "deviceName": "Android", # 连接的设备名(模拟器或真机),安卓可以随便写
  54. "platforVersion": "11", # 手机对应的系统版本(Android 11)
  55. "appPackage": "com.tencent.mm", # 被测APP的包名,乐活圈 Android
  56. "appActivity": ".ui.LauncherUI", # 启动的Activity名
  57. "autoGrantPermissions": "true", # 让 appium 自动授权 base 权限,
  58. # 如果 noReset 为 True,则该条不生效(该参数为 Android 独有),对应的值为 True 或 False
  59. "unicodekeyboard": True, # 使用自带输入法,输入中文时填True
  60. "resetkeyboard": True, # 执行完程序恢复原来输入法
  61. "noReset": True, # 不重置APP
  62. "printPageSourceOnFailure": True, # 找不到元素时,appium log 会完整记录当前页面的 pagesource
  63. "newCommandTimeout": 6000, # 初始等待时间
  64. "automationName": "UiAutomator2", # 使用引擎,默认为 Appium,
  65. # 其中 Appium、UiAutomator2、Selendroid、Espresso 用于 Android,XCUITest 用于 iOS
  66. "showChromedriverLog": True,
  67. 'enableWebviewDetailsCollection': True,
  68. 'setWebContentsDebuggingEnabled': True,
  69. 'recreateChromeDriverSessions': True,
  70. # 'chromedriverExecutable': '/Users/wangkun/Downloads/chromedriver',
  71. 'chromedriverExecutable': '/Users/piaoquan/Downloads/chromedriver',
  72. "chromeOptions": {"androidProcess": "com.tencent.mm:appbrand0"},
  73. # "chromeOptions": {"androidProcess": "com.tencent.mm:tools"},
  74. 'browserName': ''
  75. }
  76. driver = webdriver.Remote("http://localhost:4723/wd/hub", caps)
  77. driver.implicitly_wait(20)
  78. # 向下滑动页面,展示出小程序选择面板
  79. time.sleep(20)
  80. Common.logger(log_type).info('下滑,展示小程序选择面板')
  81. size = driver.get_window_size()
  82. driver.swipe(int(size['width'] * 0.5), int(size['height'] * 0.2), int(size['width'] * 0.5),
  83. int(size['height'] * 0.8), 200)
  84. # 打开小程序"知青总群"
  85. time.sleep(5)
  86. Common.logger(log_type).info('打开小程序"祝福大家好才是真好"')
  87. driver.find_elements(By.XPATH, '//*[@text="祝福大家好才是真好"]')[-1].click()
  88. # 获取视频信息
  89. time.sleep(1)
  90. cls.get_recommend(log_type, driver, env)
  91. # 退出微信
  92. time.sleep(3)
  93. Common.logger(log_type).info('退出微信')
  94. cls.quit(log_type, driver)
  95. except Exception as e:
  96. Common.logger(log_type).error('start_wechat异常:{}\n', e)
  97. # 退出 APP
  98. @classmethod
  99. def quit(cls, log_type, driver: WebDriver):
  100. driver.quit()
  101. Common.logger(log_type).info('退出APP成功\n')
  102. # 切换 Handle
  103. @classmethod
  104. def switch_to_handle(cls, log_type, driver, env):
  105. try:
  106. windowHandles = driver.window_handles
  107. # Common.logger(log_type).info('windowHandles:{}', windowHandles)
  108. # 遍历所有的handles,找到当前页面所在的handle:如果pageSource有包含你想要的元素,就是所要找的handle
  109. # 小程序的页面来回切换也需要:遍历所有的handles,切换到元素所在的handle
  110. for handle in windowHandles:
  111. driver.switch_to.window(handle)
  112. time.sleep(1)
  113. try:
  114. video_list = driver.find_element(By.XPATH, '//wx-view[@class="nav-tab-container"]/*[2]')
  115. video_list.click()
  116. Common.logger(log_type).info('切换到视频列表成功\n')
  117. return
  118. except NoSuchElementException:
  119. pass
  120. except Exception as e:
  121. Common.logger(log_type).warning('切换到小程序Handle失败,重启APP:{}\n', e)
  122. cls.quit(log_type, driver)
  123. cls.i = 0
  124. cls.start_wechat(log_type, env)
  125. # 切换视频列表 Handle
  126. @classmethod
  127. def switch_to_video_list_handle(cls, log_type, driver, env):
  128. try:
  129. recommend_handles = driver.window_handles
  130. for recommend_handle in recommend_handles:
  131. # Common.logger(log_type).info("recommend_handle:{}", recommend_handle)
  132. try:
  133. driver.switch_to.window(recommend_handle)
  134. driver.find_element(By.XPATH, '//wx-view[@class="video-list-container"]')
  135. return
  136. except NoSuchElementException:
  137. pass
  138. except Exception as e:
  139. Common.logger(log_type).error('switch_to_video_list_handle异常:{}\n', e)
  140. cls.quit(log_type, driver)
  141. cls.i = 0
  142. cls.start_wechat(log_type, env)
  143. @classmethod
  144. def get_recommend(cls, log_type, driver, env):
  145. try:
  146. driver.implicitly_wait(10)
  147. # 鼠标左键点击, 1为x坐标, 2为y坐标
  148. time.sleep(10)
  149. Common.logger(log_type).info('关闭广告')
  150. size = driver.get_window_size()
  151. TouchAction(driver).tap(x=int(size['width'] * 0.5), y=int(size['height'] * 0.1)).perform()
  152. while True:
  153. try:
  154. # 切换到 webview
  155. webview = driver.contexts
  156. Common.logger(log_type).info('切换到小程序')
  157. driver.switch_to.context(webview[1])
  158. time.sleep(5)
  159. cls.switch_to_handle(log_type, driver, env)
  160. break
  161. except Exception as e:
  162. Common.logger(log_type).warning('切换到小程序失败,重启APP:{}\n', e)
  163. cls.quit(log_type, driver)
  164. cls.i = 0
  165. cls.start_wechat(log_type, env)
  166. time.sleep(5)
  167. while True:
  168. cls.i += 1
  169. Common.logger(log_type).info('i:{}\n', cls.i)
  170. cls.switch_to_video_list_handle(log_type, driver, env)
  171. try:
  172. title = driver.find_element(
  173. By.XPATH,
  174. '//wx-view[@class="video-list-container"]/*[' + str(cls.i) + ']//*[@class="video-title"]')
  175. # 向上滚动至-元素可见
  176. # Common.logger(log_type).info('滑动视频标题至屏幕中间')
  177. driver.execute_script(
  178. "arguments[0].scrollIntoView({block:'center',inline:'center'})", title)
  179. video_title = title.get_attribute('innerHTML')
  180. play_cnt = driver.find_element(
  181. By.XPATH,
  182. '//wx-view[@class="video-list-container"]'
  183. '/*[' + str(cls.i) + ']//*[@class="video-play-num"]').get_attribute('innerHTML')
  184. cover_url = driver.find_element(
  185. By.XPATH,
  186. '//wx-view[@class="video-list-container"]'
  187. '/*[' + str(cls.i) + ']//*[@class="video-cover-img"]').get_attribute('src')
  188. except NoSuchElementException:
  189. title = 0
  190. video_title = 0
  191. play_cnt = 0
  192. cover_url = 0
  193. Common.logger(log_type).info('正在获取第{}条:{}', cls.i, video_title)
  194. if video_title == 0 or cover_url == 0:
  195. Common.logger(log_type).info('无效视频\n')
  196. elif '精美图文' in video_title:
  197. Common.logger(log_type).info('精美图文\n')
  198. elif any(word if word in video_title else False for word in cls.filter_words(log_type)) is True:
  199. Common.logger(log_type).info('视频已中过滤词:{}\n', video_title)
  200. elif video_title in [x for y in Feishu.get_values_batch(log_type, 'jxxf', 'd9e9b1') for x in y]:
  201. Common.logger(log_type).info('视频已下载\n')
  202. else:
  203. # video_url
  204. video_url = cls.get_url(log_type, driver, title)
  205. if video_url == '' or video_url is None:
  206. Common.logger(log_type).info('无法播放的视频\n')
  207. driver.press_keycode(4)
  208. else:
  209. Common.logger(log_type).info('play_cnt:{}', play_cnt)
  210. Common.logger(log_type).info('video_url:{}', video_url)
  211. # 下载视频
  212. Common.download_method(log_type, 'video', video_title, video_url)
  213. # 获取视频时长
  214. video_info = cls.get_video_info_from_local(
  215. "./videos/" + video_title + "/video.mp4")
  216. download_width = str(video_info[0])
  217. download_height = str(video_info[1])
  218. download_duration = video_info[2]
  219. # 视频时长<60s,直接删除
  220. if int(download_duration) < 40:
  221. # 删除视频文件夹
  222. shutil.rmtree("./videos/" + video_title + "/")
  223. Common.logger(log_type).info("时长:{}<40秒,删除成功\n", int(download_duration))
  224. driver.press_keycode(4)
  225. else:
  226. # 下载封面
  227. Common.download_method(log_type, 'cover', video_title, cover_url)
  228. # 保存视频信息至 "./videos/{download_video_title}/info.txt"
  229. with open("./videos/" + video_title
  230. + "/" + "info.txt", "a", encoding="UTF-8") as f_a:
  231. f_a.write(str(int(time.time())) + "\n" +
  232. str(video_title) + "\n" +
  233. str(int(download_duration)) + "\n" +
  234. str(int(float(
  235. play_cnt.split('万')[0]) * 10000)) + "\n" +
  236. '0' + "\n" +
  237. '0' + "\n" +
  238. '0' + "\n" +
  239. str(download_width) + '*' + str(download_height) + "\n" +
  240. str(int(time.time())) + "\n" +
  241. '吉祥幸福小程序' + "\n" +
  242. str(cover_url) + "\n" +
  243. str(video_url) + "\n" +
  244. str(cover_url) + "\n" +
  245. "jxxf" + str(int(time.time())))
  246. Common.logger(log_type).info("==========视频信息已保存至info.txt==========")
  247. # 上传视频
  248. Common.logger(log_type).info("开始上传视频:{}".format(video_title))
  249. if env == 'dev' and int(download_width) >= int(download_height):
  250. our_video_id = Publish.upload_and_publish(log_type, env, "width")
  251. our_video_link = "https://testadmin.piaoquantv.com/cms/post-detail/" + str(
  252. our_video_id) + "/info"
  253. elif env == 'dev' and int(download_width) < int(download_height):
  254. our_video_id = Publish.upload_and_publish(log_type, env, "height")
  255. our_video_link = "https://testadmin.piaoquantv.com/cms/post-detail/" + str(
  256. our_video_id) + "/info"
  257. elif env == 'prod' and int(download_width) >= int(download_height):
  258. our_video_id = Publish.upload_and_publish(log_type, env, "width")
  259. our_video_link = "https://admin.piaoquantv.com/cms/post-detail/" + str(
  260. our_video_id) + "/info"
  261. elif env == 'prod' and int(download_width) < int(download_height):
  262. our_video_id = Publish.upload_and_publish(log_type, env, "height")
  263. our_video_link = "https://admin.piaoquantv.com/cms/post-detail/" + str(
  264. our_video_id) + "/info"
  265. else:
  266. our_video_id = Publish.upload_and_publish(log_type, env, "width")
  267. our_video_link = "https://admin.piaoquantv.com/cms/post-detail/" + str(
  268. our_video_id) + "/info"
  269. Common.logger(log_type).info("视频上传完成:{}", video_title)
  270. # 保存视频 ID 到已下载表
  271. Common.logger(log_type).info("保存视频至已下载表:{}", video_title)
  272. # 视频ID工作表,插入首行
  273. Feishu.insert_columns(log_type, "jxxf", "d9e9b1", "ROWS", 1, 2)
  274. # 视频ID工作表,首行写入数据
  275. upload_time = int(time.time())
  276. values = [[time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(upload_time)),
  277. "推荐榜",
  278. video_title,
  279. our_video_link,
  280. play_cnt,
  281. int(download_duration),
  282. str(download_width) + '*' + str(download_height),
  283. cover_url,
  284. video_url]]
  285. time.sleep(1)
  286. Feishu.update_values(log_type, "jxxf", "d9e9b1", "F2:V2", values)
  287. Common.logger(log_type).info("视频:{},下载/上传成功\n", video_title)
  288. driver.press_keycode(4)
  289. if cls.i == 1000:
  290. cls.i = 0
  291. break
  292. except Exception:
  293. Common.logger(log_type).error('get_recommend异常,重启APP\n')
  294. cls.quit(log_type, driver)
  295. cls.i = 0
  296. cls.start_wechat(log_type, env)
  297. @classmethod
  298. def get_url(cls, log_type, driver: WebDriver, title):
  299. try:
  300. Common.logger(log_type).info('进入视频详情')
  301. title.click()
  302. time.sleep(5)
  303. Common.logger(log_type).info('关闭广告')
  304. size = driver.get_window_size()
  305. TouchAction(driver).tap(x=int(size['width'] * 0.5), y=int(size['height'] * 0.1)).perform()
  306. time.sleep(10)
  307. info_handles = driver.window_handles
  308. for info_handle in info_handles:
  309. try:
  310. driver.switch_to.window(info_handle)
  311. video_url = driver.find_element(
  312. By.XPATH,
  313. '//wx-view[@class="one-screen-2"]/*[2]').get_attribute('src')
  314. return video_url
  315. except NoSuchElementException:
  316. pass
  317. except Exception as e:
  318. Common.logger(log_type).error('get_url异常:{}\n', e)
  319. driver.press_keycode(4)
  320. if __name__ == "__main__":
  321. # print(Recommend.filter_words('recommend'))
  322. Recommend.start_wechat('recommend', 'dev')
  323. pass