haitunzhufu_recommend2.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/9/13
  4. import json
  5. import os
  6. import random
  7. import re
  8. import shutil
  9. import sys
  10. import time
  11. from hashlib import md5
  12. from appium import webdriver
  13. from appium.webdriver.extensions.android.nativekey import AndroidKey
  14. from appium.webdriver.webdriver import WebDriver
  15. from bs4 import BeautifulSoup
  16. from selenium.common import NoSuchElementException
  17. from selenium.webdriver.common.by import By
  18. sys.path.append(os.getcwd())
  19. from common.common import Common
  20. from common.feishu import Feishu
  21. from common.publish import Publish
  22. from common.scheduling_db import MysqlHelper
  23. class HTZFRecommend:
  24. platform = "海豚祝福"
  25. @classmethod
  26. def today_download_cnt(cls, log_type, crawler, env):
  27. select_sql = """ SELECT COUNT(*) FROM crawler_video WHERE platform IN ("haitunzhufu", "海豚祝福") AND DATE(create_time) = CURDATE(); """
  28. today_download_cnt = MysqlHelper.get_values(log_type, crawler, select_sql, env, action="")[0]['COUNT(*)']
  29. return today_download_cnt
  30. @classmethod
  31. def start_wechat(cls, log_type, crawler, videos_cnt, env):
  32. if env == "dev":
  33. chromedriverExecutable = "/Users/wangkun/Downloads/chromedriver/chromedriver_v111/chromedriver"
  34. else:
  35. chromedriverExecutable = "/Users/piaoquan/Downloads/chromedriver"
  36. Common.logger(log_type, crawler).info("启动微信")
  37. caps = {
  38. "platformName": "Android",
  39. "platformVersion": "11",
  40. "devicesName": "Android",
  41. "appPackage": "com.tencent.mm",
  42. "appActivity": ".ui.LauncherUI",
  43. "noReset": True,
  44. "resetkeyboard": True,
  45. "unicodekeyboard": True,
  46. "showChromedriverLog": True,
  47. "autoGrantPermissions": True,
  48. "printPageSourceOnFailure": True,
  49. "recreateChromeDriverSessions": True,
  50. "enableWebviewDetailsCollention": True,
  51. "newCommandTimeout": 6000,
  52. "automationName": "UiAutomator2",
  53. "chromedriverExecutable": chromedriverExecutable,
  54. "chromeOptions": {"androidProcess": "com.tencent.mm:appbrand0"},
  55. }
  56. driver = webdriver.Remote("http://localhost:4723/wd/hub", caps)
  57. driver.implicitly_wait(20)
  58. for i in range(120):
  59. try:
  60. if driver.find_element(By.ID, "com.tencent.mm:id/f2s"):
  61. break
  62. elif driver.find_element(By.ID, "com.android.system:id/dismiss_view"):
  63. Common.logger(log_type, crawler).info("发现并关闭系统下拉菜单栏")
  64. else:
  65. pass
  66. except NoSuchElementException:
  67. pass
  68. Common.logger(log_type, crawler).info("下滑,展示小程序选择面板")
  69. size = driver.get_window_size()
  70. driver.swipe(int(size["width"] * 0.5), int(size["height"] * 0.2),
  71. int(size["width"] * 0.5), int(size["height"] * 0.8), 200)
  72. time.sleep(3)
  73. Common.logger(log_type, crawler).info('打开小程序"海豚祝福"')
  74. driver.find_elements(By.XPATH, '//*[@text="海豚祝福"]')[-1].click()
  75. time.sleep(5)
  76. cls.get_videoList(log_type=log_type,
  77. crawler=crawler,
  78. driver=driver,
  79. videos_cnt=videos_cnt,
  80. env=env)
  81. time.sleep(1)
  82. driver.quit()
  83. @classmethod
  84. def search_elements(cls, driver: WebDriver, xpath):
  85. time.sleep(1)
  86. windowHandles = driver.window_handles
  87. for handle in windowHandles:
  88. driver.switch_to.window(handle)
  89. time.sleep(1)
  90. try:
  91. elements = driver.find_elements(By.XPATH, xpath)
  92. if elements:
  93. return elements
  94. except NoSuchElementException:
  95. pass
  96. @classmethod
  97. def repeat_out_video_id(cls, log_type, crawler, out_video_id, env):
  98. sql = f""" select * from crawler_video where platform in ("众妙音信", "刚刚都传", "吉祥幸福", "知青天天看", "zhufuquanzi", "祝福圈子", "haitunzhufu", "海豚祝福") and out_video_id="{out_video_id}"; """
  99. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  100. return len(repeat_video)
  101. @classmethod
  102. def get_video_url(cls, driver: WebDriver, video_title_element):
  103. for i in range(3):
  104. cls.search_elements(driver, '//*[@class="list"]')
  105. video_title_element[0].click()
  106. time.sleep(5)
  107. video_url_elements = cls.search_elements(driver, '//*[@id="myVideo"]')
  108. if video_url_elements:
  109. return video_url_elements[0].get_attribute("src")
  110. @classmethod
  111. def swipe_up(cls, driver: WebDriver):
  112. cls.search_elements(driver, '//*[@class="list"]')
  113. size = driver.get_window_size()
  114. driver.swipe(int(size["width"] * 0.5), int(size["height"] * 0.8),
  115. int(size["width"] * 0.5), int(size["height"] * 0.55), 200)
  116. @classmethod
  117. def get_videoList(cls, log_type, crawler, driver: WebDriver, videos_cnt, env):
  118. driver.implicitly_wait(20)
  119. webviews = driver.contexts
  120. Common.logger(log_type, crawler).info(f"webviews:{webviews}")
  121. driver.switch_to.context(webviews[1])
  122. windowHandles = driver.window_handles
  123. for handle in windowHandles:
  124. driver.switch_to.window(handle)
  125. time.sleep(1)
  126. try:
  127. if cls.search_elements(driver, '//*[@class="bottom_scroll"]'):
  128. Common.logger(log_type, crawler).info("切换到小程序")
  129. break
  130. except NoSuchElementException:
  131. time.sleep(1)
  132. cls.search_elements(driver, '//*[@class="nav cur"]')[-1].click()
  133. Common.logger(log_type, crawler).info('点击"推荐"列表成功\n')
  134. # while True:
  135. for page in range(200):
  136. Common.logger(log_type, crawler).info(f"正在抓取第{page+1}页")
  137. if cls.search_elements(driver, '//*[@class="list"]') is None:
  138. Common.logger(log_type, crawler).info("列表页窗口已销毁\n")
  139. return
  140. for i in range(1):
  141. cls.swipe_up(driver)
  142. time.sleep(0.5)
  143. page_source = driver.page_source
  144. soup = BeautifulSoup(page_source, 'html.parser')
  145. soup.prettify()
  146. video_list_elements = soup.findAll("wx-view", class_="img_bf")
  147. Common.logger(log_type, crawler).info(f"第{page+1}页共:{len(video_list_elements)}条视频\n")
  148. for i, video_element in enumerate(video_list_elements):
  149. try:
  150. today_download = cls.today_download_cnt(log_type, crawler, env)
  151. if today_download >= videos_cnt:
  152. Common.logger(log_type, crawler).info(f"今日已下载视频数:{today_download}")
  153. return
  154. Common.logger(log_type, crawler).info(f"第{i+1}条视频")
  155. video_title = video_element.find("wx-view", class_="title").text
  156. play_str = video_element.find("wx-view", class_="wan").text
  157. play_cnt = int(re.sub(r"\D", "", play_str)) * 10000 if "万" in play_str else play_str
  158. cover_url = video_element.find("wx-image", class_="img")["src"]
  159. out_video_id = md5(video_title.encode('utf8')).hexdigest()
  160. video_dict = {
  161. "video_title": video_title,
  162. 'video_id': out_video_id,
  163. "plat_cnt_str": play_str,
  164. "play_cnt": play_cnt,
  165. 'comment_cnt': 0,
  166. 'like_cnt': 0,
  167. 'share_cnt': 0,
  168. 'publish_time_stamp': int(time.time()),
  169. 'publish_time_str': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()))),
  170. 'user_name': "haitunzhufu",
  171. 'user_id': "haitunzhufu",
  172. "cover_url": cover_url,
  173. 'avatar_url': cover_url,
  174. 'session': f"haitunzhufu-{int(time.time())}"
  175. }
  176. for k, v in video_dict.items():
  177. Common.logger(log_type, crawler).info(f"{k}:{v}")
  178. if video_title is None or cover_url is None:
  179. Common.logger(log_type, crawler).info("无效视频\n")
  180. cls.swipe_up(driver)
  181. time.sleep(1)
  182. elif cls.repeat_out_video_id(log_type=log_type,
  183. crawler=crawler,
  184. out_video_id=out_video_id,
  185. env=env) != 0:
  186. Common.logger(log_type, crawler).info('视频已下载\n')
  187. cls.swipe_up(driver)
  188. time.sleep(1)
  189. else:
  190. video_title_element = cls.search_elements(driver, f'//*[contains(text(), "{video_title}")]')
  191. if video_title_element is None:
  192. Common.logger(log_type, crawler).warning(f"未找到该视频标题的element:{video_title_element}")
  193. continue
  194. Common.logger(log_type, crawler).info("点击标题,进入视频详情页")
  195. video_url = cls.get_video_url(driver, video_title_element)
  196. if video_url is None:
  197. Common.logger(log_type, crawler).info("未获取到视频播放地址\n")
  198. driver.press_keycode(AndroidKey.BACK)
  199. time.sleep(3)
  200. continue
  201. video_dict['video_url'] = video_url
  202. Common.logger(log_type, crawler).info(f"video_url:{video_url}\n")
  203. cls.download_publish(log_type=log_type,
  204. crawler=crawler,
  205. video_dict=video_dict,
  206. env=env)
  207. driver.press_keycode(AndroidKey.BACK)
  208. time.sleep(3)
  209. except Exception as e:
  210. Common.logger(log_type, crawler).error(f"抓取单条视频异常:{e}\n")
  211. Common.logger(log_type, crawler).info('已抓取完一组视频,休眠5秒\n')
  212. time.sleep(5)
  213. @classmethod
  214. def get_our_uid(cls, log_type, crawler, env):
  215. select_sql = f""" SELECT uid FROM crawler_user_v3 WHERE `source`="{crawler}"; """
  216. uids = MysqlHelper.get_values(log_type, crawler, select_sql, env, action="")
  217. uid_list = []
  218. for uid_dict in uids:
  219. uid_list.append(uid_dict["uid"])
  220. return random.choice(uid_list)
  221. @classmethod
  222. def download_publish(cls, log_type, crawler, video_dict, env):
  223. Common.download_method(log_type=log_type, crawler=crawler, text='video', title=video_dict['video_title'],
  224. url=video_dict['video_url'])
  225. ffmpeg_dict = Common.ffmpeg(log_type, crawler, f"./{crawler}/videos/{video_dict['video_title']}/video.mp4")
  226. if ffmpeg_dict is None:
  227. md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
  228. shutil.rmtree(f"./{crawler}/videos/{md_title}/")
  229. Common.logger(log_type, crawler).info("视频size=0,删除成功\n")
  230. return
  231. video_dict["duration"] = ffmpeg_dict["duration"]
  232. video_dict["video_width"] = ffmpeg_dict["width"]
  233. video_dict["video_height"] = ffmpeg_dict["height"]
  234. # 下载封面
  235. Common.download_method(log_type=log_type, crawler=crawler, text='cover', title=video_dict['video_title'],
  236. url=video_dict['cover_url'])
  237. # 保存视频信息至txt
  238. Common.save_video_info(log_type=log_type, crawler=crawler, video_dict=video_dict)
  239. # 上传视频
  240. Common.logger(log_type, crawler).info("开始上传视频...")
  241. our_video_id = Publish.upload_and_publish(log_type=log_type,
  242. crawler=crawler,
  243. strategy="推荐榜爬虫策略",
  244. our_uid=cls.get_our_uid(log_type, crawler, env),
  245. env=env,
  246. oss_endpoint="out")
  247. if env == 'dev':
  248. our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  249. else:
  250. our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  251. Common.logger(log_type, crawler).info("视频上传完成")
  252. if our_video_id is None:
  253. # 删除视频文件夹
  254. shutil.rmtree(f"./{crawler}/videos/{video_dict['video_title']}")
  255. return
  256. # 视频信息保存至飞书
  257. Feishu.insert_columns(log_type, crawler, "d51d20", "ROWS", 1, 2)
  258. # 视频ID工作表,首行写入数据
  259. upload_time = int(time.time())
  260. values = [[time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(upload_time)),
  261. "推荐榜爬虫策略",
  262. video_dict["video_title"],
  263. video_dict["video_id"],
  264. video_dict["play_cnt"],
  265. video_dict["duration"],
  266. f'{video_dict["video_width"]}*{video_dict["video_height"]}',
  267. our_video_link,
  268. video_dict["cover_url"],
  269. video_dict["video_url"]]]
  270. time.sleep(1)
  271. Feishu.update_values(log_type, crawler, "d51d20", "F2:V2", values)
  272. Common.logger(log_type, crawler).info(f"视频已保存至飞书文档\n")
  273. rule_dict = {}
  274. # 视频信息保存数据库
  275. insert_sql = f""" insert into crawler_video(video_id,
  276. out_user_id,
  277. platform,
  278. strategy,
  279. out_video_id,
  280. video_title,
  281. cover_url,
  282. video_url,
  283. duration,
  284. publish_time,
  285. play_cnt,
  286. crawler_rule,
  287. width,
  288. height)
  289. values({our_video_id},
  290. "{video_dict['user_id']}",
  291. "{cls.platform}",
  292. "推荐榜爬虫策略",
  293. "{video_dict['video_id']}",
  294. "{video_dict['video_title']}",
  295. "{video_dict['cover_url']}",
  296. "{video_dict['video_url']}",
  297. {int(video_dict['duration'])},
  298. "{video_dict['publish_time_str']}",
  299. {int(video_dict['play_cnt'])},
  300. '{json.dumps(rule_dict)}',
  301. {int(video_dict['video_width'])},
  302. {int(video_dict['video_height'])}) """
  303. Common.logger(log_type, crawler).info(f"insert_sql:{insert_sql}")
  304. MysqlHelper.update_values(log_type, crawler, insert_sql, env, action='')
  305. Common.logger(log_type, crawler).info('视频信息写入数据库成功!\n')
  306. if __name__ == "__main__":
  307. HTZFRecommend.start_wechat("recommend", "haitunzhufu", 5, "dev")
  308. # HTZFRecommend.today_download_cnt("recommend", "haitunzhufu", "dev")
  309. # HTZFRecommend.get_play_cnt()
  310. pass