xiaoniangao_plus.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. # -*- coding: utf-8 -*-
  2. # @Author: luojunhui
  3. # @Time: 2023/12/18
  4. import json
  5. import os
  6. import sys
  7. import time
  8. import uuid
  9. from hashlib import md5
  10. from appium import webdriver
  11. from appium.webdriver.extensions.android.nativekey import AndroidKey
  12. from bs4 import BeautifulSoup
  13. from selenium.common.exceptions import NoSuchElementException
  14. from selenium.webdriver.common.by import By
  15. sys.path.append(os.getcwd())
  16. from application.functions import get_redirect_url
  17. from application.pipeline import PiaoQuanPipelineTest
  18. class XiaoNianGaoPlusRecommend(object):
  19. def __init__(self, log_type, crawler, env, rule_dict, our_uid):
  20. self.mq = None
  21. self.platform = "xiaoniangaoplus"
  22. self.download_cnt = 0
  23. self.element_list = []
  24. self.count = 0
  25. self.swipe_count = 0
  26. self.log_type = log_type
  27. self.crawler = crawler
  28. self.env = env
  29. self.rule_dict = rule_dict
  30. self.our_uid = our_uid
  31. chromedriverExecutable = "/usr/bin/chromedriver"
  32. print("启动微信")
  33. # 微信的配置文件
  34. caps = {
  35. "platformName": "Android",
  36. "devicesName": "Android",
  37. "appPackage": "com.tencent.mm",
  38. "appActivity": ".ui.LauncherUI",
  39. "autoGrantPermissions": "true",
  40. "noReset": True,
  41. "resetkeyboard": True,
  42. "unicodekeyboard": True,
  43. "showChromedriverLog": True,
  44. "printPageSourceOnFailure": True,
  45. "recreateChromeDriverSessions": True,
  46. "enableWebviewDetailsCollection": True,
  47. "setWebContentsDebuggingEnabled": True,
  48. "newCommandTimeout": 6000,
  49. "automationName": "UiAutomator2",
  50. "chromedriverExecutable": chromedriverExecutable,
  51. "chromeOptions": {"androidProcess": "com.tencent.mm:appbrand0"},
  52. }
  53. try:
  54. self.driver = webdriver.Remote("http://localhost:4750/wd/hub", caps)
  55. except Exception as e:
  56. print(e)
  57. return
  58. self.driver.implicitly_wait(30)
  59. for i in range(10):
  60. try:
  61. if self.driver.find_elements(By.ID, "com.tencent.mm:id/f2s"):
  62. print("启动微信成功")
  63. break
  64. elif self.driver.find_element(
  65. By.ID, "com.android.systemui:id/dismiss_view"
  66. ):
  67. print("发现并关闭系统下拉菜单")
  68. size = self.driver.get_window_size()
  69. self.driver.swipe(
  70. int(size["width"] * 0.5),
  71. int(size["height"] * 0.8),
  72. int(size["width"] * 0.5),
  73. int(size["height"] * 0.2),
  74. 200,
  75. )
  76. else:
  77. pass
  78. except Exception as e:
  79. print(f"打开微信异常:{e}")
  80. time.sleep(1)
  81. size = self.driver.get_window_size()
  82. self.driver.swipe(
  83. int(size["width"] * 0.5),
  84. int(size["height"] * 0.2),
  85. int(size["width"] * 0.5),
  86. int(size["height"] * 0.8),
  87. 200,
  88. )
  89. time.sleep(1)
  90. self.driver.find_elements(By.XPATH, '//*[@text="小年糕+"]')[-1].click()
  91. print("打开小程序小年糕+成功")
  92. time.sleep(5)
  93. self.get_videoList()
  94. time.sleep(1)
  95. self.driver.quit()
  96. def search_elements(self, xpath):
  97. time.sleep(1)
  98. windowHandles = self.driver.window_handles
  99. for handle in windowHandles:
  100. self.driver.switch_to.window(handle)
  101. time.sleep(1)
  102. try:
  103. elements = self.driver.find_elements(By.XPATH, xpath)
  104. if elements:
  105. return elements
  106. except NoSuchElementException:
  107. pass
  108. def check_to_applet(self, xpath):
  109. time.sleep(1)
  110. webViews = self.driver.contexts
  111. self.driver.switch_to.context(webViews[-1])
  112. windowHandles = self.driver.window_handles
  113. for handle in windowHandles:
  114. self.driver.switch_to.window(handle)
  115. time.sleep(1)
  116. try:
  117. self.driver.find_element(By.XPATH, xpath)
  118. print("切换到WebView成功\n")
  119. return
  120. except NoSuchElementException:
  121. time.sleep(1)
  122. def swipe_up(self):
  123. self.search_elements('//*[@class="list-list--list"]')
  124. size = self.driver.get_window_size()
  125. self.driver.swipe(
  126. int(size["width"] * 0.5),
  127. int(size["height"] * 0.8),
  128. int(size["width"] * 0.5),
  129. int(size["height"] * 0.442),
  130. 200,
  131. )
  132. self.swipe_count += 1
  133. def get_video_url(self, video_title_element):
  134. for i in range(3):
  135. self.search_elements('//*[@class="list-list--list"]')
  136. time.sleep(1)
  137. self.driver.execute_script(
  138. "arguments[0].scrollIntoView({block:'center',inline:'center'});",
  139. video_title_element[0],
  140. )
  141. time.sleep(3)
  142. video_title_element[0].click()
  143. self.check_to_applet(
  144. xpath=r'//wx-video[@class="dynamic-index--video-item dynamic-index--video"]'
  145. )
  146. time.sleep(10)
  147. video_url_elements = self.search_elements(
  148. '//wx-video[@class="dynamic-index--video-item dynamic-index--video"]'
  149. )
  150. return video_url_elements[0].get_attribute("src")
  151. def parse_detail(self, index):
  152. page_source = self.driver.page_source
  153. soup = BeautifulSoup(page_source, "html.parser")
  154. soup.prettify()
  155. video_list = soup.findAll(
  156. name="wx-view", attrs={"class": "expose--adapt-parent"}
  157. )
  158. index = index + 1
  159. element_list = [i for i in video_list][index:]
  160. return element_list[0]
  161. def get_video_info_2(self, video_element):
  162. if self.download_cnt >= int(
  163. self.rule_dict.get("videos_cnt", {}).get("min", 10)
  164. ):
  165. self.count = 0
  166. self.download_cnt = 0
  167. self.element_list = []
  168. return
  169. self.count += 1
  170. # 获取 trace_id, 并且把该 id 当做视频生命周期唯一索引
  171. trace_id = self.crawler + str(uuid.uuid1())
  172. print("扫描到一条视频")
  173. # 标题
  174. video_title = video_element.find("wx-view", class_="dynamic--title").text
  175. # 播放量字符串
  176. play_str = video_element.find("wx-view", class_="dynamic--views").text
  177. info_list = video_element.findAll(
  178. "wx-view", class_="dynamic--commerce-btn-text"
  179. )
  180. # 点赞数量
  181. like_str = info_list[1].text
  182. # 评论数量
  183. comment_str = info_list[2].text
  184. # 视频时长
  185. duration_str = video_element.find("wx-view", class_="dynamic--duration").text
  186. user_name = video_element.find("wx-view", class_="dynamic--nick-top").text
  187. # 头像 URL
  188. avatar_url = video_element.find("wx-image", class_="avatar--avatar")["src"]
  189. # 封面 URL
  190. cover_url = video_element.find("wx-image", class_="dynamic--bg-image")["src"]
  191. play_cnt = int(play_str.replace("+", "").replace("次播放", ""))
  192. duration = int(duration_str.split(":")[0].strip()) * 60 + int(
  193. duration_str.split(":")[-1].strip()
  194. )
  195. if "点赞" in like_str:
  196. like_cnt = 0
  197. elif "万" in like_str:
  198. like_cnt = int(like_str.split("万")[0]) * 10000
  199. else:
  200. like_cnt = int(like_str)
  201. if "评论" in comment_str:
  202. comment_cnt = 0
  203. elif "万" in comment_str:
  204. comment_cnt = int(comment_str.split("万")[0]) * 10000
  205. else:
  206. comment_cnt = int(comment_str)
  207. out_video_id = md5(video_title.encode("utf8")).hexdigest()
  208. out_user_id = md5(user_name.encode("utf8")).hexdigest()
  209. video_dict = {
  210. "video_title": video_title,
  211. "video_id": out_video_id,
  212. "out_video_id": out_video_id,
  213. "duration_str": duration_str,
  214. "duration": duration,
  215. "play_str": play_str,
  216. "play_cnt": play_cnt,
  217. "like_str": like_str,
  218. "like_cnt": like_cnt,
  219. "comment_cnt": comment_cnt,
  220. "share_cnt": 0,
  221. "user_name": user_name,
  222. "user_id": out_user_id,
  223. "publish_time_stamp": int(time.time()),
  224. "publish_time_str": time.strftime(
  225. "%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()))
  226. ),
  227. "update_time_stamp": int(time.time()),
  228. "avatar_url": avatar_url,
  229. "cover_url": cover_url,
  230. "session": f"xiaoniangao-{int(time.time())}",
  231. }
  232. pipeline = PiaoQuanPipelineTest(
  233. platform=self.crawler,
  234. mode=self.log_type,
  235. item=video_dict,
  236. rule_dict=self.rule_dict,
  237. env=self.env,
  238. trace_id=trace_id,
  239. )
  240. flag = pipeline.process_item()
  241. if flag:
  242. video_title_element = self.search_elements(
  243. f'//*[contains(text(), "{video_title}")]'
  244. )
  245. if video_title_element is None:
  246. return
  247. print("点击标题,进入视频详情页")
  248. video_url = self.get_video_url(video_title_element)
  249. print(video_url)
  250. video_url = get_redirect_url(video_url)
  251. print(video_url)
  252. if video_url is None:
  253. self.driver.press_keycode(AndroidKey.BACK)
  254. time.sleep(5)
  255. return
  256. video_dict["video_url"] = video_url
  257. video_dict["platform"] = self.crawler
  258. video_dict["strategy"] = self.log_type
  259. video_dict["out_video_id"] = video_dict["video_id"]
  260. video_dict["crawler_rule"] = json.dumps(self.rule_dict)
  261. video_dict["user_id"] = self.our_uid
  262. video_dict["publish_time"] = video_dict["publish_time_str"]
  263. print(json.dumps(video_dict, ensure_ascii=False, indent=4))
  264. self.download_cnt += 1
  265. self.driver.press_keycode(AndroidKey.BACK)
  266. time.sleep(5)
  267. def get_video_info(self, video_element):
  268. try:
  269. self.get_video_info_2(video_element)
  270. except Exception as e:
  271. self.driver.press_keycode(AndroidKey.BACK)
  272. print(f"抓取单条视频异常:{e}\n")
  273. def get_videoList(self):
  274. self.driver.implicitly_wait(20)
  275. # 切换到 web_view
  276. self.check_to_applet(xpath='//*[@class="tab-bar--tab tab-bar--tab-selected"]')
  277. print("切换到 webview 成功")
  278. time.sleep(1)
  279. page = 0
  280. if self.search_elements('//*[@class="list-list--list"]') is None:
  281. print("窗口已销毁")
  282. self.count = 0
  283. self.download_cnt = 0
  284. self.element_list = []
  285. return
  286. print("开始获取视频信息")
  287. for i in range(50):
  288. print("下滑{}次".format(i))
  289. element = self.parse_detail(i)
  290. self.get_video_info(element)
  291. self.swipe_up()
  292. time.sleep(1)
  293. if self.swipe_count > 100:
  294. return
  295. print("已抓取完一组,休眠 5 秒\n")
  296. time.sleep(5)