xiaoniangao_plus_scheduling2.py 17 KB

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