zhufumao_recommend.py 15 KB

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