xiaoniangao_plus_scheduling2.py 17 KB

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