xiaoniangao_plus_scheduling.py 17 KB

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