zhufuquanzi_recommend_new.py 17 KB

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