shipinhao_recommend.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. @classmethod
  22. def repeat_out_video_id(cls, log_type, crawler, out_video_id, env):
  23. sql = f""" select * from crawler_video where platform in ("{crawler}","{cls.platform}") and out_video_id="{out_video_id}"; """
  24. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  25. return len(repeat_video)
  26. @classmethod
  27. def start_wechat(cls, log_type, crawler, env):
  28. Common.logger(log_type, crawler).info('启动微信')
  29. Common.logging(log_type, crawler, env, '启动微信')
  30. if env == "dev":
  31. chromedriverExecutable = "/Users/wangkun/Downloads/chromedriver/chromedriver_v107/chromedriver"
  32. else:
  33. chromedriverExecutable = '/Users/lieyunye/Downloads/chromedriver/chromedriver_v111/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, scan_count, driver: WebDriver):
  65. Common.logger(log_type, crawler).info("进入发现页")
  66. Common.logging(log_type, crawler, env, "进入发现页")
  67. tabs = driver.find_elements(By.ID, "com.tencent.mm:id/f2s")
  68. for tab in tabs:
  69. if tab.text == "发现":
  70. tab.click()
  71. time.sleep(0.5)
  72. break
  73. Common.logger(log_type, crawler).info('点击"视频号"')
  74. Common.logging(log_type, crawler, env, '点击"视频号"')
  75. textviews = driver.find_elements(By.ID, "android:id/title")
  76. for textview in textviews:
  77. if textview.text == "视频号":
  78. textview.click()
  79. time.sleep(0.5)
  80. break
  81. # 关闭青少年模式弹框
  82. Common.logger(log_type, crawler).info("尝试关闭青少年模式弹框\n")
  83. Common.logging(log_type, crawler, env, "尝试关闭青少年模式弹框\n")
  84. try:
  85. driver.find_element(By.ID, "com.tencent.mm:id/lqz").click()
  86. except NoSuchElementException:
  87. pass
  88. for i in range(scan_count):
  89. try:
  90. Common.logger(log_type, crawler).info(f"第{i + 1}条视频")
  91. Common.logging(log_type, crawler, env, f"第{i + 1}条视频")
  92. if len(driver.find_elements(By.ID, "com.tencent.mm:id/dkf")) != 0:
  93. Common.logger(log_type, crawler).info("这是一个直播间,滑动至下一个视频\n")
  94. Common.logging(log_type, crawler, env, "这是一个直播间,滑动至下一个视频\n")
  95. driver.swipe(10, 1600, 10, 300, 200)
  96. continue
  97. video_dict = cls.get_video_info(driver)
  98. for k, v in video_dict.items():
  99. Common.logger(log_type, crawler).info(f"{k}:{v}")
  100. Common.logging(log_type, crawler, env, f"video_dict:{video_dict}")
  101. if video_dict["video_title"] is None:
  102. Common.logger(log_type, crawler).info("无效视频")
  103. Common.logging(log_type, crawler, env, "无效视频")
  104. elif download_rule(log_type=log_type, crawler=crawler, video_dict=video_dict, rule_dict=rule_dict) is False:
  105. Common.logger(log_type, crawler).info("不满足抓取规则")
  106. Common.logging(log_type, crawler, env, "不满足抓取规则\n")
  107. elif cls.repeat_out_video_id(log_type, crawler, video_dict["video_id"], env) != 0:
  108. Common.logger(log_type, crawler).info('视频已下载')
  109. Common.logging(log_type, crawler, env, '视频已下载\n')
  110. else:
  111. cls.download_video_list.append(video_dict)
  112. if i+1 == scan_count:
  113. Common.logger(log_type, crawler).info("扫描一轮结束\n")
  114. Common.logging(log_type, crawler, env, "扫描一轮结束\n")
  115. return
  116. Common.logger(log_type, crawler).info(f"已抓取符合规则视频{len(cls.download_video_list)}条,滑动至下一个视频\n")
  117. Common.logging(log_type, crawler, env, f"已抓取符合规则视频{len(cls.download_video_list)}条,滑动至下一个视频\n")
  118. driver.swipe(10, 1600, 10, 300, 200)
  119. except Exception as e:
  120. Common.logger(log_type, crawler).info(f"扫描单条视频时异常:{e}\n")
  121. Common.logging(log_type, crawler, env, f"扫描单条视频时异常:{e}\n")
  122. @classmethod
  123. def is_contain_chinese(cls, strword):
  124. for ch in strword:
  125. if u'\u4e00' <= ch <= u'\u9fff':
  126. return True
  127. return False
  128. @classmethod
  129. def get_video_info(cls, driver: WebDriver):
  130. # 点击暂停
  131. global duration
  132. for i in range(3):
  133. pause_elements = driver.find_elements(By.ID, "com.tencent.mm:id/gpx")
  134. if len(pause_elements) != 0:
  135. pause_elements[0].click()
  136. try:
  137. duration_str = driver.find_element(By.ID, "com.tencent.mm:id/l7i").text
  138. duration = int(duration_str.split(":")[0]) * 60 + int(duration_str.split(":")[-1])
  139. break
  140. except NoSuchElementException:
  141. duration = 0
  142. else:
  143. duration = 0
  144. # user_name
  145. user_name = driver.find_element(By.ID, "com.tencent.mm:id/hft").text
  146. # 点赞
  147. like_cnt = driver.find_element(By.ID, 'com.tencent.mm:id/k04').text
  148. if like_cnt == "" or like_cnt == "喜欢" or like_cnt == "火":
  149. like_cnt = 0
  150. elif '万+' in like_cnt:
  151. like_cnt = int(float(like_cnt.split('万+')[0]) * 10000)
  152. elif '万' in like_cnt:
  153. like_cnt = int(float(like_cnt.split('万')[0]) * 10000)
  154. else:
  155. like_cnt = int(float(like_cnt))
  156. # 分享
  157. share_cnt = driver.find_element(By.ID, 'com.tencent.mm:id/jhv').text
  158. if share_cnt == "" or share_cnt == "转发":
  159. share_cnt = 0
  160. elif '万+' in share_cnt:
  161. share_cnt = int(float(share_cnt.split('万+')[0]) * 10000)
  162. elif '万' in share_cnt:
  163. share_cnt = int(float(share_cnt.split('万')[0]) * 10000)
  164. else:
  165. share_cnt = int(float(share_cnt))
  166. # 收藏
  167. favorite_cnt = driver.find_element(By.ID, 'com.tencent.mm:id/fnp').text
  168. if favorite_cnt == "" or favorite_cnt == "收藏" or favorite_cnt == "推荐" or favorite_cnt == "火":
  169. favorite_cnt = 0
  170. elif '万+' in favorite_cnt:
  171. favorite_cnt = int(float(favorite_cnt.split('万+')[0]) * 10000)
  172. elif '万' in favorite_cnt:
  173. favorite_cnt = int(float(favorite_cnt.split('万')[0]) * 10000)
  174. else:
  175. favorite_cnt = int(float(favorite_cnt))
  176. # 评论
  177. comment_id = driver.find_element(By.ID, 'com.tencent.mm:id/bje')
  178. comment_cnt = comment_id.text
  179. if comment_cnt == "" or comment_cnt == "评论":
  180. comment_cnt = 0
  181. elif '万+' in comment_cnt:
  182. comment_cnt = int(float(comment_cnt.split('万+')[0]) * 10000)
  183. elif '万' in comment_cnt:
  184. comment_cnt = int(float(comment_cnt.split('万')[0]) * 10000)
  185. else:
  186. comment_cnt = int(float(comment_cnt))
  187. comment_id.click()
  188. time.sleep(1)
  189. # title
  190. title_elements = driver.find_elements(By.ID, "com.tencent.mm:id/bga")
  191. if len(title_elements) == 0:
  192. title = ""
  193. else:
  194. title = title_elements[0].text.replace("\n", " ")[:40]
  195. # 发布时间
  196. publish_time = driver.find_element(By.ID, "com.tencent.mm:id/bre").get_attribute("name")
  197. if "秒" in publish_time or "分钟" in publish_time or "小时" in publish_time:
  198. publish_time_str = (date.today() + timedelta(days=0)).strftime("%Y-%m-%d")
  199. elif "天前" in publish_time:
  200. days = int(publish_time.replace("天前", ""))
  201. publish_time_str = (date.today() + timedelta(days=-days)).strftime("%Y-%m-%d")
  202. elif "年" in publish_time:
  203. year_str = publish_time.split("年")[0]
  204. month_str = publish_time.split("年")[-1].split("月")[0]
  205. day_str = publish_time.split("月")[-1].split("日")[0]
  206. if int(month_str) < 10:
  207. month_str = f"0{month_str}"
  208. if int(day_str) < 10:
  209. day_str = f"0{day_str}"
  210. publish_time_str = f"{year_str}-{month_str}-{day_str}"
  211. else:
  212. year_str = str(datetime.datetime.now().year)
  213. month_str = publish_time.split("月")[0]
  214. day_str = publish_time.split("月")[-1].split("日")[0]
  215. if int(month_str) < 10:
  216. month_str = f"0{month_str}"
  217. if int(day_str) < 10:
  218. day_str = f"0{day_str}"
  219. publish_time_str = f"{year_str}-{month_str}-{day_str}"
  220. publish_time_stamp = int(time.mktime(time.strptime(publish_time_str, "%Y-%m-%d")))
  221. # 收起评论
  222. driver.find_element(By.ID, "com.tencent.mm:id/be_").click()
  223. time.sleep(0.5)
  224. video_id = md5(title.encode('utf8')).hexdigest()
  225. video_dict = {
  226. "video_title": title,
  227. "video_id": video_id,
  228. "duration": duration,
  229. "user_name": user_name,
  230. "like_cnt": like_cnt,
  231. "share_cnt": share_cnt,
  232. "favorite_cnt": favorite_cnt,
  233. "comment_cnt": comment_cnt,
  234. "publish_time_str": publish_time_str+" 00:00:00",
  235. "publish_time_stamp": publish_time_stamp,
  236. }
  237. return video_dict
  238. @classmethod
  239. def get_recommend_list(cls, log_type, crawler, rule_dict, scan_count, env):
  240. # try:
  241. driver = cls.start_wechat(log_type, crawler, env)
  242. cls.get_videoList(log_type=log_type,
  243. crawler=crawler,
  244. rule_dict=rule_dict,
  245. env=env,
  246. scan_count=scan_count,
  247. driver=driver)
  248. driver.quit()
  249. Common.logger(log_type, crawler).info(f"微信退出成功\n")
  250. Common.logging(log_type, crawler, env, f"微信退出成功\n")
  251. # except Exception as e:
  252. # Common.logger(log_type, crawler).info(f"扫描视频列表异常:{e}\n")
  253. # Common.logging(log_type, crawler, env, f"扫描视频列表异常:{e}\n")
  254. if __name__ == "__main__":
  255. rule_dict1 = {"period": {"min": 365, "max": 365},
  256. "duration": {"min": 10, "max": 1800},
  257. "favorite_cnt": {"min": 50000, "max": 0},
  258. "share_cnt": {"min": 10000, "max": 0}}
  259. ShipinhaoRecommend.get_recommend_list("recommend", "shipinhao", rule_dict1, 5, "dev")
  260. print(ShipinhaoRecommend.download_video_list)
  261. pass