jxxf_recommend.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. 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, 'jxxf', '9Ws66h')
  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',
  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. time.sleep(20)
  78. Common.logger(log_type).info('下滑,展示小程序选择面板')
  79. size = driver.get_window_size()
  80. driver.swipe(int(size['width'] * 0.5), int(size['height'] * 0.2), int(size['width'] * 0.5),
  81. int(size['height'] * 0.8), 200)
  82. # 打开小程序"知青总群"
  83. time.sleep(5)
  84. Common.logger(log_type).info('打开小程序"祝福大家好才是真好"')
  85. driver.find_elements(By.XPATH, '//*[@text="祝福大家好才是真好"]')[-1].click()
  86. # 获取视频信息
  87. time.sleep(1)
  88. cls.get_recommend(log_type, driver, env)
  89. # 退出微信
  90. time.sleep(3)
  91. Common.logger(log_type).info('退出微信')
  92. cls.quit(log_type, driver)
  93. except Exception as e:
  94. Common.logger(log_type).error('start_wechat异常:{}\n', e)
  95. # 退出 APP
  96. @classmethod
  97. def quit(cls, log_type, driver: WebDriver):
  98. driver.quit()
  99. Common.logger(log_type).info('退出APP成功\n')
  100. # 切换 Handle
  101. @classmethod
  102. def switch_to_handle(cls, log_type, driver, env):
  103. try:
  104. windowHandles = driver.window_handles
  105. # Common.logger(log_type).info('windowHandles:{}', windowHandles)
  106. # 遍历所有的handles,找到当前页面所在的handle:如果pageSource有包含你想要的元素,就是所要找的handle
  107. # 小程序的页面来回切换也需要:遍历所有的handles,切换到元素所在的handle
  108. for handle in windowHandles:
  109. driver.switch_to.window(handle)
  110. time.sleep(1)
  111. try:
  112. video_list = driver.find_element(By.XPATH, '//wx-view[@class="nav-tab-container"]/*[2]')
  113. video_list.click()
  114. Common.logger(log_type).info('切换到视频列表成功\n')
  115. return
  116. except NoSuchElementException:
  117. pass
  118. except Exception as e:
  119. Common.logger(log_type).warning('切换到小程序Handle失败,重启APP:{}\n', e)
  120. cls.quit(log_type, driver)
  121. cls.i = 0
  122. cls.start_wechat(log_type, env)
  123. # 切换视频列表 Handle
  124. @classmethod
  125. def switch_to_video_list_handle(cls, log_type, driver, env):
  126. try:
  127. recommend_handles = driver.window_handles
  128. for recommend_handle in recommend_handles:
  129. # Common.logger(log_type).info("recommend_handle:{}", recommend_handle)
  130. try:
  131. driver.switch_to.window(recommend_handle)
  132. driver.find_element(By.XPATH, '//wx-view[@class="video-list-container"]')
  133. return
  134. except NoSuchElementException:
  135. pass
  136. except Exception as e:
  137. Common.logger(log_type).error('switch_to_video_list_handle异常:{}\n', e)
  138. cls.quit(log_type, driver)
  139. cls.i = 0
  140. cls.start_wechat(log_type, env)
  141. @classmethod
  142. def get_recommend(cls, log_type, driver, env):
  143. try:
  144. driver.implicitly_wait(10)
  145. # 鼠标左键点击, 1为x坐标, 2为y坐标
  146. time.sleep(10)
  147. Common.logger(log_type).info('关闭广告')
  148. size = driver.get_window_size()
  149. TouchAction(driver).tap(x=int(size['width'] * 0.5), y=int(size['height'] * 0.1)).perform()
  150. while True:
  151. try:
  152. # 切换到 webview
  153. webview = driver.contexts
  154. Common.logger(log_type).info('切换到小程序')
  155. driver.switch_to.context(webview[1])
  156. time.sleep(5)
  157. cls.switch_to_handle(log_type, driver, env)
  158. break
  159. except Exception as e:
  160. Common.logger(log_type).warning('切换到小程序失败,重启APP:{}\n', e)
  161. cls.quit(log_type, driver)
  162. cls.i = 0
  163. cls.start_wechat(log_type, env)
  164. time.sleep(5)
  165. while True:
  166. cls.i += 1
  167. # Common.logger(log_type).info('i:{}\n', cls.i)
  168. cls.switch_to_video_list_handle(log_type, driver, env)
  169. try:
  170. title = driver.find_element(
  171. By.XPATH,
  172. '//wx-view[@class="video-list-container"]/*[' + str(cls.i) + ']//*[@class="video-title"]')
  173. # 向上滚动至-元素可见
  174. # Common.logger(log_type).info('滑动视频标题至屏幕中间')
  175. driver.execute_script(
  176. "arguments[0].scrollIntoView({block:'center',inline:'center'})", title)
  177. video_title = title.get_attribute('innerHTML')
  178. play_cnt = driver.find_element(
  179. By.XPATH,
  180. '//wx-view[@class="video-list-container"]'
  181. '/*[' + str(cls.i) + ']//*[@class="video-play-num"]').get_attribute('innerHTML')
  182. cover_url = driver.find_element(
  183. By.XPATH,
  184. '//wx-view[@class="video-list-container"]'
  185. '/*[' + str(cls.i) + ']//*[@class="video-cover-img"]').get_attribute('src')
  186. except NoSuchElementException:
  187. title = 0
  188. video_title = 0
  189. play_cnt = 0
  190. cover_url = 0
  191. Common.logger(log_type).info('正在获取第{}条:{}', cls.i, video_title)
  192. if video_title == 0 or cover_url == 0:
  193. Common.logger(log_type).info('无效视频\n')
  194. elif '精美图文' in video_title:
  195. Common.logger(log_type).info('精美图文\n')
  196. elif any(word if word in video_title else False for word in cls.filter_words(log_type)) is True:
  197. Common.logger(log_type).info('视频已中过滤词:{}\n', video_title)
  198. elif video_title in [x for y in Feishu.get_values_batch(log_type, 'jxxf', 'd9e9b1') for x in y]:
  199. Common.logger(log_type).info('视频已下载\n')
  200. else:
  201. # video_url
  202. video_url = cls.get_url(log_type, driver, title)
  203. if video_url == '' or video_url is None:
  204. Common.logger(log_type).info('无法播放的视频\n')
  205. driver.press_keycode(4)
  206. else:
  207. Common.logger(log_type).info('play_cnt:{}', play_cnt)
  208. Common.logger(log_type).info('video_url:{}', video_url)
  209. # 下载视频
  210. Common.download_method(log_type, 'video', video_title, video_url)
  211. # 获取视频时长
  212. video_info = cls.get_video_info_from_local(
  213. "./videos/" + video_title + "/video.mp4")
  214. download_width = str(video_info[0])
  215. download_height = str(video_info[1])
  216. download_duration = video_info[2]
  217. # 视频时长<60s,直接删除
  218. if int(download_duration) < 40:
  219. # 删除视频文件夹
  220. shutil.rmtree("./videos/" + video_title + "/")
  221. Common.logger(log_type).info("时长:{}<40秒,删除成功\n", int(download_duration))
  222. driver.press_keycode(4)
  223. else:
  224. # 下载封面
  225. Common.download_method(log_type, 'cover', video_title, cover_url)
  226. # 保存视频信息至 "./videos/{download_video_title}/info.txt"
  227. with open("./videos/" + video_title
  228. + "/" + "info.txt", "a", encoding="UTF-8") as f_a:
  229. f_a.write("jixiangxingfu" + str(int(time.time())) + "\n" +
  230. str(video_title) + "\n" +
  231. str(int(download_duration)) + "\n" +
  232. str(int(float(
  233. play_cnt.split('万')[0]) * 10000)) + "\n" +
  234. '0' + "\n" +
  235. '0' + "\n" +
  236. '0' + "\n" +
  237. str(download_width) + '*' + str(download_height) + "\n" +
  238. str(int(time.time())) + "\n" +
  239. '吉祥幸福小程序' + "\n" +
  240. str(cover_url) + "\n" +
  241. str(video_url) + "\n" +
  242. str(cover_url) + "\n" +
  243. "jxxf" + str(int(time.time())))
  244. Common.logger(log_type).info("==========视频信息已保存至info.txt==========")
  245. # 上传视频
  246. Common.logger(log_type).info("开始上传视频:{}".format(video_title))
  247. if env == 'dev' and int(download_width) >= int(download_height):
  248. our_video_id = Publish.upload_and_publish(log_type, env, "width")
  249. our_video_link = "https://testadmin.piaoquantv.com/cms/post-detail/" + str(
  250. our_video_id) + "/info"
  251. elif env == 'dev' and int(download_width) < int(download_height):
  252. our_video_id = Publish.upload_and_publish(log_type, env, "height")
  253. our_video_link = "https://testadmin.piaoquantv.com/cms/post-detail/" + str(
  254. our_video_id) + "/info"
  255. elif env == 'prod' and int(download_width) >= int(download_height):
  256. our_video_id = Publish.upload_and_publish(log_type, env, "width")
  257. our_video_link = "https://admin.piaoquantv.com/cms/post-detail/" + str(
  258. our_video_id) + "/info"
  259. elif env == 'prod' and int(download_width) < int(download_height):
  260. our_video_id = Publish.upload_and_publish(log_type, env, "height")
  261. our_video_link = "https://admin.piaoquantv.com/cms/post-detail/" + str(
  262. our_video_id) + "/info"
  263. else:
  264. our_video_id = Publish.upload_and_publish(log_type, env, "width")
  265. our_video_link = "https://admin.piaoquantv.com/cms/post-detail/" + str(
  266. our_video_id) + "/info"
  267. Common.logger(log_type).info("视频上传完成:{}", video_title)
  268. # 保存视频 ID 到已下载表
  269. Common.logger(log_type).info("保存视频至已下载表:{}", video_title)
  270. # 视频ID工作表,插入首行
  271. Feishu.insert_columns(log_type, "jxxf", "d9e9b1", "ROWS", 1, 2)
  272. # 视频ID工作表,首行写入数据
  273. upload_time = int(time.time())
  274. values = [[time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(upload_time)),
  275. "推荐榜",
  276. video_title,
  277. our_video_link,
  278. play_cnt,
  279. int(download_duration),
  280. str(download_width) + '*' + str(download_height),
  281. cover_url,
  282. video_url]]
  283. time.sleep(1)
  284. Feishu.update_values(log_type, "jxxf", "d9e9b1", "F2:V2", values)
  285. Common.logger(log_type).info("视频:{},下载/上传成功\n", video_title)
  286. driver.press_keycode(4)
  287. if cls.i == 1000:
  288. cls.i = 0
  289. break
  290. except Exception as e:
  291. Common.logger(log_type).error('get_recommend异常,重启APP:{}\n', e)
  292. cls.quit(log_type, driver)
  293. cls.i = 0
  294. cls.start_wechat(log_type, env)
  295. @classmethod
  296. def get_url(cls, log_type, driver: WebDriver, title):
  297. try:
  298. Common.logger(log_type).info('点击视频标题,进入详情:{}', title)
  299. time.sleep(3)
  300. title.click()
  301. time.sleep(5)
  302. Common.logger(log_type).info('关闭广告')
  303. size = driver.get_window_size()
  304. TouchAction(driver).tap(x=int(size['width'] * 0.5), y=int(size['height'] * 0.1)).perform()
  305. time.sleep(10)
  306. info_handles = driver.window_handles
  307. for info_handle in info_handles:
  308. try:
  309. driver.switch_to.window(info_handle)
  310. video_url = driver.find_element(
  311. By.XPATH,
  312. '//wx-view[@class="one-screen-2"]/*[2]').get_attribute('src')
  313. return video_url
  314. except NoSuchElementException:
  315. pass
  316. except Exception as e:
  317. Common.logger(log_type).error('get_url异常:{}\n', e)
  318. driver.press_keycode(4)
  319. if __name__ == "__main__":
  320. # print(Recommend.filter_words('recommend'))
  321. Recommend.start_wechat('recommend', 'prod')
  322. pass