zhiqingzongqun_recommend.py 22 KB

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