zhufumao_recommend.py 15 KB

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