haitunzhufu_recommend2.py 17 KB

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