shipinhao_recommend.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/7/25
  4. import datetime
  5. import os
  6. import sys
  7. import time
  8. from datetime import date, timedelta
  9. from hashlib import md5
  10. from appium import webdriver
  11. from appium.webdriver.webdriver import WebDriver
  12. from selenium.common import NoSuchElementException
  13. from selenium.webdriver.common.by import By
  14. sys.path.append(os.getcwd())
  15. from common.common import Common
  16. from common.public import download_rule
  17. from common.scheduling_db import MysqlHelper
  18. class ShipinhaoRecommend:
  19. platform = "视频号"
  20. download_video_list = []
  21. scan_count = 20
  22. @classmethod
  23. def repeat_out_video_id(cls, log_type, crawler, out_video_id, env):
  24. sql = f""" select * from crawler_video where platform in ("{crawler}","{cls.platform}") and out_video_id="{out_video_id}"; """
  25. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  26. return len(repeat_video)
  27. @classmethod
  28. def start_wechat(cls, log_type, crawler, env):
  29. Common.logger(log_type, crawler).info('启动微信')
  30. if env == "dev":
  31. chromedriverExecutable = "/Users/wangkun/Downloads/chromedriver/chromedriver_v107/chromedriver"
  32. else:
  33. chromedriverExecutable = '/Users/piaoquan/Downloads/chromedriver'
  34. caps = {
  35. "platformName": "Android", # 手机操作系统 Android / iOS
  36. "deviceName": "Android", # 连接的设备名(模拟器或真机),安卓可以随便写
  37. "platforVersion": "13", # 手机对应的系统版本(Android 13)
  38. "appPackage": "com.tencent.mm", # 被测APP的包名,乐活圈 Android
  39. "appActivity": ".ui.LauncherUI", # 启动的Activity名
  40. "autoGrantPermissions": True, # 让 appium 自动授权 base 权限,
  41. # 如果 noReset 为 True,则该条不生效(该参数为 Android 独有),对应的值为 True 或 False
  42. "unicodekeyboard": True, # 使用自带输入法,输入中文时填True
  43. "resetkeyboard": True, # 执行完程序恢复原来输入法
  44. "noReset": True, # 不重置APP
  45. "recreateChromeDriverSessions": True, # 切换到非 chrome-Driver 会 kill 掉 session,就不需要手动 kill 了
  46. "printPageSourceOnFailure": True, # 找不到元素时,appium log 会完整记录当前页面的 pagesource
  47. "newCommandTimeout": 6000, # 初始等待时间
  48. "automationName": "UiAutomator2", # 使用引擎,默认为 Appium,
  49. # 其中 Appium、UiAutomator2、Selendroid、Espresso 用于 Android,XCUITest 用于 iOS
  50. "showChromedriverLog": True,
  51. # "chromeOptions": {"androidProcess": "com.tencent.mm:appbrand0"},
  52. "chromeOptions": {"androidProcess": "com.tencent.mm:tools"},
  53. # "chromeOptions": {"androidProcess": "com.tencent.mm:toolsmp"},
  54. # "chromeOptions": {"androidProcess": "com.tencent.mm"},
  55. 'enableWebviewDetailsCollection': True,
  56. 'setWebContentsDebuggingEnabled': True,
  57. 'chromedriverExecutable': chromedriverExecutable,
  58. }
  59. driver = webdriver.Remote("http://localhost:4723/wd/hub", caps)
  60. driver.implicitly_wait(10)
  61. time.sleep(5)
  62. return driver
  63. @classmethod
  64. def get_videoList(cls, log_type, crawler, rule_dict, env, driver: WebDriver):
  65. Common.logger(log_type, crawler).info("进入发现页")
  66. tabs = driver.find_elements(By.ID, "com.tencent.mm:id/f2s")
  67. for tab in tabs:
  68. if tab.text == "发现":
  69. tab.click()
  70. time.sleep(0.5)
  71. break
  72. Common.logger(log_type, crawler).info('点击"视频号"')
  73. textviews = driver.find_elements(By.ID, "android:id/title")
  74. for textview in textviews:
  75. if textview.text == "视频号":
  76. textview.click()
  77. time.sleep(0.5)
  78. break
  79. # 关闭青少年模式弹框
  80. Common.logger(log_type, crawler).info("尝试关闭青少年模式弹框\n")
  81. try:
  82. driver.find_element(By.ID, "com.tencent.mm:id/lqz").click()
  83. except NoSuchElementException:
  84. pass
  85. for i in range(cls.scan_count):
  86. Common.logger(log_type, crawler).info(f"第{i + 1}条视频")
  87. if len(driver.find_elements(By.ID, "com.tencent.mm:id/dkf")) != 0:
  88. Common.logger(log_type, crawler).info("这是一个直播间,滑动至下一个视频\n")
  89. driver.swipe(10, 1600, 10, 300, 200)
  90. continue
  91. video_dict = cls.get_video_info(driver)
  92. for k, v in video_dict.items():
  93. Common.logger(log_type, crawler).info(f"{k}:{v}")
  94. if video_dict["video_title"] is None:
  95. Common.logger(log_type, crawler).info("无效视频")
  96. elif download_rule(log_type=log_type, crawler=crawler, video_dict=video_dict, rule_dict=rule_dict) is False:
  97. Common.logger(log_type, crawler).info("不满足抓取规则")
  98. # Common.logging(log_type, crawler, env, "不满足抓取规则\n")
  99. elif cls.repeat_out_video_id(log_type, crawler, video_dict["video_id"], env) != 0:
  100. Common.logger(log_type, crawler).info('视频已下载')
  101. # Common.logging(log_type, crawler, env, '视频已下载\n')
  102. else:
  103. cls.download_video_list.append(video_dict)
  104. if i+1 == cls.scan_count:
  105. Common.logger(log_type, crawler).info("扫描一轮结束\n")
  106. driver.quit()
  107. return
  108. Common.logger(log_type, crawler).info(f"已抓取符合规则视频{len(cls.download_video_list)}条,滑动至下一个视频\n")
  109. driver.swipe(10, 1600, 10, 300, 200)
  110. @classmethod
  111. def is_contain_chinese(cls, strword):
  112. for ch in strword:
  113. if u'\u4e00' <= ch <= u'\u9fff':
  114. return True
  115. return False
  116. @classmethod
  117. def get_video_info(cls, driver: WebDriver):
  118. # 点击暂停
  119. global duration
  120. for i in range(3):
  121. try:
  122. driver.find_element(By.ID, "com.tencent.mm:id/gpx").click()
  123. duration_str = driver.find_element(By.ID, "com.tencent.mm:id/l7i").text
  124. duration = int(duration_str.split(":")[0]) * 60 + int(duration_str.split(":")[-1])
  125. break
  126. except NoSuchElementException:
  127. duration = 0
  128. # user_name
  129. user_name = driver.find_element(By.ID, "com.tencent.mm:id/hft").text
  130. # 点赞
  131. like_cnt = driver.find_element(By.ID, 'com.tencent.mm:id/k04').text
  132. if like_cnt == "" or like_cnt == "喜欢" or like_cnt == "火":
  133. like_cnt = 0
  134. elif '万+' in like_cnt:
  135. like_cnt = int(float(like_cnt.split('万+')[0]) * 10000)
  136. elif '万' in like_cnt:
  137. like_cnt = int(float(like_cnt.split('万')[0]) * 10000)
  138. else:
  139. like_cnt = int(float(like_cnt))
  140. # 分享
  141. share_cnt = driver.find_element(By.ID, 'com.tencent.mm:id/jhv').text
  142. if share_cnt == "" or share_cnt == "转发":
  143. share_cnt = 0
  144. elif '万+' in share_cnt:
  145. share_cnt = int(float(share_cnt.split('万+')[0]) * 10000)
  146. elif '万' in share_cnt:
  147. share_cnt = int(float(share_cnt.split('万')[0]) * 10000)
  148. else:
  149. share_cnt = int(float(share_cnt))
  150. # 收藏
  151. favorite_cnt = driver.find_element(By.ID, 'com.tencent.mm:id/fnp').text
  152. if favorite_cnt == "" or favorite_cnt == "收藏" or favorite_cnt == "推荐" or favorite_cnt == "火":
  153. favorite_cnt = 0
  154. elif '万+' in favorite_cnt:
  155. favorite_cnt = int(float(favorite_cnt.split('万+')[0]) * 10000)
  156. elif '万' in favorite_cnt:
  157. favorite_cnt = int(float(favorite_cnt.split('万')[0]) * 10000)
  158. else:
  159. favorite_cnt = int(float(favorite_cnt))
  160. # 评论
  161. comment_id = driver.find_element(By.ID, 'com.tencent.mm:id/bje')
  162. comment_cnt = comment_id.text
  163. if comment_cnt == "" or comment_cnt == "评论":
  164. comment_cnt = 0
  165. elif '万+' in comment_cnt:
  166. comment_cnt = int(float(comment_cnt.split('万+')[0]) * 10000)
  167. elif '万' in comment_cnt:
  168. comment_cnt = int(float(comment_cnt.split('万')[0]) * 10000)
  169. else:
  170. comment_cnt = int(float(comment_cnt))
  171. comment_id.click()
  172. time.sleep(1)
  173. # title
  174. title = driver.find_elements(By.ID, "com.tencent.mm:id/bga")[0].text.replace("\n", " ")[:40]
  175. # 发布时间
  176. publish_time = driver.find_element(By.ID, "com.tencent.mm:id/bre").get_attribute("name")
  177. if "秒" in publish_time or "分钟" in publish_time or "小时" in publish_time:
  178. publish_time_str = (date.today() + timedelta(days=0)).strftime("%Y-%m-%d")
  179. elif "天前" in publish_time:
  180. days = int(publish_time.replace("天前", ""))
  181. publish_time_str = (date.today() + timedelta(days=-days)).strftime("%Y-%m-%d")
  182. elif "年" in publish_time:
  183. year_str = publish_time.split("年")[0]
  184. month_str = publish_time.split("年")[-1].split("月")[0]
  185. day_str = publish_time.split("月")[-1].split("日")[0]
  186. if int(month_str) < 10:
  187. month_str = f"0{month_str}"
  188. if int(day_str) < 10:
  189. day_str = f"0{day_str}"
  190. publish_time_str = f"{year_str}-{month_str}-{day_str}"
  191. else:
  192. year_str = str(datetime.datetime.now().year)
  193. month_str = publish_time.split("月")[0]
  194. day_str = publish_time.split("月")[-1].split("日")[0]
  195. if int(month_str) < 10:
  196. month_str = f"0{month_str}"
  197. if int(day_str) < 10:
  198. day_str = f"0{day_str}"
  199. publish_time_str = f"{year_str}-{month_str}-{day_str}"
  200. publish_time_stamp = int(time.mktime(time.strptime(publish_time_str, "%Y-%m-%d")))
  201. # 收起评论
  202. driver.find_element(By.ID, "com.tencent.mm:id/be_").click()
  203. time.sleep(0.5)
  204. video_id = md5(title.encode('utf8')).hexdigest()
  205. video_dict = {
  206. "video_title": title,
  207. "video_id": video_id,
  208. "duration": duration,
  209. "user_name": user_name,
  210. "like_cnt": like_cnt,
  211. "share_cnt": share_cnt,
  212. "favorite_cnt": favorite_cnt,
  213. "comment_cnt": comment_cnt,
  214. "publish_time_str": publish_time_str,
  215. "publish_time_stamp": publish_time_stamp,
  216. }
  217. return video_dict
  218. @classmethod
  219. def get_recommend_list(cls, log_type, crawler, rule_dict, env):
  220. driver = cls.start_wechat(log_type, crawler, env)
  221. cls.get_videoList(log_type=log_type,
  222. crawler=crawler,
  223. rule_dict=rule_dict,
  224. env=env,
  225. driver=driver)
  226. driver.quit()
  227. Common.logger(log_type, crawler).info(f"微信退出成功\n")
  228. if __name__ == "__main__":
  229. rule_dict1 = {"period": {"min": 365, "max": 365},
  230. "duration": {"min": 10, "max": 1800},
  231. "favorite_cnt": {"min": 50000, "max": 0},
  232. "share_cnt": {"min": 10000, "max": 0}}
  233. ShipinhaoRecommend.get_recommend_list("recommend", "shipinhao", rule_dict1, "dev")
  234. print(ShipinhaoRecommend.download_video_list)
  235. pass