zhiqingzongqun_recommend.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. "chromeOptions": {"androidProcess": "com.tencent.mm:appbrand0"},
  86. # "chromeOptions": {"androidProcess": "com.tencent.mm:tools"},
  87. 'browserName': ''
  88. }
  89. driver = webdriver.Remote("http://localhost:4723/wd/hub", caps)
  90. driver.implicitly_wait(20)
  91. # 向下滑动页面,展示出小程序选择面板
  92. time.sleep(10)
  93. Common.logger(log_type).info('下滑,展示小程序选择面板')
  94. size = driver.get_window_size()
  95. driver.swipe(int(size['width'] * 0.5), int(size['height'] * 0.2), int(size['width'] * 0.5),
  96. int(size['height'] * 0.8), 200)
  97. # 打开小程序"知青总群"
  98. time.sleep(3)
  99. Common.logger(log_type).info('打开小程序"知青总群"')
  100. driver.find_elements(By.XPATH, '//*[@text="知青总群"]')[-1].click()
  101. # 获取视频信息
  102. time.sleep(1)
  103. cls.get_recommend(log_type, driver, env)
  104. # 退出微信
  105. time.sleep(3)
  106. Common.logger(log_type).info('退出微信')
  107. cls.quit(log_type, driver)
  108. except Exception as e:
  109. Common.logger(log_type).error('start_wechat异常:{}\n', e)
  110. # 退出 APP
  111. @classmethod
  112. def quit(cls, log_type, driver: WebDriver):
  113. driver.quit()
  114. Common.logger(log_type).info('退出 APP 成功\n')
  115. # 切换 Handle
  116. @classmethod
  117. def switch_to_handle(cls, log_type, driver, env, text):
  118. try:
  119. windowHandles = driver.window_handles
  120. Common.logger(log_type).info('windowHandles:{}', windowHandles)
  121. # 遍历所有的handles,找到当前页面所在的handle:如果pageSource有包含你想要的元素,就是所要找的handle
  122. # 小程序的页面来回切换也需要:遍历所有的handles,切换到元素所在的handle
  123. for handle in windowHandles:
  124. Common.logger(log_type).info('切换到对应的windowHandle', handle)
  125. driver.switch_to.window(handle)
  126. time.sleep(3)
  127. if driver.page_source.find(text) != -1:
  128. break
  129. except Exception as e:
  130. Common.logger(log_type).warning('切换到小程序handle失败,重启APP:{}\n', e)
  131. cls.quit(log_type, driver)
  132. cls.start_wechat(log_type, env)
  133. @classmethod
  134. def get_recommend(cls, log_type, driver: WebDriver, env):
  135. try:
  136. driver.implicitly_wait(5)
  137. # 鼠标左键点击, 1为x坐标, 2为y坐标
  138. time.sleep(10)
  139. Common.logger(log_type).info('关闭广告')
  140. size = driver.get_window_size()
  141. TouchAction(driver).tap(x=int(size['width'] * 0.5), y=int(size['height'] * 0.1)).perform()
  142. while True:
  143. try:
  144. # 切换到 webview
  145. webview = driver.contexts
  146. Common.logger(log_type).info('webview:{}', webview)
  147. Common.logger(log_type).info('切换到小程序\n')
  148. # driver.switch_to.context('WEBVIEW_com.tencent.mm:appbrand0')
  149. driver.switch_to.context(webview[1])
  150. time.sleep(5)
  151. cls.switch_to_handle(log_type, driver, env, '知青总群')
  152. break
  153. except Exception as e:
  154. Common.logger(log_type).warning('切换到小程序失败,重启APP:{}\n', e)
  155. cls.quit(log_type, driver)
  156. cls.start_wechat(log_type, env)
  157. time.sleep(5)
  158. Common.logger(log_type).info('获取推荐列表视频信息')
  159. while True:
  160. cls.i += 1
  161. Common.logger(log_type).info('正在获取第{}条视频信息', cls.i)
  162. recommend_handles = driver.window_handles
  163. for recommend_handle in recommend_handles:
  164. try:
  165. driver.switch_to.window(recommend_handle)
  166. # video_title
  167. try:
  168. title = driver.find_element(
  169. By.XPATH,
  170. '//*[@class="videolistbox videolist--videolistbox"]'
  171. '/*[' + str(cls.i) + ']//*[@class="video_title videolist--video_title"]')
  172. # 向上滚动至-元素可见
  173. Common.logger(log_type).info('滑动视频标题至屏幕中间')
  174. driver.execute_script(
  175. "arguments[0].scrollIntoView({block:'center',inline:'center'})", title)
  176. video_title = title.get_attribute('innerHTML')
  177. except NoSuchElementException:
  178. title = 0
  179. video_title = 0
  180. # play_cnt
  181. try:
  182. play_cnt = driver.find_element(
  183. By.XPATH,
  184. '//*[@class="videolistbox videolist--videolistbox"]'
  185. '/*[' + str(cls.i) + ']//*[@class="clickbox videolist--clickbox"]')\
  186. .get_attribute('innerHTML')
  187. except NoSuchElementException:
  188. play_cnt = 0
  189. # cover_url
  190. try:
  191. cover_url = driver.find_element(
  192. By.XPATH,
  193. '//*[@class="videolistbox videolist--videolistbox"]'
  194. '/*[' + str(cls.i) + ']//*[@class="itemimage videolist--itemimage"]')\
  195. .get_attribute('src')
  196. except Exception as e:
  197. Common.logger(log_type).error('cover_url异常:{}', e)
  198. cover_url = 0
  199. # video_url
  200. if title == 0 or video_title == 0:
  201. video_url = 0
  202. elif '精美图文' in video_title:
  203. video_url = 0
  204. else:
  205. Common.logger(log_type).info('进入视频详情:{}', video_title)
  206. title.click()
  207. time.sleep(5)
  208. Common.logger(log_type).info('关闭广告')
  209. size = driver.get_window_size()
  210. TouchAction(driver).tap(x=int(size['width'] * 0.5), y=int(size['height'] * 0.1)).perform()
  211. time.sleep(10)
  212. info_handles = driver.window_handles
  213. for info_handle in info_handles:
  214. try:
  215. driver.switch_to.window(info_handle)
  216. url = driver.find_element(
  217. By.XPATH,
  218. '//*[@class="wx-swiper-slide-frame"]'
  219. '/*[2]//*[@class="video_item videoswiper--video_item"]')
  220. video_url = url.get_attribute('src')
  221. break
  222. except NoSuchElementException:
  223. pass
  224. Common.logger(log_type).info('video_title:{}', video_title)
  225. Common.logger(log_type).info('play_cnt:{}', play_cnt)
  226. Common.logger(log_type).info('video_url:{}', video_url)
  227. if video_title == 0 or cover_url == 0 or video_url == 0:
  228. Common.logger(log_type).info('无效视频\n')
  229. elif '精美图文' in video_title:
  230. Common.logger(log_type).info('精美图文\n')
  231. elif any(word if word in video_title else False for word in cls.filter_words(log_type)) is True:
  232. Common.logger(log_type).info('视频已中过滤词:{}', video_title)
  233. elif video_title in [x for y in Feishu.get_values_batch(
  234. log_type, 'zhiqingzongqun', 'Z48hlq') for x in y]:
  235. Common.logger(log_type).info('视频已存在\n')
  236. driver.press_keycode(4)
  237. elif video_title in [x for y in Feishu.get_values_batch(
  238. log_type, 'zhiqingzongqun', '1a88b3') for x in y]:
  239. Common.logger(log_type).info('视频已下载\n')
  240. driver.press_keycode(4)
  241. else:
  242. Feishu.insert_columns(log_type, 'zhiqingzongqun', 'Z48hlq', 'ROWS', 1, 2)
  243. get_feeds_time = int(time.time())
  244. values = [[time.strftime('%Y/%m/%d %H:%M:%S', time.localtime(get_feeds_time)),
  245. '推荐榜',
  246. str(video_title),
  247. play_cnt,
  248. cover_url,
  249. video_url]]
  250. time.sleep(1)
  251. Feishu.update_values(log_type, 'zhiqingzongqun', 'Z48hlq', 'A2:Z2', values)
  252. Common.logger(log_type).info('视频信息写入飞书文档成功\n')
  253. driver.press_keycode(4)
  254. cls.download_publish(log_type, env)
  255. except Exception as e:
  256. Common.logger(log_type).error('switch_to.window(recommend_handle)异常:{}', e)
  257. pass
  258. if cls.i == 200:
  259. cls.i = 0
  260. break
  261. except Exception as e:
  262. Common.logger(log_type).error('get_recommend异常:{},重启 APP\n', e)
  263. cls.quit(log_type, driver)
  264. cls.start_wechat(log_type, env)
  265. @classmethod
  266. def download_publish(cls, log_type, env):
  267. try:
  268. recommend_sheet = Feishu.get_values_batch(log_type, 'zhiqingzongqun', 'Z48hlq')
  269. for i in range(1, len(recommend_sheet)):
  270. download_video_title = recommend_sheet[i][2]
  271. download_play_cnt = recommend_sheet[i][3]
  272. download_cover_url = recommend_sheet[i][4]
  273. download_video_url = recommend_sheet[i][5]
  274. download_comment_cnt = 0
  275. download_like_cnt = 0
  276. download_share_cnt = 0
  277. download_user_name = '知青总群'
  278. download_head_url = download_cover_url
  279. if download_video_title is None or download_video_url is None:
  280. Feishu.dimension_range(log_type, 'zhiqingqongqun', 'Z48hlq', 'ROWS', i + 1, i + 1)
  281. Common.logger(log_type).info('空行,删除成功\n')
  282. elif download_video_title in [x for y in Feishu.get_values_batch(log_type, 'zhiqingzongqun', '1a88b3')
  283. for x in y]:
  284. Feishu.dimension_range(log_type, 'zhiqingqongqun', 'Z48hlq', 'ROWS', i + 1, i + 1)
  285. Common.logger(log_type).info('视频已下载,删除成功\n')
  286. else:
  287. # 下载视频
  288. Common.download_method(log_type, 'video', download_video_title, download_video_url)
  289. # 获取视频时长
  290. video_info = cls.get_video_info_from_local("./videos/" + download_video_title + "/video.mp4")
  291. download_width = str(video_info[0])
  292. download_height = str(video_info[1])
  293. download_duration = video_info[2]
  294. # 视频时长<60s,直接删除
  295. if int(download_duration) < 60:
  296. # 删除视频文件夹
  297. shutil.rmtree("./videos/" + download_video_title + "/")
  298. # 删除云文档recommend_feeds中的记录
  299. Feishu.dimension_range(log_type, "zhiqingzongqun", "Z48hlq", "ROWS", i + 1, i + 1)
  300. Common.logger(log_type).info("时长:{}<60秒,删除成功\n", int(download_duration))
  301. return
  302. else:
  303. # 下载封面
  304. Common.download_method(log_type, 'cover', download_video_title, download_cover_url)
  305. # 保存视频信息至 "./videos/{download_video_title}/info.txt"
  306. with open("./videos/" + download_video_title
  307. + "/" + "info.txt", "a", encoding="UTF-8") as f_a:
  308. f_a.write(str(int(time.time())) + "\n" +
  309. str(download_video_title) + "\n" +
  310. str(int(download_duration)) + "\n" +
  311. str(int(float(download_play_cnt.split(' ')[-1].split('万')[0])*10000)) + "\n" +
  312. str(download_comment_cnt) + "\n" +
  313. str(download_like_cnt) + "\n" +
  314. str(download_share_cnt) + "\n" +
  315. str(download_width)+'*'+str(download_height) + "\n" +
  316. str(int(time.time())) + "\n" +
  317. str(download_user_name) + "\n" +
  318. str(download_head_url) + "\n" +
  319. str(download_video_url) + "\n" +
  320. str(download_cover_url) + "\n" +
  321. "zhiqingzongqun"+str(int(time.time())))
  322. Common.logger(log_type).info("==========视频信息已保存至info.txt==========")
  323. # 上传视频
  324. Common.logger(log_type).info("开始上传视频:{}".format(download_video_title))
  325. if env == 'dev' and int(download_width) >= int(download_height):
  326. our_video_id = Publish.upload_and_publish(log_type, env, "width")
  327. our_video_link = "https://testadmin.piaoquantv.com/cms/post-detail/" + str(
  328. our_video_id) + "/info"
  329. elif env == 'dev' and int(download_width) < int(download_height):
  330. our_video_id = Publish.upload_and_publish(log_type, env, "height")
  331. our_video_link = "https://testadmin.piaoquantv.com/cms/post-detail/" + str(
  332. our_video_id) + "/info"
  333. elif env == 'prod' and int(download_width) >= int(download_height):
  334. our_video_id = Publish.upload_and_publish(log_type, env, "width")
  335. our_video_link = "https://admin.piaoquantv.com/cms/post-detail/" + str(
  336. our_video_id) + "/info"
  337. elif env == 'prod' and int(download_width) < int(download_height):
  338. our_video_id = Publish.upload_and_publish(log_type, env, "height")
  339. our_video_link = "https://admin.piaoquantv.com/cms/post-detail/" + str(
  340. our_video_id) + "/info"
  341. else:
  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. Common.logger(log_type).info("视频上传完成:{}", download_video_title)
  346. # 保存视频 ID 到已下载表
  347. Common.logger(log_type).info("保存视频至已下载表:{}", download_video_title)
  348. # 视频ID工作表,插入首行
  349. Feishu.insert_columns(log_type, "zhiqingzongqun", "1a88b3", "ROWS", 1, 2)
  350. # 视频ID工作表,首行写入数据
  351. upload_time = int(time.time())
  352. values = [[time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(upload_time)),
  353. "推荐榜",
  354. download_video_title,
  355. our_video_link,
  356. download_play_cnt,
  357. int(download_duration),
  358. str(download_width)+'*'+str(download_height),
  359. download_cover_url,
  360. download_video_url]]
  361. time.sleep(1)
  362. Feishu.update_values(log_type, "zhiqingzongqun", "1a88b3", "F2:V2", values)
  363. # 删除行或列,可选 ROWS、COLUMNS
  364. Feishu.dimension_range(log_type, "zhiqingzongqun", "Z48hlq", "ROWS", i + 1, i + 1)
  365. Common.logger(log_type).info("视频:{},下载/上传成功\n", download_video_title)
  366. return
  367. except Exception as e:
  368. Feishu.dimension_range(log_type, "zhiqingzongqun", "Z48hlq", "ROWS", 2, 2)
  369. Common.logger(log_type).error('download_publish异常,删除成功:{}\n', e)
  370. if __name__ == '__main__':
  371. # Recommend.start_wechat('recommend', 'prod')
  372. print(Recommend.filter_words('recommend'))
  373. pass