zhufuquanzi_recommend_new.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. # -*- coding: utf-8 -*-
  2. # @Time: 2023/11/17
  3. import json
  4. import os
  5. import random
  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 appium.webdriver.webdriver import WebDriver
  13. from bs4 import BeautifulSoup
  14. from selenium.common import NoSuchElementException
  15. from selenium.webdriver.common.by import By
  16. sys.path.append(os.getcwd())
  17. from common import AliyunLogger, PiaoQuanPipeline, get_redirect_url
  18. from common.common import Common
  19. from common.mq import MQ
  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/piaoquan/Downloads/chromedriver"
  30. else:
  31. chromedriverExecutable = "/Users/piaoquan/Downloads/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 Exception as e:
  58. AliyunLogger.logging(
  59. code="3002",
  60. platform=ZFQZRecommend.platform,
  61. mode=log_type,
  62. env=env,
  63. message="appium 启动异常, 报错原因是{}".format(e)
  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. name = ["推荐", "搞笑", "大雪", "亲子"]
  189. selected_text = random.choice(name)
  190. try:
  191. driver.find_element(By.XPATH, f"//wx-button[contains(., '{selected_text}')]").click()
  192. time.sleep(2)
  193. except NoSuchElementException:
  194. Common.logger(log_type, crawler).info(f"没有该tab:{selected_text}\n")
  195. pass
  196. page = 0
  197. while True:
  198. if cls.search_elements(driver, '//*[@class="bless--list"]') is None:
  199. Common.logger(log_type, crawler).info("窗口已销毁\n")
  200. AliyunLogger.logging(
  201. code="3000",
  202. platform=ZFQZRecommend.platform,
  203. mode=log_type,
  204. env=env,
  205. message='窗口已销毁'
  206. )
  207. cls.i = 0
  208. cls.download_cnt = 0
  209. cls.element_list = []
  210. return
  211. cls.swipe_up(driver)
  212. page_source = driver.page_source
  213. soup = BeautifulSoup(page_source, 'html.parser')
  214. soup.prettify()
  215. video_list_elements = soup.findAll("wx-view", class_="expose--adapt-parent")
  216. # video_list_elements 有,cls.element_list 中没有的元素
  217. video_list_elements = list(set(video_list_elements).difference(set(cls.element_list)))
  218. # video_list_elements 与 cls.element_list 的并集
  219. cls.element_list = list(set(video_list_elements) | set(cls.element_list))
  220. Common.logger(log_type, crawler).info(f"正在抓取第{page + 1}页,共:{len(video_list_elements)}条视频")
  221. AliyunLogger.logging(
  222. code="1000",
  223. platform=ZFQZRecommend.platform,
  224. mode=log_type,
  225. env=env,
  226. message=f"正在抓取第{page + 1}页,共:{len(video_list_elements)}条视频"
  227. )
  228. if len(video_list_elements) == 0:
  229. for i in range(10):
  230. Common.logger(log_type, crawler).info(f"向上滑动第{i+1}次")
  231. AliyunLogger.logging(
  232. code="1000",
  233. platform=ZFQZRecommend.platform,
  234. mode=log_type,
  235. env=env,
  236. message=f"向上滑动第{i+1}次"
  237. )
  238. cls.swipe_up(driver)
  239. time.sleep(0.5)
  240. continue
  241. for i, video_element in enumerate(video_list_elements):
  242. try:
  243. Common.logger(log_type, crawler).info(f"本轮已抓取{cls.download_cnt}条视频\n")
  244. AliyunLogger.logging(
  245. code="1000",
  246. platform=ZFQZRecommend.platform,
  247. mode=log_type,
  248. env=env,
  249. message=f"本轮已抓取{cls.download_cnt}条视频\n"
  250. )
  251. if cls.download_cnt >= int(rule_dict.get("videos_cnt", {}).get("min", 10)):
  252. cls.i = 0
  253. cls.download_cnt = 0
  254. cls.element_list = []
  255. return
  256. trace_id = crawler + str(uuid.uuid1())
  257. AliyunLogger.logging(
  258. code="1001",
  259. platform=ZFQZRecommend.platform,
  260. mode=log_type,
  261. env=env,
  262. trace_id=trace_id,
  263. message="扫描到一条视频",
  264. )
  265. cls.i += 1
  266. video_title = video_element.find("wx-view", class_="dynamic--title").text
  267. play_str = video_element.find("wx-view", class_="dynamic--views").text
  268. like_str = video_element.findAll("wx-view", class_="dynamic--commerce-btn-text")[0].text
  269. comment_str = video_element.findAll("wx-view", class_="dynamic--commerce-btn-text")[1].text
  270. duration_str = video_element.find("wx-view", class_="dynamic--duration").text
  271. user_name = video_element.find("wx-view", class_="dynamic--nick-top").text
  272. avatar_url = video_element.find("wx-image", class_="avatar--avatar")["src"]
  273. cover_url = video_element.find("wx-image", class_="dynamic--bg-image")["src"]
  274. play_cnt = int(play_str.replace("+", "").replace("次播放", ""))
  275. duration = int(duration_str.split(":")[0].strip()) * 60 + int(duration_str.split(":")[-1].strip())
  276. if "点赞" in like_str:
  277. like_cnt = 0
  278. elif "万" in like_str:
  279. like_cnt = int(like_str.split("万")[0]) * 10000
  280. else:
  281. like_cnt = int(like_str)
  282. if "评论" in comment_str:
  283. comment_cnt = 0
  284. elif "万" in comment_str:
  285. comment_cnt = int(comment_str.split("万")[0]) * 10000
  286. else:
  287. comment_cnt = int(comment_str)
  288. out_video_id = md5(video_title.encode('utf8')).hexdigest()+selected_text
  289. out_user_id = md5(user_name.encode('utf8')).hexdigest()
  290. Common.logger(log_type, crawler).warning(f"视频标题:{video_title},点赞:{like_str},播放:{play_cnt},用户名称:{user_name},")
  291. video_dict = {
  292. "video_title": video_title,
  293. "video_id": out_video_id,
  294. 'out_video_id': out_video_id,
  295. "duration_str": duration_str,
  296. "duration": duration,
  297. "play_str": play_str,
  298. "play_cnt": play_cnt,
  299. "like_str": like_str,
  300. "like_cnt": like_cnt,
  301. "comment_cnt": comment_cnt,
  302. "share_cnt": 0,
  303. "user_name": user_name,
  304. "user_id": out_user_id,
  305. 'publish_time_stamp': int(time.time()),
  306. 'publish_time_str': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()))),
  307. 'update_time_stamp': int(time.time()),
  308. "avatar_url": avatar_url,
  309. "cover_url": cover_url,
  310. "session": f"zhufuquanzi-{int(time.time())}"
  311. }
  312. pipeline = PiaoQuanPipeline(
  313. platform=ZFQZRecommend.platform,
  314. mode=log_type,
  315. item=video_dict,
  316. rule_dict=rule_dict,
  317. env=env,
  318. trace_id=trace_id
  319. )
  320. flag = pipeline.process_item()
  321. if flag:
  322. video_title_element = cls.search_elements(driver, f'//*[contains(text(), "{video_title}")]')
  323. if video_title_element is None:
  324. Common.logger(log_type, crawler).warning(f"未找到该视频标题的element:{video_title_element}")
  325. continue
  326. Common.logger(log_type, crawler).info("点击标题,进入视频详情页")
  327. AliyunLogger.logging(
  328. code="1000",
  329. platform=ZFQZRecommend.platform,
  330. mode=log_type,
  331. env=env,
  332. message=f"点击标题,进入视频详情页\n"
  333. )
  334. video_url = cls.get_video_url(log_type, crawler, driver, video_title_element)
  335. video_url = get_redirect_url(video_url)
  336. if video_url is None:
  337. driver.press_keycode(AndroidKey.BACK)
  338. time.sleep(5)
  339. continue
  340. video_dict['video_url'] = video_url
  341. Common.logger(log_type, crawler).info(f"video_url:{video_url}")
  342. video_dict["platform"] = crawler
  343. video_dict["strategy"] = log_type
  344. video_dict["out_video_id"] = video_dict["video_id"]
  345. video_dict["crawler_rule"] = json.dumps(rule_dict)
  346. video_dict["user_id"] = our_uid
  347. video_dict["publish_time"] = video_dict["publish_time_str"]
  348. mq.send_msg(video_dict)
  349. cls.download_cnt += 1
  350. driver.press_keycode(AndroidKey.BACK)
  351. time.sleep(5)
  352. cls.swipe_up(driver)
  353. except Exception as e:
  354. Common.logger(log_type, crawler).error(f"抓取单条视频异常:{e}\n")
  355. driver.press_keycode(AndroidKey.BACK)
  356. AliyunLogger.logging(
  357. code="3001",
  358. platform=ZFQZRecommend.platform,
  359. mode=log_type,
  360. env=env,
  361. message=f"抓取单条视频异常:{e}\n"
  362. )
  363. Common.logger(log_type, crawler).info("已抓取完一组,休眠 5 秒\n")
  364. AliyunLogger.logging(
  365. code="1000",
  366. platform=ZFQZRecommend.platform,
  367. mode=log_type,
  368. env=env,
  369. message="已抓取完一组,休眠 5 秒\n"
  370. )
  371. time.sleep(5)
  372. page += 1
  373. if __name__ == "__main__":
  374. rule_dict1 = {"period": {"min": 365, "max": 365},
  375. "duration": {"min": 30, "max": 1800},
  376. "favorite_cnt": {"min": 5000, "max": 0},
  377. "videos_cnt": {"min": 10, "max": 20},
  378. "share_cnt": {"min": 1000, "max": 0}}
  379. ZFQZRecommend.start_wechat("recommend", "zhufuquanzi", "dev", rule_dict1, 6267141)