xiaoniangao_plus.py 12 KB

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