zqttk_recommend.py 21 KB

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