shipinhao_recommend.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. # @Author: wangkun
  2. # @Time: 3月 02, 2022
  3. import os
  4. import sys
  5. import time
  6. from appium import webdriver
  7. from appium.webdriver.webdriver import WebDriver
  8. from selenium.common.exceptions import NoSuchElementException
  9. from selenium.webdriver.common.by import By
  10. sys.path.append(os.getcwd())
  11. from main.common import Common
  12. from main.publish import Publish
  13. from main.feishu_lib import Feishu
  14. class Recommend:
  15. # 当日已下载数量
  16. download_cnt = []
  17. # 启动微信,并打开视频号
  18. @classmethod
  19. def start_wechat(cls, log_type, env):
  20. try:
  21. Common.logger(log_type).info('启动微信')
  22. caps = {
  23. "platformName": "Android", # 手机操作系统 Android / iOS
  24. "deviceName": "Android", # 连接的设备名(模拟器或真机),安卓可以随便写
  25. "platforVersion": "11", # 手机对应的系统版本(Android 11)
  26. "appPackage": "com.tencent.mm", # 被测APP的包名,乐活圈 Android
  27. "appActivity": ".ui.LauncherUI", # 启动的Activity名
  28. "autoGrantPermissions": "true", # 让 appium 自动授权 base 权限,
  29. # 如果 noReset 为 True,则该条不生效(该参数为 Android 独有),对应的值为 True 或 False
  30. "unicodekeyboard": True, # 使用自带输入法,输入中文时填True
  31. "resetkeyboard": True, # 执行完程序恢复原来输入法
  32. "noReset": True, # 不重置APP
  33. "printPageSourceOnFailure": True, # 找不到元素时,appium log 会完整记录当前页面的 pagesource
  34. "newCommandTimeout": 6000, # 初始等待时间
  35. "automationName": "UiAutomator2" # 使用引擎,默认为 Appium,
  36. # 其中 Appium、UiAutomator2、Selendroid、Espresso 用于 Android,XCUITest 用于 iOS
  37. }
  38. driver = webdriver.Remote("http://localhost:4723/wd/hub", caps)
  39. driver.implicitly_wait(10)
  40. Common.logger(log_type).info('点击发现TAB')
  41. driver.find_elements(By.ID, 'com.tencent.mm:id/f2s')[2].click()
  42. Common.logger(log_type).info('点击视频号\n')
  43. driver.find_elements(By.ID, 'com.tencent.mm:id/gv6')[1].click()
  44. time.sleep(5)
  45. cls.get_feeds(log_type, driver, env)
  46. Common.logger(log_type).info('休眠 3s')
  47. time.sleep(3)
  48. cls.quit(log_type, driver)
  49. except Exception as e:
  50. Common.logger(log_type).error('start_wechat异常\n', e)
  51. # 退出 APP
  52. @classmethod
  53. def quit(cls, log_type, driver: WebDriver):
  54. driver.quit()
  55. Common.logger(log_type).info('退出 APP 成功\n')
  56. # 下载规则
  57. @staticmethod
  58. def download_rule(duration, like_cnt, share_cnt, favorite_cnt, comment_cnt):
  59. if int(duration) >= 30:
  60. if int(like_cnt) >= 1000:
  61. if int(share_cnt) >= 0:
  62. if int(favorite_cnt) >= 0:
  63. if int(comment_cnt) >= 0:
  64. return True
  65. else:
  66. return False
  67. else:
  68. return False
  69. else:
  70. return False
  71. else:
  72. return False
  73. else:
  74. return False
  75. # 操作安卓手机,自己滑动首页视频,并获取视频信息
  76. @classmethod
  77. def get_feeds(cls, log_type, driver: WebDriver, env):
  78. try:
  79. driver.implicitly_wait(10)
  80. for i in range(5):
  81. # 视频标题
  82. try:
  83. title_id = driver.find_element(By.ID, 'com.tencent.mm:id/ki5')
  84. video_title = title_id.get_attribute('name').split('\n')[0].replace('#', '').strip()
  85. except NoSuchElementException:
  86. video_title = ''
  87. driver.swipe(10, 1600, 10, 300, 200)
  88. # 点击播放器,获取视频时长
  89. # Common.logger(log_type).info('暂停播放')
  90. pause_btn = driver.find_element(By.ID, 'com.tencent.mm:id/eh4')
  91. pause_btn.click()
  92. start_time = driver.find_element(By.ID, 'com.tencent.mm:id/l59').get_attribute('name')
  93. start_time = int(start_time.split(':')[0])*60 + int(start_time.split(':')[-1])
  94. try:
  95. end_time = driver.find_element(By.ID, 'com.tencent.mm:id/l7i').get_attribute('name')
  96. except NoSuchElementException:
  97. end_time = driver.find_element(By.ID, 'com.tencent.mm:id/g73').get_attribute('name')
  98. end_time = int(end_time.split(':')[0]) * 60 + int(end_time.split(':')[-1])
  99. duration = start_time + end_time
  100. # 点赞
  101. like_id = driver.find_element(By.ID, 'com.tencent.mm:id/k04')
  102. like_cnt = like_id.get_attribute('name')
  103. if like_cnt == "" or like_cnt == "喜欢":
  104. like_cnt = 0
  105. elif '万' in like_cnt:
  106. like_cnt = float(like_cnt.split('万')[0]) * 10000
  107. elif '万+' in like_cnt:
  108. like_cnt = float(like_cnt.split('万+')[0]) * 10000
  109. else:
  110. like_cnt = float(like_cnt)
  111. # 分享
  112. share_id = driver.find_element(By.ID, 'com.tencent.mm:id/jhv')
  113. share_cnt = share_id.get_attribute('name')
  114. if share_cnt == "" or share_cnt == "转发":
  115. share_cnt = 0
  116. elif '万' in share_cnt:
  117. share_cnt = float(share_cnt.split('万')[0]) * 10000
  118. elif '万+' in share_cnt:
  119. share_cnt = float(share_cnt.split('万+')[0]) * 10000
  120. else:
  121. share_cnt = float(share_cnt)
  122. # 收藏
  123. favorite_id = driver.find_element(By.ID, 'com.tencent.mm:id/fnp')
  124. favorite_cnt = favorite_id.get_attribute('name')
  125. if favorite_cnt == "" or favorite_cnt == "收藏":
  126. favorite_cnt = 0
  127. elif '万' in favorite_cnt:
  128. favorite_cnt = float(favorite_cnt.split('万')[0]) * 10000
  129. elif '万+' in favorite_cnt:
  130. favorite_cnt = float(favorite_cnt.split('万+')[0]) * 10000
  131. else:
  132. favorite_cnt = float(favorite_cnt)
  133. # 评论
  134. comment_id = driver.find_element(By.ID, 'com.tencent.mm:id/bje')
  135. comment_cnt = comment_id.get_attribute('name')
  136. if comment_cnt == "" or comment_cnt == "评论":
  137. comment_cnt = 0
  138. elif '万' in comment_cnt:
  139. comment_cnt = float(comment_cnt.split('万')[0]) * 10000
  140. elif '万+' in comment_cnt:
  141. comment_cnt = float(comment_cnt.split('万+')[0]) * 10000
  142. else:
  143. comment_cnt = float(comment_cnt)
  144. # 用户名
  145. username_id = driver.find_element(By.ID, 'com.tencent.mm:id/hft')
  146. user_name = username_id.get_attribute('name')
  147. Common.logger(log_type).info('video_title:{}', video_title)
  148. Common.logger(log_type).info('duration:{}', duration)
  149. Common.logger(log_type).info('like_cnt:{}', like_cnt)
  150. Common.logger(log_type).info('share_cnt:{}', share_cnt)
  151. Common.logger(log_type).info('favorite_cnt:{}', favorite_cnt)
  152. Common.logger(log_type).info('comment_cnt:{}', comment_cnt)
  153. Common.logger(log_type).info('user_name:{}', user_name)
  154. # 判断无效视频
  155. if video_title == '' or user_name == '':
  156. Common.logger(log_type).info('无效视频,滑动到下一个视频\n')
  157. driver.swipe(10, 1600, 10, 300, 200)
  158. # 判断下载规则
  159. elif cls.download_rule(duration, like_cnt, share_cnt, favorite_cnt, comment_cnt) is False:
  160. Common.logger(log_type).info('不满足抓取规则,滑动到下一个视频\n')
  161. driver.swipe(10, 1600, 10, 300, 200)
  162. # 已下载表去重
  163. elif str(video_title) in [x for y in Feishu.get_values_batch(log_type, 'shipinhao', 'c77cf9') for x in y]:
  164. Common.logger(log_type).info('视频已下载,滑动到下一个视频\n')
  165. driver.swipe(10, 1600, 10, 300, 200)
  166. # feeds 表去重
  167. elif str(video_title) in [x for y in Feishu.get_values_batch(log_type, 'shipinhao', 'FSDlBy') for x in y]:
  168. Common.logger(log_type).info('视频已存在,滑动到下一个视频\n')
  169. driver.swipe(10, 1600, 10, 300, 200)
  170. # 分享给 windows 爬虫机
  171. else:
  172. share_id.click()
  173. driver.find_element(By.XPATH, '//*[@text="转发给朋友"]').click()
  174. driver.find_element(By.XPATH, '//*[@text="爬虫群"]').click()
  175. driver.find_element(By.ID, 'com.tencent.mm:id/guw').click()
  176. # 把视频信息写入飞书feeds文档
  177. Feishu.insert_columns(log_type, 'shipinhao', 'FSDlBy', 'ROWS', 1, 2)
  178. get_feeds_time = int(time.time())
  179. values = [[time.strftime('%Y/%m/%d %H:%M:%S', time.localtime(get_feeds_time)),
  180. '推荐榜',
  181. str(video_title),
  182. duration,
  183. like_cnt,
  184. share_cnt,
  185. favorite_cnt,
  186. comment_cnt,
  187. str(user_name)]]
  188. time.sleep(1)
  189. Feishu.update_values(log_type, 'shipinhao', 'FSDlBy', 'A2:Z2', values)
  190. Common.logger(log_type).info('视频信息写入飞书文档成功\n')
  191. while True:
  192. if Feishu.get_values_batch(log_type, 'shipinhao', 'FSDlBy')[1][11] is None:
  193. Common.logger(log_type).info('等待更新 URL 信息')
  194. time.sleep(10)
  195. else:
  196. Common.logger(log_type).info('URL 信息已更新,滑动到下一个视频\n')
  197. driver.swipe(10, 1600, 10, 300, 200)
  198. break
  199. # # 下载该视频
  200. # if len(cls.download_cnt) >= 100:
  201. # Feishu.dimension_range(log_type, "shipinhao", "FSDlBy", "ROWS", 2, 2)
  202. # return
  203. # else:
  204. # cls.download_publish(log_type, env)
  205. cls.download_publish(log_type, env)
  206. except Exception as e:
  207. Common.logger(log_type).error('get_feeds异常,滑动到下一个视频\n', e)
  208. Feishu.dimension_range(log_type, "shipinhao", "FSDlBy", "ROWS", 2, 2)
  209. driver.swipe(10, 1600, 10, 300, 200)
  210. # 下载 、上传
  211. @classmethod
  212. def download_publish(cls, log_type, env):
  213. try:
  214. recommend_feeds_sheet = Feishu.get_values_batch(log_type, 'shipinhao', 'FSDlBy')
  215. for i in range(1, len(recommend_feeds_sheet)):
  216. download_title = recommend_feeds_sheet[i][2].strip().replace('"', '') \
  217. .replace('“', '').replace('“', '…').replace("\n", "") \
  218. .replace("/", "").replace("\r", "").replace("#", "") \
  219. .replace(".", "。").replace("\\", "").replace("&NBSP", "") \
  220. .replace(":", "").replace("*", "").replace("?", "") \
  221. .replace("?", "").replace('"', "").replace("<", "") \
  222. .replace(">", "").replace("|", "").replace(" ", "")
  223. download_duration = recommend_feeds_sheet[i][3]
  224. download_like_cnt = recommend_feeds_sheet[i][4]
  225. download_share_cnt = recommend_feeds_sheet[i][5]
  226. download_favorite_cnt = recommend_feeds_sheet[i][6]
  227. download_comment_cnt = recommend_feeds_sheet[i][7]
  228. download_username = recommend_feeds_sheet[i][8]
  229. download_head_url = recommend_feeds_sheet[i][9]
  230. download_cover_url = recommend_feeds_sheet[i][10]
  231. download_video_url = recommend_feeds_sheet[i][11]
  232. Common.logger(log_type).info("download_title:{}", download_title)
  233. Common.logger(log_type).info("download_username:{}", download_username)
  234. Common.logger(log_type).info("download_video_url:{}", download_video_url)
  235. if download_title is None or download_duration is None or download_video_url is None:
  236. Feishu.dimension_range(log_type, 'shipinhao', 'FSDlBy', 'ROWS', i+1, i+1)
  237. Common.logger(log_type).info('空行,删除成功\n')
  238. return
  239. elif str(download_title) in [x for y in Feishu.get_values_batch(log_type, 'shipinhao', 'c77cf9') for x in y]:
  240. Feishu.dimension_range(log_type, 'shipinhao', 'FSDlBy', 'ROWS', i + 1, i + 1)
  241. Common.logger(log_type).info('视频已下载,删除成功\n')
  242. return
  243. else:
  244. # 下载封面
  245. Common.download_method(log_type=log_type, text="cover",
  246. d_name=str(download_title), d_url=str(download_cover_url))
  247. # 下载视频
  248. Common.download_method(log_type=log_type, text="video",
  249. d_name=str(download_title), d_url=str(download_video_url))
  250. # 保存视频信息至 "./videos/{download_video_title}/info.txt"
  251. with open("./videos/" + download_title
  252. + "/" + "info.txt", "a", encoding="UTF-8") as f_a:
  253. f_a.write('shipinhao' + str(int(time.time())) + "\n" +
  254. str(download_title) + "\n" +
  255. str(download_duration) + "\n" +
  256. str(download_favorite_cnt) + "\n" +
  257. str(download_comment_cnt) + "\n" +
  258. str(download_like_cnt) + "\n" +
  259. str(download_share_cnt) + "\n" +
  260. str(1920*1080) + "\n" +
  261. str(int(time.time())) + "\n" +
  262. str(download_username) + "\n" +
  263. str(download_head_url) + "\n" +
  264. str(download_video_url) + "\n" +
  265. str(download_cover_url) + "\n" +
  266. "shipinhao")
  267. Common.logger(log_type).info("==========视频信息已保存至info.txt==========")
  268. Common.logger(log_type).info("开始上传视频:{}".format(download_title))
  269. our_video_id = Publish.upload_and_publish(log_type, env, "play")
  270. if env == 'dev':
  271. our_video_link = "https://testadmin.piaoquantv.com/cms/post-detail/" + str(our_video_id) + "/info"
  272. else:
  273. our_video_link = "https://admin.piaoquantv.com/cms/post-detail/" + str(our_video_id) + "/info"
  274. Common.logger(log_type).info("视频上传完成:{}", our_video_link)
  275. # 视频ID工作表,插入首行
  276. Feishu.insert_columns(log_type, "shipinhao", "c77cf9", "ROWS", 1, 2)
  277. # 视频ID工作表,首行写入数据
  278. upload_time = int(time.time())
  279. values = [[time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(upload_time)),
  280. "推荐榜",
  281. str(download_title),
  282. our_video_link,
  283. download_duration,
  284. download_like_cnt,
  285. download_share_cnt,
  286. download_favorite_cnt,
  287. download_comment_cnt,
  288. download_username,
  289. str(download_head_url),
  290. str(download_cover_url),
  291. str(download_video_url)]]
  292. time.sleep(1)
  293. Feishu.update_values(log_type, "shipinhao", "c77cf9", "F2:V2", values)
  294. cls.download_cnt.append(download_title)
  295. # 删除行或列,可选 ROWS、COLUMNS
  296. time.sleep(1)
  297. Feishu.dimension_range(log_type, "shipinhao", "FSDlBy", "ROWS", i + 1, i + 1)
  298. Common.logger(log_type).info("下载/上传成功:{}\n", download_title)
  299. return
  300. except Exception as e:
  301. Feishu.dimension_range(log_type, "shipinhao", "FSDlBy", "ROWS", 2, 2)
  302. Common.logger(log_type).error('download_publish异常,删除视频信息成功:{}\n', e)
  303. if __name__ == '__main__':
  304. Publish.upload_and_publish('recommend', 'dev', "play")
  305. pass