xiaoniangao_plus_scheduling.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. # -*- coding: utf-8 -*-
  2. # @Author: luojunhui
  3. # @Time: 2023/9/27
  4. import json
  5. import os
  6. import sys
  7. import time
  8. from hashlib import md5
  9. from appium import webdriver
  10. from appium.webdriver.extensions.android.nativekey import AndroidKey
  11. from appium.webdriver.webdriver import WebDriver
  12. from bs4 import BeautifulSoup
  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.mq import MQ
  18. from common.public import download_rule, get_config_from_mysql
  19. from common.scheduling_db import MysqlHelper
  20. class XiaoNianGaoPlusRecommend:
  21. platform = "小年糕"
  22. download_cnt = 0
  23. element_list = []
  24. i = 0
  25. @classmethod
  26. def start_wechat(cls, log_type, crawler, env, rule_dict, our_uid):
  27. if env == "dev":
  28. chromedriverExecutable = "/Users/luojunhui/Downloads/chromedriver_v111/chromedriver"
  29. else:
  30. chromedriverExecutable = "/Users/piaoquan/Downloads/chromedriver"
  31. Common.logger(log_type, crawler).info("启动微信")
  32. Common.logging(log_type, crawler, env, '启动微信')
  33. # 微信的配置文件
  34. caps = {
  35. "platformName": "Android",
  36. "devicesName": "Android",
  37. "platformVersion": "13",
  38. # "udid": "emulator-5554",
  39. "appPackage": "com.tencent.mm",
  40. "appActivity": ".ui.LauncherUI",
  41. "autoGrantPermissions": "true",
  42. "noReset": True,
  43. "resetkeyboard": True,
  44. "unicodekeyboard": True,
  45. "showChromedriverLog": True,
  46. "printPageSourceOnFailure": True,
  47. "recreateChromeDriverSessions": True,
  48. "enableWebviewDetailsCollection": True,
  49. "setWebContentsDebuggingEnabled": True,
  50. "newCommandTimeout": 6000,
  51. "automationName": "UiAutomator2",
  52. "chromedriverExecutable": chromedriverExecutable,
  53. "chromeOptions": {"androidProcess": "com.tencent.mm:appbrand0"},
  54. }
  55. driver = webdriver.Remote("http://localhost:4723/wd/hub", caps)
  56. driver.implicitly_wait(30)
  57. for i in range(120):
  58. try:
  59. if driver.find_elements(By.ID, "com.tencent.mm:id/f2s"):
  60. Common.logger(log_type, crawler).info("微信启动成功")
  61. Common.logging(log_type, crawler, env, '微信启动成功')
  62. break
  63. elif driver.find_element(By.ID, "com.android.systemui:id/dismiss_view"):
  64. Common.logger(log_type, crawler).info("发现并关闭系统下拉菜单")
  65. Common.logging(log_type, crawler, env, '发现并关闭系统下拉菜单')
  66. driver.find_element(By.ID, "com.android.system:id/dismiss_view").click()
  67. else:
  68. pass
  69. except NoSuchElementException:
  70. time.sleep(1)
  71. Common.logger(log_type, crawler).info("下滑,展示小程序选择面板")
  72. # Common.logging(log_type, crawler, env, '下滑,展示小程序选择面板')
  73. size = driver.get_window_size()
  74. driver.swipe(int(size['width'] * 0.5), int(size['height'] * 0.2),
  75. int(size['width'] * 0.5), int(size['height'] * 0.8), 200)
  76. time.sleep(1)
  77. Common.logger(log_type, crawler).info('打开小程序"小年糕+"')
  78. # Common.logging(log_type, crawler, env, '打开小程序"小年糕+"')
  79. driver.find_elements(By.XPATH, '//*[@text="小年糕+"]')[-1].click()
  80. time.sleep(5)
  81. cls.get_videoList(log_type, crawler, driver, env, rule_dict, our_uid)
  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 check_to_applet(cls, log_type, crawler, env, driver: WebDriver, xpath):
  99. time.sleep(1)
  100. webViews = driver.contexts
  101. driver.switch_to.context(webViews[-1])
  102. windowHandles = driver.window_handles
  103. for handle in windowHandles:
  104. driver.switch_to.window(handle)
  105. time.sleep(1)
  106. try:
  107. driver.find_element(By.XPATH, xpath)
  108. Common.logger(log_type, crawler).info("切换到WebView成功\n")
  109. Common.logging(log_type, crawler, env, '切换到WebView成功\n')
  110. return
  111. except NoSuchElementException:
  112. time.sleep(1)
  113. @classmethod
  114. def repeat_video(cls, log_type, crawler, video_id, env):
  115. sql = f""" select * from crawler_video where platform in ("众妙音信", "刚刚都传", "吉祥幸福", "知青天天看", "zhufuquanzi", "祝福圈子", "haitunzhufu", "海豚祝福", "小年糕") and out_video_id="{video_id}"; """
  116. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  117. return len(repeat_video)
  118. @classmethod
  119. def swipe_up(cls, driver: WebDriver):
  120. cls.search_elements(driver, '//*[@class="list-list--list"]')
  121. size = driver.get_window_size()
  122. driver.swipe(int(size["width"] * 0.5), int(size["height"] * 0.8),
  123. int(size["width"] * 0.5), int(size["height"] * 0.4), 200)
  124. @classmethod
  125. def get_video_url(cls, log_type, crawler, driver: WebDriver, video_title_element, env):
  126. for i in range(3):
  127. cls.search_elements(driver, '//*[@class="list-list--list"]')
  128. Common.logger(log_type, crawler).info(f"video_title_element:{video_title_element[0]}")
  129. time.sleep(1)
  130. Common.logger(log_type, crawler).info("滑动标题至可见状态")
  131. driver.execute_script("arguments[0].scrollIntoView({block:'center',inline:'center'});",
  132. video_title_element[0])
  133. time.sleep(3)
  134. Common.logger(log_type, crawler).info("点击标题")
  135. video_title_element[0].click()
  136. cls.check_to_applet(log_type=log_type, crawler=crawler, driver=driver, env=env,
  137. xpath=r'//wx-video[@class="dynamic-index--video-item dynamic-index--video"]')
  138. Common.logger(log_type, crawler).info("点击标题完成")
  139. time.sleep(10)
  140. video_url_elements = cls.search_elements(driver,
  141. '//wx-video[@class="dynamic-index--video-item dynamic-index--video"]')
  142. if video_url_elements:
  143. return video_url_elements[0].get_attribute("src")
  144. @classmethod
  145. def get_videoList(cls, log_type, crawler, driver: WebDriver, env, rule_dict, our_uid):
  146. mq = MQ(topic_name="topic_crawler_etl_" + env)
  147. driver.implicitly_wait(20)
  148. # 切换到 web_view
  149. cls.check_to_applet(log_type=log_type, crawler=crawler, env=env, driver=driver,
  150. xpath='//*[@class="tab-bar--tab tab-bar--tab-selected"]')
  151. time.sleep(1)
  152. page = 0
  153. while True:
  154. if cls.search_elements(driver, '//*[@class="list-list--list"]') is None:
  155. Common.logger(log_type, crawler).info("窗口已销毁\n")
  156. Common.logging(log_type, crawler, env, '窗口已销毁\n')
  157. cls.i = 0
  158. cls.download_cnt = 0
  159. cls.element_list = []
  160. return
  161. cls.swipe_up(driver)
  162. page_source = driver.page_source
  163. soup = BeautifulSoup(page_source, 'html.parser')
  164. soup.prettify()
  165. video_list_elements = soup.findAll("wx-view", class_="expose--adapt-parent")
  166. # video_list_elements 有,cls.element_list 中没有的元素
  167. video_list_elements = list(set(video_list_elements).difference(set(cls.element_list)))
  168. # video_list_elements 与 cls.element_list 的并集
  169. cls.element_list = list(set(video_list_elements) | set(cls.element_list))
  170. Common.logger(log_type, crawler).info(f"正在抓取第{page + 1}页,共:{len(video_list_elements)}条视频")
  171. Common.logging(log_type, crawler, env, f"正在抓取第{page + 1}页,共:{len(video_list_elements)}条视频")
  172. if len(video_list_elements) == 0:
  173. for i in range(10):
  174. Common.logger(log_type, crawler).info(f"向上滑动第{i + 1}次")
  175. cls.swipe_up(driver)
  176. time.sleep(0.5)
  177. continue
  178. for i, video_element in enumerate(video_list_elements):
  179. try:
  180. Common.logger(log_type, crawler).info(f"本轮已抓取{cls.download_cnt}条视频\n")
  181. Common.logging(log_type, crawler, env, f"本轮已抓取{cls.download_cnt}条视频\n")
  182. if cls.download_cnt >= int(rule_dict.get("videos_cnt", {}).get("min", 10)):
  183. cls.i = 0
  184. cls.download_cnt = 0
  185. cls.element_list = []
  186. return
  187. cls.i += 1
  188. Common.logger(log_type, crawler).info(f"第{cls.i}条视频")
  189. Common.logging(log_type, crawler, env, f"第{cls.i}条视频")
  190. # 标题
  191. video_title = video_element.find("wx-view", class_="dynamic--title").text
  192. # 播放量字符串
  193. play_str = video_element.find("wx-view", class_="dynamic--views").text
  194. info_list = video_element.findAll("wx-view", class_="dynamic--commerce-btn-text")
  195. # 点赞数量
  196. like_str = info_list[1].text
  197. # 评论数量
  198. comment_str = info_list[2].text
  199. # 视频时长
  200. duration_str = video_element.find("wx-view", class_="dynamic--duration").text
  201. user_name = video_element.find("wx-view", class_="dynamic--nick-top").text
  202. # 头像 URL
  203. avatar_url = video_element.find("wx-image", class_="avatar--avatar")["src"]
  204. # 封面 URL
  205. cover_url = video_element.find("wx-image", class_="dynamic--bg-image")["src"]
  206. play_cnt = int(play_str.replace("+", "").replace("次播放", ""))
  207. duration = int(duration_str.split(":")[0].strip()) * 60 + int(duration_str.split(":")[-1].strip())
  208. if "点赞" in like_str:
  209. like_cnt = 0
  210. elif "万" in like_str:
  211. like_cnt = int(like_str.split("万")[0]) * 10000
  212. else:
  213. like_cnt = int(like_str)
  214. if "评论" in comment_str:
  215. comment_cnt = 0
  216. elif "万" in comment_str:
  217. comment_cnt = int(comment_str.split("万")[0]) * 10000
  218. else:
  219. comment_cnt = int(comment_str)
  220. out_video_id = md5(video_title.encode('utf8')).hexdigest()
  221. out_user_id = md5(user_name.encode('utf8')).hexdigest()
  222. video_dict = {
  223. "video_title": video_title,
  224. "video_id": out_video_id,
  225. "duration_str": duration_str,
  226. "duration": duration,
  227. "play_str": play_str,
  228. "play_cnt": play_cnt,
  229. "like_str": like_str,
  230. "like_cnt": like_cnt,
  231. "comment_cnt": comment_cnt,
  232. "share_cnt": 0,
  233. "user_name": user_name,
  234. "user_id": out_user_id,
  235. 'publish_time_stamp': int(time.time()),
  236. 'publish_time_str': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()))),
  237. "avatar_url": avatar_url,
  238. "cover_url": cover_url,
  239. "session": f"xiaoniangao-{int(time.time())}"
  240. }
  241. for k, v in video_dict.items():
  242. Common.logger(log_type, crawler).info(f"{k}:{v}")
  243. Common.logging(log_type, crawler, env, f"video_dict:{video_dict}")
  244. # Common.logger(log_type, crawler).info(f"==========分割线==========\n")
  245. if video_title is None or cover_url is None:
  246. Common.logger(log_type, crawler).info("无效视频\n")
  247. Common.logging(log_type, crawler, env, '无效视频\n')
  248. cls.swipe_up(driver)
  249. time.sleep(0.5)
  250. elif download_rule(log_type=log_type, crawler=crawler, video_dict=video_dict,
  251. rule_dict=rule_dict) is False:
  252. Common.logger(log_type, crawler).info("不满足抓取规则\n")
  253. Common.logging(log_type, crawler, env, "不满足抓取规则\n")
  254. cls.swipe_up(driver)
  255. time.sleep(0.5)
  256. elif any(str(word) if str(word) in video_dict["video_title"] else False
  257. for word in get_config_from_mysql(log_type=log_type,
  258. source=crawler,
  259. env=env,
  260. text="filter",
  261. action="")) is True:
  262. Common.logger(log_type, crawler).info('已中过滤词\n')
  263. Common.logging(log_type, crawler, env, '已中过滤词\n')
  264. cls.swipe_up(driver)
  265. time.sleep(0.5)
  266. elif cls.repeat_video(log_type, crawler, out_video_id, env) != 0:
  267. Common.logger(log_type, crawler).info('视频已下载\n')
  268. Common.logging(log_type, crawler, env, '视频已下载\n')
  269. cls.swipe_up(driver)
  270. time.sleep(5)
  271. else:
  272. video_title_element = cls.search_elements(driver, f'//*[contains(text(), "{video_title}")]')
  273. if video_title_element is None:
  274. Common.logger(log_type, crawler).warning(f"未找到该视频标题的element:{video_title_element}")
  275. Common.logging(log_type, crawler, env, f"未找到该视频标题的element:{video_title_element}")
  276. continue
  277. Common.logger(log_type, crawler).info("点击标题,进入视频详情页")
  278. Common.logging(log_type, crawler, env, "点击标题,进入视频详情页")
  279. video_url = cls.get_video_url(log_type, crawler, driver, video_title_element, env=env)
  280. if video_url is None:
  281. Common.logger(log_type, crawler).info("未获取到视频播放地址\n")
  282. driver.press_keycode(AndroidKey.BACK)
  283. time.sleep(5)
  284. continue
  285. video_dict['video_url'] = video_url
  286. Common.logger(log_type, crawler).info(f"video_url:{video_url}")
  287. video_dict["platform"] = crawler
  288. video_dict["strategy"] = log_type
  289. video_dict["out_video_id"] = video_dict["video_id"]
  290. video_dict["crawler_rule"] = json.dumps(rule_dict)
  291. video_dict["user_id"] = our_uid
  292. video_dict["publish_time"] = video_dict["publish_time_str"]
  293. mq.send_msg(video_dict)
  294. # print(video_dict)
  295. cls.download_cnt += 1
  296. driver.press_keycode(AndroidKey.BACK)
  297. time.sleep(5)
  298. cls.swipe_up(driver)
  299. except Exception as e:
  300. Common.logger(log_type, crawler).error(f"抓取单条视频异常:{e}\n")
  301. Common.logging(log_type, crawler, env, f"抓取单条视频异常:{e}\n")
  302. Common.logger(log_type, crawler).info("已抓取完一组,休眠 5 秒\n")
  303. Common.logging(log_type, crawler, env, "已抓取完一组,休眠 5 秒\n")
  304. time.sleep(5)
  305. page += 1
  306. if __name__ == "__main__":
  307. rule_dict1 = {"period": {"min": 365, "max": 365},
  308. "duration": {"min": 30, "max": 1800},
  309. "favorite_cnt": {"min": 0, "max": 0},
  310. "videos_cnt": {"min": 100, "max": 0},
  311. "share_cnt": {"min": 0, "max": 0}}
  312. XiaoNianGaoPlusRecommend.start_wechat("recommend", "xiaoniangao", "dev", rule_dict1, 6267141)