zhufuquanzi_recommend2.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. # -*- coding: utf-8 -*-
  2. # @Author: wang
  3. # @Time: 2023/9/6
  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 ZFQZRecommend:
  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/wangkun/Downloads/chromedriver/chromedriver_v111/chromedriver"
  29. else:
  30. chromedriverExecutable = "/Users/crawler/Downloads/chromedriver_v111/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": "11",
  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. cls.get_videoList(log_type, crawler, driver, env, rule_dict, our_uid)
  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 check_to_applet(cls, log_type, crawler, env, driver: WebDriver, xpath):
  98. time.sleep(1)
  99. webViews = driver.contexts
  100. Common.logger(log_type, crawler).info(f"webViews:{webViews}")
  101. Common.logging(log_type, crawler, env, f"webViews:{webViews}")
  102. driver.switch_to.context(webViews[1])
  103. windowHandles = driver.window_handles
  104. for handle in windowHandles:
  105. driver.switch_to.window(handle)
  106. time.sleep(1)
  107. try:
  108. driver.find_element(By.XPATH, xpath)
  109. Common.logger(log_type, crawler).info("切换到小程序成功\n")
  110. Common.logging(log_type, crawler, env, '切换到小程序成功\n')
  111. return
  112. except NoSuchElementException:
  113. time.sleep(1)
  114. @classmethod
  115. def repeat_video(cls, log_type, crawler, video_id, env):
  116. sql = f""" select * from crawler_video where platform in ("众妙音信", "刚刚都传", "吉祥幸福", "知青天天看", "zhufuquanzi", "祝福圈子", "haitunzhufu", "海豚祝福") and out_video_id="{video_id}"; """
  117. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  118. return len(repeat_video)
  119. @classmethod
  120. def swipe_up(cls, driver: WebDriver):
  121. cls.search_elements(driver, '//*[@class="bless--list"]')
  122. size = driver.get_window_size()
  123. driver.swipe(int(size["width"] * 0.5), int(size["height"] * 0.8),
  124. int(size["width"] * 0.5), int(size["height"] * 0.4), 200)
  125. @classmethod
  126. def get_video_url(cls, log_type, crawler, driver: WebDriver, video_title_element):
  127. for i in range(3):
  128. cls.search_elements(driver, '//*[@class="bless--list"]')
  129. Common.logger(log_type, crawler).info(f"video_title_element:{video_title_element[0]}")
  130. time.sleep(1)
  131. Common.logger(log_type, crawler).info("滑动标题至可见状态")
  132. driver.execute_script("arguments[0].scrollIntoView({block:'center',inline:'center'});", video_title_element[0])
  133. time.sleep(3)
  134. Common.logger(log_type, crawler).info("点击标题")
  135. video_title_element[0].click()
  136. # driver.execute_script("arguments[0].click();", video_title_element[0])
  137. Common.logger(log_type, crawler).info("点击标题完成")
  138. time.sleep(1)
  139. video_url_elements = cls.search_elements(driver, '//*[@class="index--video-item index--video"]')
  140. if video_url_elements:
  141. return video_url_elements[0].get_attribute("src")
  142. @classmethod
  143. def get_videoList(cls, log_type, crawler, driver: WebDriver, env, rule_dict, our_uid):
  144. mq = MQ(topic_name="topic_crawler_etl_" + env)
  145. driver.implicitly_wait(20)
  146. cls.check_to_applet(log_type=log_type, crawler=crawler, env=env, driver=driver,
  147. xpath='//*[@class="tags--tag tags--tag-0 tags--checked"]')
  148. time.sleep(1)
  149. page = 0
  150. while True:
  151. if cls.search_elements(driver, '//*[@class="bless--list"]') is None:
  152. Common.logger(log_type, crawler).info("窗口已销毁\n")
  153. Common.logging(log_type, crawler, env, '窗口已销毁\n')
  154. cls.i = 0
  155. cls.download_cnt = 0
  156. cls.element_list = []
  157. return
  158. cls.swipe_up(driver)
  159. page_source = driver.page_source
  160. soup = BeautifulSoup(page_source, 'html.parser')
  161. soup.prettify()
  162. video_list_elements = soup.findAll("wx-view", class_="expose--adapt-parent")
  163. # video_list_elements 有,cls.element_list 中没有的元素
  164. video_list_elements = list(set(video_list_elements).difference(set(cls.element_list)))
  165. # video_list_elements 与 cls.element_list 的并集
  166. cls.element_list = list(set(video_list_elements) | set(cls.element_list))
  167. Common.logger(log_type, crawler).info(f"正在抓取第{page + 1}页,共:{len(video_list_elements)}条视频")
  168. Common.logging(log_type, crawler, env, f"正在抓取第{page + 1}页,共:{len(video_list_elements)}条视频")
  169. if len(video_list_elements) == 0:
  170. for i in range(10):
  171. Common.logger(log_type, crawler).info(f"向上滑动第{i+1}次")
  172. cls.swipe_up(driver)
  173. time.sleep(0.5)
  174. continue
  175. for i, video_element in enumerate(video_list_elements):
  176. try:
  177. Common.logger(log_type, crawler).info(f"本轮已抓取{cls.download_cnt}条视频\n")
  178. Common.logging(log_type, crawler, env, f"本轮已抓取{cls.download_cnt}条视频\n")
  179. if cls.download_cnt >= int(rule_dict.get("videos_cnt", {}).get("min", 10)):
  180. cls.i = 0
  181. cls.download_cnt = 0
  182. cls.element_list = []
  183. return
  184. cls.i += 1
  185. Common.logger(log_type, crawler).info(f"第{cls.i}条视频")
  186. Common.logging(log_type, crawler, env, f"第{cls.i}条视频")
  187. video_title = video_element.find("wx-view", class_="dynamic--title").text
  188. play_str = video_element.find("wx-view", class_="dynamic--views").text
  189. like_str = video_element.findAll("wx-view", class_="dynamic--commerce-btn-text")[0].text
  190. comment_str = video_element.findAll("wx-view", class_="dynamic--commerce-btn-text")[1].text
  191. duration_str = video_element.find("wx-view", class_="dynamic--duration").text
  192. user_name = video_element.find("wx-view", class_="dynamic--nick-top").text
  193. avatar_url = video_element.find("wx-image", class_="avatar--avatar")["src"]
  194. cover_url = video_element.find("wx-image", class_="dynamic--bg-image")["src"]
  195. play_cnt = int(play_str.replace("+", "").replace("次播放", ""))
  196. duration = int(duration_str.split(":")[0].strip()) * 60 + int(duration_str.split(":")[-1].strip())
  197. if "点赞" in like_str:
  198. like_cnt = 0
  199. elif "万" in like_str:
  200. like_cnt = int(like_str.split("万")[0]) * 10000
  201. else:
  202. like_cnt = int(like_str)
  203. if "评论" in comment_str:
  204. comment_cnt = 0
  205. elif "万" in comment_str:
  206. comment_cnt = int(comment_str.split("万")[0]) * 10000
  207. else:
  208. comment_cnt = int(comment_str)
  209. out_video_id = md5(video_title.encode('utf8')).hexdigest()
  210. out_user_id = md5(user_name.encode('utf8')).hexdigest()
  211. video_dict = {
  212. "video_title": video_title,
  213. "video_id": out_video_id,
  214. "duration_str": duration_str,
  215. "duration": duration,
  216. "play_str": play_str,
  217. "play_cnt": play_cnt,
  218. "like_str": like_str,
  219. "like_cnt": like_cnt,
  220. "comment_cnt": comment_cnt,
  221. "share_cnt": 0,
  222. "user_name": user_name,
  223. "user_id": out_user_id,
  224. 'publish_time_stamp': int(time.time()),
  225. 'publish_time_str': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()))),
  226. "avatar_url": avatar_url,
  227. "cover_url": cover_url,
  228. "session": f"zhufuquanzi-{int(time.time())}"
  229. }
  230. for k, v in video_dict.items():
  231. Common.logger(log_type, crawler).info(f"{k}:{v}")
  232. Common.logging(log_type, crawler, env, f"video_dict:{video_dict}")
  233. # Common.logger(log_type, crawler).info(f"==========分割线==========\n")
  234. if video_title is None or cover_url is None:
  235. Common.logger(log_type, crawler).info("无效视频\n")
  236. Common.logging(log_type, crawler, env, '无效视频\n')
  237. cls.swipe_up(driver)
  238. time.sleep(0.5)
  239. elif download_rule(log_type=log_type, crawler=crawler, video_dict=video_dict,
  240. rule_dict=rule_dict) is False:
  241. Common.logger(log_type, crawler).info("不满足抓取规则\n")
  242. Common.logging(log_type, crawler, env, "不满足抓取规则\n")
  243. cls.swipe_up(driver)
  244. time.sleep(0.5)
  245. elif any(str(word) if str(word) in video_dict["video_title"] else False
  246. for word in get_config_from_mysql(log_type=log_type,
  247. source=crawler,
  248. env=env,
  249. text="filter",
  250. action="")) is True:
  251. Common.logger(log_type, crawler).info('已中过滤词\n')
  252. Common.logging(log_type, crawler, env, '已中过滤词\n')
  253. cls.swipe_up(driver)
  254. time.sleep(0.5)
  255. elif cls.repeat_video(log_type, crawler, out_video_id, env) != 0:
  256. Common.logger(log_type, crawler).info('视频已下载\n')
  257. Common.logging(log_type, crawler, env, '视频已下载\n')
  258. cls.swipe_up(driver)
  259. time.sleep(5)
  260. else:
  261. video_title_element = cls.search_elements(driver, f'//*[contains(text(), "{video_title}")]')
  262. if video_title_element is None:
  263. Common.logger(log_type, crawler).warning(f"未找到该视频标题的element:{video_title_element}")
  264. Common.logging(log_type, crawler, env, f"未找到该视频标题的element:{video_title_element}")
  265. continue
  266. Common.logger(log_type, crawler).info("点击标题,进入视频详情页")
  267. Common.logging(log_type, crawler, env, "点击标题,进入视频详情页")
  268. video_url = cls.get_video_url(log_type, crawler, driver, video_title_element)
  269. if video_url is None:
  270. Common.logger(log_type, crawler).info("未获取到视频播放地址\n")
  271. driver.press_keycode(AndroidKey.BACK)
  272. time.sleep(5)
  273. continue
  274. video_dict['video_url'] = video_url
  275. Common.logger(log_type, crawler).info(f"video_url:{video_url}")
  276. video_dict["platform"] = crawler
  277. video_dict["strategy"] = log_type
  278. video_dict["out_video_id"] = video_dict["video_id"]
  279. video_dict["crawler_rule"] = json.dumps(rule_dict)
  280. video_dict["user_id"] = our_uid
  281. video_dict["publish_time"] = video_dict["publish_time_str"]
  282. mq.send_msg(video_dict)
  283. cls.download_cnt += 1
  284. driver.press_keycode(AndroidKey.BACK)
  285. time.sleep(5)
  286. cls.swipe_up(driver)
  287. except Exception as e:
  288. Common.logger(log_type, crawler).error(f"抓取单条视频异常:{e}\n")
  289. Common.logging(log_type, crawler, env, f"抓取单条视频异常:{e}\n")
  290. Common.logger(log_type, crawler).info("已抓取完一组,休眠 5 秒\n")
  291. Common.logging(log_type, crawler, env, "已抓取完一组,休眠 5 秒\n")
  292. time.sleep(5)
  293. page += 1
  294. if __name__ == "__main__":
  295. rule_dict1 = {"period": {"min": 365, "max": 365},
  296. "duration": {"min": 30, "max": 1800},
  297. "favorite_cnt": {"min": 5000, "max": 0},
  298. "videos_cnt": {"min": 10, "max": 20},
  299. "share_cnt": {"min": 1000, "max": 0}}
  300. ZFQZRecommend.start_wechat("recommend", "zhufuquanzi", "dev", rule_dict1, 6267141)