ganggangdouchuan_recommend.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/4/13
  4. import difflib
  5. import os
  6. import sys
  7. import time
  8. import ffmpeg
  9. from appium import webdriver
  10. from appium.webdriver.extensions.android.nativekey import AndroidKey
  11. from appium.webdriver.webdriver import WebDriver
  12. from selenium.common import NoSuchElementException
  13. from selenium.webdriver.common.by import By
  14. sys.path.append(os.getcwd())
  15. from common.common import Common
  16. class GanggangdouchuanRecommend:
  17. i = 0
  18. @classmethod
  19. def start_wechat(cls, log_type, crawler, oss_endpoint, env):
  20. # try:
  21. if env == "dev":
  22. chromedriverExecutable = '/Users/wangkun/Downloads/chromedriver/chromedriver_v107/chromedriver'
  23. else:
  24. chromedriverExecutable = '/Users/piaoquan/Downloads/chromedriver'
  25. Common.logger(log_type, crawler).info('启动微信')
  26. caps = {
  27. "platformName": "Android", # 手机操作系统 Android / iOS
  28. "deviceName": "a0a65126", # 连接的设备名(模拟器或真机),安卓可以随便写
  29. "platforVersion": "11", # 手机对应的系统版本(Android 11)
  30. "appPackage": "com.tencent.mm", # 被测APP的包名,乐活圈 Android
  31. "appActivity": ".ui.LauncherUI", # 启动的Activity名
  32. "autoGrantPermissions": "true", # 让 appium 自动授权 base 权限,
  33. # 如果 noReset 为 True,则该条不生效(该参数为 Android 独有),对应的值为 True 或 False
  34. "unicodekeyboard": True, # 使用自带输入法,输入中文时填True
  35. "resetkeyboard": True, # 执行完程序恢复原来输入法
  36. "noReset": True, # 不重置APP
  37. "printPageSourceOnFailure": True, # 找不到元素时,appium log 会完整记录当前页面的 pagesource
  38. "newCommandTimeout": 6000, # 初始等待时间
  39. "automationName": "UiAutomator2", # 使用引擎,默认为 Appium,
  40. # 其中 Appium、UiAutomator2、Selendroid、Espresso 用于 Android,XCUITest 用于 iOS
  41. "showChromedriverLog": True,
  42. 'enableWebviewDetailsCollection': True,
  43. 'setWebContentsDebuggingEnabled': True,
  44. 'recreateChromeDriverSessions': True,
  45. 'chromedriverExecutable': chromedriverExecutable,
  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, crawler).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, crawler).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, crawler).info('打开小程序"刚刚都传"')
  72. driver.find_elements(By.XPATH, '//*[@text="刚刚都传"]')[-1].click()
  73. cls.get_videoList(log_type, crawler, oss_endpoint, env, driver)
  74. driver.quit()
  75. Common.logger(log_type, crawler).info('退出微信成功\n')
  76. # except Exception as e:
  77. # Common.logger(log_type, crawler).error(f'start_wechat异常:{e}\n')
  78. # cmd = "cd ~ && source .bash_profile && adb kill-server && adb start-server"
  79. # os.system(cmd)
  80. @classmethod
  81. def search_elements(cls, log_type, crawler, driver: WebDriver, element):
  82. try:
  83. windowHandles = driver.window_handles
  84. for handle in windowHandles:
  85. driver.switch_to.window(handle)
  86. time.sleep(1)
  87. if len(driver.find_elements(By.XPATH, element)) != 0:
  88. return driver.find_elements(By.XPATH, element)
  89. else:
  90. return None
  91. except Exception as e:
  92. Common.logger(log_type, crawler).error(f'search_element异常:{e}\n')
  93. @classmethod
  94. def get_video_url(cls, log_type, crawler, driver: WebDriver, video_element):
  95. try:
  96. time.sleep(1)
  97. # Common.logger(log_type, crawler).info('进入视频详情')
  98. video_element.click()
  99. time.sleep(3)
  100. video_url_element = cls.search_elements(log_type, crawler, driver, '//wx-video[@id="v_id"]')
  101. if video_url_element is None or len(video_url_element) == 0:
  102. Common.logger(log_type, crawler).info('未获取到视频 URL')
  103. return 0
  104. else:
  105. return video_url_element[0].get_attribute('src')
  106. except Exception as e:
  107. Common.logger(log_type, crawler).error(f'get_video_url异常:{e}\n')
  108. @classmethod
  109. def get_videoList(cls, log_type, crawler, oss_endpoint, env, driver: WebDriver):
  110. # try:
  111. driver.implicitly_wait(15)
  112. Common.logger(log_type, crawler).info('切换到小程序\n')
  113. time.sleep(5)
  114. webviews = driver.contexts
  115. driver.switch_to.context(webviews[1])
  116. time.sleep(1)
  117. cls.search_elements(log_type, crawler, driver, '//wx-view[text()="视频"]')[0].click()
  118. time.sleep(1)
  119. index = 0
  120. while True:
  121. if cls.search_elements(log_type, crawler, driver, '//wx-view[@class="lists"]') is None:
  122. Common.logger(log_type, crawler).info('窗口已销毁\n')
  123. return
  124. Common.logger(log_type, crawler).info('获取视频列表\n')
  125. video_elements = cls.search_elements(log_type, crawler, driver, '//wx-view[@class="list"]')
  126. if video_elements is None:
  127. Common.logger(log_type, crawler).warning(f'video_elements:{video_elements}')
  128. return
  129. video_element_temp = video_elements[index:]
  130. if len(video_element_temp) == 0:
  131. Common.logger(log_type, crawler).info('到底啦~~~~~~~~~~~~~\n')
  132. return
  133. for i, video_element in enumerate(video_element_temp):
  134. if video_element is None:
  135. Common.logger(log_type, crawler).info('到底啦~\n')
  136. return
  137. cls.i += 1
  138. cls.search_elements(log_type, crawler, driver, '//wx-view[@class="list"]')
  139. Common.logger(log_type, crawler).info(f'拖动"视频"列表第{cls.i}个至屏幕中间')
  140. time.sleep(3)
  141. driver.execute_script("arguments[0].scrollIntoView({block:'center',inline:'center'})", video_element)
  142. video_title = video_element.find_elements(By.XPATH, '//wx-view[@class="title"]//span[2]')[cls.i - 1].get_attribute('innerHTML')
  143. cover_url = video_element.find_elements(By.XPATH, '//wx-image[@class="poster-img"]')[cls.i - 1].get_attribute('src')
  144. Common.logger(log_type, crawler).info(f'video_title:{video_title}')
  145. Common.logger(log_type, crawler).info(f'cover_url:{cover_url}')
  146. # cls.download_publish(log_type, crawler, oss_endpoint, env, job, driver, video_element, video_title, cover_url)
  147. # time.sleep(3)
  148. Common.logger(log_type, crawler).info('已抓取完一组视频,休眠10秒\n')
  149. time.sleep(10)
  150. index = index + len(video_element_temp)
  151. # except Exception as e:
  152. # Common.logger(log_type, crawler).error(f'get_recommend异常,重启APP:{e}\n')
  153. # cls.i = 0
  154. # cls.quit(log_type, driver)
  155. # cls.start_wechat(log_type, crawler, oss_endpoint, env, job)
  156. # @classmethod
  157. # def title_like(cls, log_type, title):
  158. # sheet = Feishu.get_values_batch(log_type, 'ggdc', '070a67')
  159. # for i in range(1, len(sheet)):
  160. # video_title = sheet[i][7]
  161. # if video_title is None:
  162. # pass
  163. # elif difflib.SequenceMatcher(None, title, video_title).quick_ratio() >= 0.8:
  164. # return True
  165. # else:
  166. # pass
  167. #
  168. # @classmethod
  169. # def download_publish(cls, log_type, crawler, oss_endpoint, env, job, driver: WebDriver, video_element, video_title, cover_url):
  170. # try:
  171. # if video_title == 0 or cover_url == 0:
  172. # Common.logger(log_type, crawler).info('无效视频\n')
  173. # elif video_title in [x for y in Feishu.get_values_batch(log_type, 'ggdc', '070a67') for x in y]:
  174. # Common.logger(log_type, crawler).info('视频已下载\n')
  175. # elif any(word if word in video_title else False for word in cls.filter_words(log_type)) is True:
  176. # Common.logger(log_type, crawler).info('已中过滤词\n')
  177. # else:
  178. # video_url = cls.get_video_url(log_type, driver, video_element)
  179. # if video_url == 0:
  180. # Common.logger(log_type, crawler).info('video_url:未获取到\n')
  181. # elif video_url in [x for y in Feishu.get_values_batch(log_type, 'ggdc', '070a67') for x in y]:
  182. # Common.logger(log_type, crawler).info('视频已下载\n')
  183. # else:
  184. # Common.logger(log_type, crawler).info(f'cover_url:{cover_url}')
  185. # Common.logger(log_type, crawler).info(f'video_url:{video_url}')
  186. #
  187. # # 下载视频
  188. # Common.download_method(log_type, 'video', video_title, video_url)
  189. # # # 获取视频时长
  190. # # video_info = cls.get_video_info_from_local(log_type, "./videos/" + video_title + "/video.mp4")
  191. # # video_width = str(video_info[0])
  192. # # video_height = str(video_info[1])
  193. # # duration = video_info[2]
  194. # # 下载封面
  195. # Common.download_method(log_type, 'cover', video_title, cover_url)
  196. # # 保存视频信息至 "./videos/{download_video_title}/info.txt"
  197. # with open("./videos/" + video_title
  198. # + "/" + "info.txt", "a", encoding="UTF-8") as f_a:
  199. # f_a.write("ggdc" + str(int(time.time())) + "\n" +
  200. # str(video_title) + "\n" +
  201. # '100' + "\n" +
  202. # '100000' + "\n" +
  203. # '100000' + "\n" +
  204. # '100000' + "\n" +
  205. # '100000' + "\n" +
  206. # '1920*1080' + "\n" +
  207. # str(int(time.time())) + "\n" +
  208. # '刚刚都传小程序' + "\n" +
  209. # str(cover_url) + "\n" +
  210. # str(video_url) + "\n" +
  211. # str(cover_url) + "\n" +
  212. # "ganggangdouchuan" + str(int(time.time())))
  213. # Common.logger(log_type, crawler).info("==========视频信息已保存至info.txt==========")
  214. #
  215. # # 上传视频
  216. # Common.logger(log_type, crawler).info(f"开始上传视频:{video_title}")
  217. # if env == 'dev':
  218. # our_video_id = Publish.upload_and_publish(log_type, crawler, oss_endpoint, env, job)
  219. # our_video_link = "https://testadmin.piaoquantv.com/cms/post-detail/" + str(our_video_id) + "/info"
  220. # else:
  221. # our_video_id = Publish.upload_and_publish(log_type, crawler, oss_endpoint, env, job)
  222. # our_video_link = "https://admin.piaoquantv.com/cms/post-detail/" + str(our_video_id) + "/info"
  223. # Common.logger(log_type, crawler).info("视频上传完成")
  224. #
  225. # # 视频信息保存至飞书
  226. # Feishu.insert_columns(log_type, "ggdc", "070a67", "ROWS", 1, 2)
  227. # # 视频ID工作表,首行写入数据
  228. # upload_time = int(time.time())
  229. # values = [[time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(upload_time)),
  230. # "推荐榜",
  231. # video_title,
  232. # our_video_link,
  233. # cover_url,
  234. # video_url]]
  235. # time.sleep(1)
  236. # Feishu.update_values(log_type, "ggdc", "070a67", "F2:V2", values)
  237. # driver.press_keycode(AndroidKey.BACK)
  238. # Common.logger(log_type, crawler).info(f"视频:{video_title},下载/上传成功\n")
  239. # except Exception as e:
  240. # Common.logger(log_type, crawler).error(f'download_publish异常:{e}\n')
  241. if __name__ == '__main__':
  242. GanggangdouchuanRecommend.start_wechat('recommend', 'ganggangdouchuan', 'out', 'dev')
  243. pass