zqttk_recommend.py 20 KB

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