ganggangdouchuan_recommend.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/4/13
  4. import json
  5. import os
  6. import shutil
  7. import sys
  8. import time
  9. from hashlib import md5
  10. from appium import webdriver
  11. from appium.webdriver.extensions.android.nativekey import AndroidKey
  12. from appium.webdriver.webdriver import WebDriver
  13. from selenium.common import NoSuchElementException
  14. from selenium.webdriver.common.by import By
  15. sys.path.append(os.getcwd())
  16. from common.common import Common
  17. from common.feishu import Feishu
  18. from common.publish import Publish
  19. from common.scheduling_db import MysqlHelper
  20. class GanggangdouchuanRecommend:
  21. platform = "刚刚都传"
  22. i = 0
  23. @classmethod
  24. def start_wechat(cls, log_type, crawler, oss_endpoint, env):
  25. try:
  26. if env == "dev":
  27. chromedriverExecutable = '/Users/wangkun/Downloads/chromedriver/chromedriver_v107/chromedriver'
  28. else:
  29. chromedriverExecutable = '/Users/piaoquan/Downloads/chromedriver'
  30. Common.logger(log_type, crawler).info('启动微信')
  31. caps = {
  32. "platformName": "Android", # 手机操作系统 Android / iOS
  33. "deviceName": "a0a65126", # 连接的设备名(模拟器或真机),安卓可以随便写
  34. "platforVersion": "11", # 手机对应的系统版本(Android 11)
  35. "appPackage": "com.tencent.mm", # 被测APP的包名,乐活圈 Android
  36. "appActivity": ".ui.LauncherUI", # 启动的Activity名
  37. "autoGrantPermissions": "true", # 让 appium 自动授权 base 权限,
  38. # 如果 noReset 为 True,则该条不生效(该参数为 Android 独有),对应的值为 True 或 False
  39. "unicodekeyboard": True, # 使用自带输入法,输入中文时填True
  40. "resetkeyboard": True, # 执行完程序恢复原来输入法
  41. "noReset": True, # 不重置APP
  42. "printPageSourceOnFailure": True, # 找不到元素时,appium log 会完整记录当前页面的 pagesource
  43. "newCommandTimeout": 6000, # 初始等待时间
  44. "automationName": "UiAutomator2", # 使用引擎,默认为 Appium,
  45. # 其中 Appium、UiAutomator2、Selendroid、Espresso 用于 Android,XCUITest 用于 iOS
  46. "showChromedriverLog": True,
  47. 'enableWebviewDetailsCollection': True,
  48. 'setWebContentsDebuggingEnabled': True,
  49. 'recreateChromeDriverSessions': True,
  50. 'chromedriverExecutable': chromedriverExecutable,
  51. "chromeOptions": {"androidProcess": "com.tencent.mm:appbrand0"},
  52. 'browserName': ''
  53. }
  54. driver = webdriver.Remote("http://localhost:4723/wd/hub", caps)
  55. driver.implicitly_wait(20)
  56. # 向下滑动页面,展示出小程序选择面板
  57. for i in range(120):
  58. try:
  59. # 发现微信消息 TAB,代表微信已启动成功
  60. if driver.find_elements(By.ID, 'com.tencent.mm:id/f2s'):
  61. break
  62. # 发现并关闭系统菜单栏
  63. elif driver.find_element(By.ID, 'com.android.systemui:id/dismiss_view'):
  64. Common.logger(log_type, crawler).info('发现并关闭系统下拉菜单栏')
  65. driver.find_element(By.ID, 'com.android.systemui:id/dismiss_view').click()
  66. else:
  67. pass
  68. except NoSuchElementException:
  69. time.sleep(1)
  70. Common.logger(log_type, crawler).info('下滑,展示小程序选择面板')
  71. size = driver.get_window_size()
  72. driver.swipe(int(size['width'] * 0.5), int(size['height'] * 0.2),
  73. int(size['width'] * 0.5), int(size['height'] * 0.8), 200)
  74. # 打开小程序"刚刚都传"
  75. time.sleep(3)
  76. Common.logger(log_type, crawler).info('打开小程序"刚刚都传"')
  77. driver.find_elements(By.XPATH, '//*[@text="刚刚都传"]')[-1].click()
  78. time.sleep(10)
  79. cls.get_videoList(log_type, crawler, oss_endpoint, env, driver)
  80. driver.quit()
  81. Common.logger(log_type, crawler).info('退出微信成功\n')
  82. except Exception as e:
  83. Common.logger(log_type, crawler).error(f'start_wechat异常:{e}\n')
  84. @classmethod
  85. def get_video_url(cls, log_type, crawler, driver: WebDriver, video_element):
  86. try:
  87. time.sleep(1)
  88. # Common.logger(log_type, crawler).info('进入视频详情')
  89. video_element.click()
  90. time.sleep(5)
  91. windowHandles = driver.window_handles
  92. # Common.logger(log_type, crawler).info('windowHandles:{}', windowHandles)
  93. # 遍历所有的handles,找到当前页面所在的handle:如果pageSource有包含你想要的元素,就是所要找的handle
  94. # 小程序的页面来回切换也需要:遍历所有的handles,切换到元素所在的handle
  95. for handle in windowHandles:
  96. driver.switch_to.window(handle)
  97. time.sleep(1)
  98. try:
  99. video_url_element = driver.find_element(By.XPATH, '//wx-video[@id="v_id"]')
  100. video_url = video_url_element.get_attribute("src")
  101. return video_url
  102. except NoSuchElementException:
  103. time.sleep(1)
  104. except Exception as e:
  105. Common.logger(log_type, crawler).error(f'get_video_url异常:{e}\n')
  106. # 切换 Handle
  107. @classmethod
  108. def search_elements(cls, log_type, crawler, driver: WebDriver, xpath):
  109. try:
  110. windowHandles = driver.window_handles
  111. # Common.logger(log_type, crawler).info('windowHandles:{}', windowHandles)
  112. # 遍历所有的handles,找到当前页面所在的handle:如果pageSource有包含你想要的元素,就是所要找的handle
  113. # 小程序的页面来回切换也需要:遍历所有的handles,切换到元素所在的handle
  114. for handle in windowHandles:
  115. driver.switch_to.window(handle)
  116. time.sleep(1)
  117. try:
  118. elements = driver.find_elements(By.XPATH, xpath)
  119. if elements:
  120. return elements
  121. except NoSuchElementException:
  122. pass
  123. except Exception as e:
  124. Common.logger(log_type, crawler).warning(f'search_elements异常:{e}\n')
  125. @classmethod
  126. def check_to_applet(cls, log_type, crawler, driver: WebDriver):
  127. while True:
  128. webview = driver.contexts
  129. Common.logger(log_type, crawler).info(f"webviews:{webview}")
  130. driver.switch_to.context(webview[1])
  131. windowHandles = driver.window_handles
  132. for handle in windowHandles:
  133. driver.switch_to.window(handle)
  134. time.sleep(1)
  135. try:
  136. video_list = driver.find_element(By.XPATH, '//wx-view[text()="视频"]')
  137. video_list.click()
  138. Common.logger(log_type, crawler).info('切换到小程序视频列表成功\n')
  139. return
  140. except NoSuchElementException:
  141. time.sleep(1)
  142. Common.logger(log_type, crawler).info("切换到小程序失败\n")
  143. break
  144. @classmethod
  145. def repeat_out_video_id(cls, log_type, crawler, out_video_id, env):
  146. sql = f""" select * from crawler_video where platform="{cls.platform}" and out_video_id="{out_video_id}"; """
  147. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  148. return len(repeat_video)
  149. @classmethod
  150. def repeat_video_url(cls, log_type, crawler, video_url, env):
  151. sql = f""" select * from crawler_video where platform="{cls.platform}" and video_url="{video_url}"; """
  152. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  153. return len(repeat_video)
  154. @classmethod
  155. def get_videoList(cls, log_type, crawler, oss_endpoint, env, driver: WebDriver):
  156. # 切换到小程序
  157. cls.check_to_applet(log_type, crawler, driver)
  158. time.sleep(1)
  159. index = 0
  160. while True:
  161. try:
  162. if cls.search_elements(log_type, crawler, driver, '//wx-view[@class="lists"]') is None:
  163. Common.logger(log_type, crawler).info('窗口已销毁\n')
  164. return
  165. Common.logger(log_type, crawler).info('获取视频列表\n')
  166. video_elements = cls.search_elements(log_type, crawler, driver, '//wx-view[@class="list"]')
  167. if video_elements is None:
  168. Common.logger(log_type, crawler).warning(f'video_elements:{video_elements}')
  169. return
  170. video_element_temp = video_elements[index:]
  171. if len(video_element_temp) == 0:
  172. Common.logger(log_type, crawler).info('到底啦~~~~~~~~~~~~~\n')
  173. return
  174. for i, video_element in enumerate(video_element_temp):
  175. if video_element is None:
  176. Common.logger(log_type, crawler).info('到底啦~\n')
  177. return
  178. cls.i += 1
  179. cls.search_elements(log_type, crawler, driver, '//wx-view[@class="list"]')
  180. Common.logger(log_type, crawler).info(f'拖动"视频"列表第{cls.i}个至屏幕中间')
  181. time.sleep(3)
  182. driver.execute_script("arguments[0].scrollIntoView({block:'center',inline:'center'})", video_element)
  183. # video_title = video_element.find_elements(By.XPATH, '//wx-view[@class="title"]//span[2]')[cls.i - 1].text
  184. # cover_url = video_element.find_elements(By.XPATH, '//wx-image[@class="poster-img"]')[cls.i - 1].get_attribute('src')
  185. video_title = video_element.find_elements(By.XPATH, '//wx-view[@class="title"]//span[2]')[index+i].text
  186. cover_url = video_element.find_elements(By.XPATH, '//wx-image[@class="poster-img"]')[index+i].get_attribute('src')
  187. out_video_id = md5(video_title.encode('utf8')).hexdigest()
  188. video_dict = {
  189. 'video_title': video_title,
  190. 'video_id': out_video_id,
  191. 'play_cnt': 0,
  192. 'comment_cnt': 0,
  193. 'like_cnt': 0,
  194. 'share_cnt': 0,
  195. 'publish_time_stamp': int(time.time()),
  196. 'publish_time_str': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()))),
  197. 'user_name': "ganggangdouchuan",
  198. 'user_id': "ganggangdouchuan",
  199. 'avatar_url': cover_url,
  200. 'cover_url': cover_url,
  201. 'session': f"ganggangdouchuan-{int(time.time())}"
  202. }
  203. for k, v in video_dict.items():
  204. Common.logger(log_type, crawler).info(f"{k}:{v}")
  205. if video_title is None or cover_url is None:
  206. Common.logger(log_type, crawler).info("无效视频\n")
  207. elif cls.repeat_out_video_id(log_type, crawler, out_video_id, env) != 0:
  208. Common.logger(log_type, crawler).info('视频已下载\n')
  209. else:
  210. video_url = cls.get_video_url(log_type, crawler, driver, video_element)
  211. Common.logger(log_type, crawler).info(f'video_url:{video_url}')
  212. if video_url is None:
  213. Common.logger(log_type, crawler).info("未获取到视频播放地址\n")
  214. driver.press_keycode(AndroidKey.BACK)
  215. elif cls.repeat_video_url(log_type, crawler, video_url, env) != 0:
  216. Common.logger(log_type, crawler).info('视频已下载\n')
  217. driver.press_keycode(AndroidKey.BACK)
  218. else:
  219. video_dict["video_url"]=video_url
  220. cls.download_publish(log_type, crawler, video_dict, oss_endpoint, env, driver)
  221. Common.logger(log_type, crawler).info('已抓取完一组视频,休眠10秒\n')
  222. time.sleep(10)
  223. index = index + len(video_element_temp)
  224. except Exception as e:
  225. Common.logger(log_type, crawler).error(f'get_videoList异常:{e}\n')
  226. cls.i = 0
  227. @classmethod
  228. def download_publish(cls, log_type, crawler, video_dict, oss_endpoint, env, driver: WebDriver):
  229. # 下载视频
  230. Common.download_method(log_type=log_type, crawler=crawler, text='video', title=video_dict['video_title'], url=video_dict['video_url'])
  231. ffmpeg_dict = Common.ffmpeg(log_type, crawler, f"./{crawler}/videos/{video_dict['video_title']}/video.mp4")
  232. if ffmpeg_dict is None:
  233. md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
  234. shutil.rmtree(f"./{crawler}/videos/{md_title}/")
  235. Common.logger(log_type, crawler).info("视频size=0,删除成功\n")
  236. return
  237. video_dict["duration"] = ffmpeg_dict["duration"]
  238. video_dict["video_width"] = ffmpeg_dict["width"]
  239. video_dict["video_height"] = ffmpeg_dict["height"]
  240. # 下载封面
  241. Common.download_method(log_type=log_type, crawler=crawler, text='cover', title=video_dict['video_title'],
  242. url=video_dict['cover_url'])
  243. # 保存视频信息至txt
  244. Common.save_video_info(log_type=log_type, crawler=crawler, video_dict=video_dict)
  245. # 上传视频
  246. Common.logger(log_type, crawler).info("开始上传视频...")
  247. our_video_id = Publish.upload_and_publish(log_type=log_type,
  248. crawler=crawler,
  249. strategy="推荐榜爬虫策略",
  250. our_uid="recommend",
  251. env=env,
  252. oss_endpoint=oss_endpoint)
  253. if env == 'dev':
  254. our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  255. else:
  256. our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  257. Common.logger(log_type, crawler).info("视频上传完成")
  258. if our_video_id is None:
  259. # 删除视频文件夹
  260. shutil.rmtree(f"./{crawler}/videos/{video_dict['video_title']}")
  261. return
  262. # 视频信息保存至飞书
  263. Feishu.insert_columns(log_type, crawler, "070a67", "ROWS", 1, 2)
  264. # 视频ID工作表,首行写入数据
  265. upload_time = int(time.time())
  266. values = [[time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(upload_time)),
  267. "推荐榜爬虫策略",
  268. video_dict["video_title"],
  269. video_dict["video_id"],
  270. video_dict["duration"],
  271. f'{video_dict["video_width"]}*{video_dict["video_height"]}',
  272. our_video_link,
  273. video_dict["cover_url"],
  274. video_dict["video_url"]]]
  275. time.sleep(1)
  276. Feishu.update_values(log_type, crawler, "070a67", "F2:V2", values)
  277. Common.logger(log_type, crawler).info(f"视频已保存至飞书文档\n")
  278. rule_dict = {}
  279. # 视频信息保存数据库
  280. insert_sql = f""" insert into crawler_video(video_id,
  281. out_user_id,
  282. platform,
  283. strategy,
  284. out_video_id,
  285. video_title,
  286. cover_url,
  287. video_url,
  288. duration,
  289. publish_time,
  290. play_cnt,
  291. crawler_rule,
  292. width,
  293. height)
  294. values({our_video_id},
  295. "{video_dict['user_id']}",
  296. "{cls.platform}",
  297. "推荐榜爬虫策略",
  298. "{video_dict['video_id']}",
  299. "{video_dict['video_title']}",
  300. "{video_dict['cover_url']}",
  301. "{video_dict['video_url']}",
  302. {int(video_dict['duration'])},
  303. "{video_dict['publish_time_str']}",
  304. {int(video_dict['play_cnt'])},
  305. '{json.dumps(rule_dict)}',
  306. {int(video_dict['video_width'])},
  307. {int(video_dict['video_height'])}) """
  308. Common.logger(log_type, crawler).info(f"insert_sql:{insert_sql}")
  309. MysqlHelper.update_values(log_type, crawler, insert_sql, env, action='')
  310. Common.logger(log_type, crawler).info('视频信息插入数据库成功!\n')
  311. driver.press_keycode(AndroidKey.BACK)
  312. if __name__ == '__main__':
  313. GanggangdouchuanRecommend.start_wechat('recommend', 'ganggangdouchuan', 'out', 'dev')
  314. pass