shipinhao_follow.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2022/12/14
  4. import os
  5. import sys
  6. import time
  7. from appium import webdriver
  8. from appium.webdriver.extensions.android.nativekey import AndroidKey
  9. from selenium.common import NoSuchElementException
  10. from appium.webdriver.webdriver import WebDriver
  11. from selenium.webdriver.common.by import By
  12. sys.path.append(os.getcwd())
  13. from main.common import Common
  14. from main.feishu_lib import Feishu
  15. from shipinhao.shipinhao_publish import Publish
  16. class Follow:
  17. # 过滤词库
  18. @classmethod
  19. def filter_words(cls, log_type):
  20. try:
  21. filter_words_sheet = Feishu.get_values_batch(log_type, 'shipinhao', 'gmeOgJ')
  22. filter_words_list = []
  23. for x in filter_words_sheet:
  24. for y in x:
  25. if y is None:
  26. pass
  27. else:
  28. filter_words_list.append(y)
  29. return filter_words_list
  30. except Exception as e:
  31. Common.logger(log_type).error('filter_words异常:{}\n', e)
  32. @classmethod
  33. def get_users_from_feishu(cls, log_type):
  34. try:
  35. users_sheet = Feishu.get_values_batch(log_type, 'shipinhao', 'yVFqxa')
  36. user_list = []
  37. for i in range(1, len(users_sheet)):
  38. user_name = users_sheet[i][1]
  39. if user_name is not None:
  40. user_list.append(user_name)
  41. return user_list
  42. except Exception as e:
  43. Common.logger(log_type).error(f'get_users_from_feishu异常:{e}\n')
  44. @classmethod
  45. def start_follow_wechat(cls, log_type, user_name, env):
  46. # try:
  47. Common.logger(log_type).info('启动微信')
  48. caps = {
  49. "platformName": "Android", # 手机操作系统 Android / iOS
  50. "deviceName": "Android", # 连接的设备名(模拟器或真机),安卓可以随便写
  51. "platforVersion": "11", # 手机对应的系统版本(Android 11)
  52. "appPackage": "com.tencent.mm", # 被测APP的包名,乐活圈 Android
  53. "appActivity": ".ui.LauncherUI", # 启动的Activity名
  54. "autoGrantPermissions": "true", # 让 appium 自动授权 base 权限,
  55. # 如果 noReset 为 True,则该条不生效(该参数为 Android 独有),对应的值为 True 或 False
  56. "unicodekeyboard": True, # 使用自带输入法,输入中文时填True
  57. "resetkeyboard": True, # 执行完程序恢复原来输入法
  58. "noReset": True, # 不重置APP
  59. "printPageSourceOnFailure": True, # 找不到元素时,appium log 会完整记录当前页面的 pagesource
  60. "newCommandTimeout": 6000, # 初始等待时间
  61. "automationName": "UiAutomator2", # 使用引擎,默认为 Appium,
  62. # 其中 Appium、UiAutomator2、Selendroid、Espresso 用于 Android,XCUITest 用于 iOS
  63. "showChromedriverLog": True,
  64. # "chromeOptions": {"androidProcess": "com.tencent.mm:appbrand0"},
  65. "chromeOptions": {"androidProcess": "com.tencent.mm:tools"},
  66. 'enableWebviewDetailsCollection': True,
  67. 'setWebContentsDebuggingEnabled': True,
  68. 'chromedriverExecutable': '/Users/wangkun/Downloads/chromedriver_v86/chromedriver',
  69. # 'chromedriverExecutable': '/Users/lieyunye/Downloads/chromedriver_v86/chromedriver',
  70. }
  71. driver = webdriver.Remote("http://localhost:4723/wd/hub", caps)
  72. driver.implicitly_wait(10)
  73. cls.search_to_user_homepage(log_type, user_name, driver)
  74. cls.search_user_videos(log_type, driver, env)
  75. Common.logger(log_type).info('休眠 3s')
  76. time.sleep(3)
  77. cls.quit(log_type, driver)
  78. # except Exception as e:
  79. # Common.logger(log_type).error('start_follow_wechat异常:{}\n', e)
  80. @classmethod
  81. def quit(cls, log_type, driver: WebDriver):
  82. driver.quit()
  83. Common.logger(log_type).info('退出 APP 成功\n')
  84. @classmethod
  85. def search_element(cls, log_type, driver: WebDriver, element):
  86. try:
  87. windowHandles = driver.window_handles
  88. # 遍历所有的handles,找到当前页面所在的handle:如果pageSource有包含你想要的元素,就是所要找的handle
  89. # 小程序的页面来回切换也需要:遍历所有的handles,切换到元素所在的handle
  90. for handle in windowHandles:
  91. driver.switch_to.window(handle)
  92. time.sleep(3)
  93. if len(driver.find_elements(By.XPATH, element)) != 0:
  94. return driver.find_element(By.XPATH, element)
  95. else:
  96. pass
  97. except Exception as e:
  98. Common.logger(log_type).warning('search_element异常:{}\n', e)
  99. @classmethod
  100. def search_to_user_homepage(cls, log_type, user_name, driver: WebDriver):
  101. Common.logger(log_type).info('点击搜索按钮')
  102. driver.find_element(By.ID, 'com.tencent.mm:id/j5t').click()
  103. Common.logger(log_type).info(f'输入搜索词:{user_name}')
  104. driver.find_element(By.ID, 'com.tencent.mm:id/cd7').send_keys(user_name)
  105. driver.press_keycode(AndroidKey.ENTER)
  106. Common.logger(log_type).info('点击进入搜索结果页')
  107. driver.find_element(By.ID, 'com.tencent.mm:id/m94').click()
  108. Common.logger(log_type).info('切换到webview')
  109. webview = driver.contexts
  110. driver.switch_to.context(webview[1])
  111. time.sleep(3)
  112. Common.logger(log_type).info('点击"视频号"分类')
  113. cls.search_element(log_type, driver, '//div[@class="unit"]/*[2]').click()
  114. time.sleep(3)
  115. Common.logger(log_type).info(f'进入用户主页:{user_name}')
  116. user_element = cls.search_element(log_type, driver, '//div[@class="video-account__container search_item_inner"]')
  117. if user_element is None:
  118. Common.logger(log_type).info(f'未搜索到用户:{user_name}\n')
  119. return
  120. else:
  121. user_element.click()
  122. time.sleep(1)
  123. Common.logger(log_type).info(f'进入 {user_name} 主页成功\n')
  124. @classmethod
  125. def search_user_videos(cls, log_type, driver: WebDriver, env):
  126. Common.logger(log_type).info('切回NATIVE_APP')
  127. driver.switch_to.context('NATIVE_APP')
  128. # 判断置顶视频
  129. top_videos = driver.find_elements(By.ID, 'com.tencent.mm:id/i56')
  130. Common.logger(log_type).info(f'发现置顶视频{len(top_videos)}个\n')
  131. if len(top_videos) == 0:
  132. return
  133. else:
  134. for i in range(len(top_videos)):
  135. top_videos[i].click()
  136. cls.download_publish(log_type, driver, env)
  137. driver.press_keycode(AndroidKey.BACK)
  138. # 判断非置顶视频
  139. not_top_first_video = driver.find_elements(By.ID, 'com.tencent.mm:id/nmz')[len(top_videos)]
  140. not_top_first_video.click()
  141. while True:
  142. cls.download_publish(log_type, driver, env)
  143. driver.swipe(10, 1600, 10, 300, 200)
  144. if len(driver.find_elements(By.ID, 'com.tencent.mm:id/g2s')) > 0:
  145. Common.logger(log_type).info('到底啦 ~\n')
  146. return
  147. @classmethod
  148. def get_video_info(cls, log_type, driver: WebDriver):
  149. driver.implicitly_wait(10)
  150. # 视频标题
  151. try:
  152. title_id = driver.find_element(By.ID, 'com.tencent.mm:id/ki5')
  153. video_title = title_id.get_attribute('name').split('\n')[0].strip()
  154. except NoSuchElementException:
  155. video_title = ''
  156. # 点击播放器,获取视频时长
  157. # Common.logger(log_type).info('暂停播放')
  158. pause_btn = driver.find_element(By.ID, 'com.tencent.mm:id/eh4')
  159. pause_btn.click()
  160. start_time = driver.find_element(By.ID, 'com.tencent.mm:id/l59').get_attribute('name')
  161. start_time = int(start_time.split(':')[0]) * 60 + int(start_time.split(':')[-1])
  162. try:
  163. end_time = driver.find_element(By.ID, 'com.tencent.mm:id/l7i').get_attribute('name')
  164. except NoSuchElementException:
  165. end_time = driver.find_element(By.ID, 'com.tencent.mm:id/g73').get_attribute('name')
  166. end_time = int(end_time.split(':')[0]) * 60 + int(end_time.split(':')[-1])
  167. duration = start_time + end_time
  168. # 点赞
  169. like_id = driver.find_element(By.ID, 'com.tencent.mm:id/k04')
  170. like_cnt = like_id.get_attribute('name')
  171. if like_cnt == "" or like_cnt == "喜欢":
  172. like_cnt = 0
  173. elif '万' in like_cnt:
  174. like_cnt = float(like_cnt.split('万')[0]) * 10000
  175. elif '万+' in like_cnt:
  176. like_cnt = float(like_cnt.split('万+')[0]) * 10000
  177. else:
  178. like_cnt = float(like_cnt)
  179. # 分享
  180. share_id = driver.find_element(By.ID, 'com.tencent.mm:id/jhv')
  181. share_cnt = share_id.get_attribute('name')
  182. if share_cnt == "" or share_cnt == "转发":
  183. share_cnt = 0
  184. elif '万' in share_cnt:
  185. share_cnt = float(share_cnt.split('万')[0]) * 10000
  186. elif '万+' in share_cnt:
  187. share_cnt = float(share_cnt.split('万+')[0]) * 10000
  188. else:
  189. share_cnt = float(share_cnt)
  190. # 收藏
  191. favorite_id = driver.find_element(By.ID, 'com.tencent.mm:id/fnp')
  192. favorite_cnt = favorite_id.get_attribute('name')
  193. if favorite_cnt == "" or favorite_cnt == "收藏":
  194. favorite_cnt = 0
  195. elif '万' in favorite_cnt:
  196. favorite_cnt = float(favorite_cnt.split('万')[0]) * 10000
  197. elif '万+' in favorite_cnt:
  198. favorite_cnt = float(favorite_cnt.split('万+')[0]) * 10000
  199. else:
  200. favorite_cnt = float(favorite_cnt)
  201. # 评论
  202. comment_id = driver.find_element(By.ID, 'com.tencent.mm:id/bje')
  203. comment_cnt = comment_id.get_attribute('name')
  204. if comment_cnt == "" or comment_cnt == "评论":
  205. comment_cnt = 0
  206. elif '万' in comment_cnt:
  207. comment_cnt = float(comment_cnt.split('万')[0]) * 10000
  208. elif '万+' in comment_cnt:
  209. comment_cnt = float(comment_cnt.split('万+')[0]) * 10000
  210. else:
  211. comment_cnt = float(comment_cnt)
  212. # 用户名
  213. username_id = driver.find_element(By.ID, 'com.tencent.mm:id/hft')
  214. user_name = username_id.get_attribute('name')
  215. Common.logger(log_type).info('video_title:{}', video_title)
  216. Common.logger(log_type).info('duration:{}', duration)
  217. Common.logger(log_type).info('like_cnt:{}', like_cnt)
  218. Common.logger(log_type).info('share_cnt:{}', share_cnt)
  219. Common.logger(log_type).info('favorite_cnt:{}', favorite_cnt)
  220. Common.logger(log_type).info('comment_cnt:{}', comment_cnt)
  221. Common.logger(log_type).info('user_name:{}', user_name)
  222. video_dict = {
  223. 'video_title': video_title,
  224. 'duration': duration,
  225. 'like_cnt': like_cnt,
  226. 'share_cnt': share_cnt,
  227. 'share_id': share_id,
  228. 'favorite_cnt': favorite_cnt,
  229. 'comment_cnt': comment_cnt,
  230. 'user_name': user_name
  231. }
  232. return video_dict
  233. @classmethod
  234. def download_publish(cls, log_type, driver: WebDriver, env):
  235. video_dict = cls.get_video_info(log_type, driver)
  236. if int(video_dict['duration']) < 50:
  237. Common.logger(log_type).info(f'时长:{int(video_dict["duration"])} < 50 秒\n')
  238. elif video_dict['video_title'] == '':
  239. Common.logger(log_type).info('视频标题为空\n')
  240. # 过滤词库(视频标题)
  241. elif any(word if word in video_dict['video_title'] else False for word in cls.filter_words(log_type)) is True:
  242. Common.logger(log_type).info(f'视频已中过滤词:{video_dict["video_title"]}\n')
  243. # 视频号推荐_已下载表
  244. elif str(video_dict['video_title']) in [x for y in Feishu.get_values_batch(log_type, 'shipinhao', 'c77cf9') for x in y]:
  245. Common.logger(log_type).info('视频已下载\n')
  246. # 视频号定向_已下载表
  247. elif str(video_dict['video_title']) in [x for y in Feishu.get_values_batch(log_type, 'shipinhao', 'XxmRlE') for x in y]:
  248. Common.logger(log_type).info('视频已下载\n')
  249. # feeds 表去重
  250. elif str(video_dict['video_title']) in [x for y in Feishu.get_values_batch(log_type, 'shipinhao', 'FSDlBy') for x in y]:
  251. Common.logger(log_type).info('视频已存在\n')
  252. # feeds 表去重
  253. elif str(video_dict['video_title']) in [x for y in Feishu.get_values_batch(log_type, 'shipinhao', 'qzDljJ') for x in y]:
  254. Common.logger(log_type).info('视频已存在\n')
  255. # 分享给 windows 爬虫机
  256. else:
  257. video_dict['share_id'].click()
  258. driver.find_element(By.XPATH, '//*[@text="转发给朋友"]').click()
  259. driver.find_element(By.XPATH, '//*[@text="爬虫群"]').click()
  260. driver.find_element(By.ID, 'com.tencent.mm:id/guw').click()
  261. # 把视频信息写入飞书feeds文档
  262. Feishu.insert_columns(log_type, 'shipinhao', 'qzDljJ', 'ROWS', 1, 2)
  263. get_feeds_time = int(time.time())
  264. values = [[time.strftime('%Y/%m/%d %H:%M:%S', time.localtime(get_feeds_time)),
  265. '定向榜',
  266. str(video_dict['video_title']),
  267. int(video_dict['duration']),
  268. int(video_dict['like_cnt']),
  269. int(video_dict['share_cnt']),
  270. int(video_dict['favorite_cnt']),
  271. int(video_dict['comment_cnt']),
  272. str(video_dict['user_name'])]]
  273. time.sleep(1)
  274. Feishu.update_values(log_type, 'shipinhao', 'qzDljJ', 'A2:Z2', values)
  275. Common.logger(log_type).info('视频信息写入飞书文档成功\n')
  276. while True:
  277. if Feishu.get_values_batch(log_type, 'shipinhao', 'qzDljJ')[1][11] is None:
  278. Common.logger(log_type).info('等待更新 URL 信息')
  279. time.sleep(10)
  280. else:
  281. Common.logger(log_type).info('URL 信息已更新\n')
  282. break
  283. cls.publish(log_type, env)
  284. # 下载 、上传
  285. @classmethod
  286. def publish(cls, log_type, env):
  287. try:
  288. follow_feeds_sheet = Feishu.get_values_batch(log_type, 'shipinhao', 'qzDljJ')
  289. for i in range(1, len(follow_feeds_sheet)):
  290. download_title = follow_feeds_sheet[i][2].strip().replace('"', '') \
  291. .replace('“', '').replace('“', '…').replace("\n", "") \
  292. .replace("/", "").replace("\r", "") \
  293. .replace(".", "。").replace("\\", "").replace("&NBSP", "") \
  294. .replace(":", "").replace("*", "").replace("?", "") \
  295. .replace("?", "").replace('"', "").replace("<", "") \
  296. .replace(">", "").replace("|", "").replace(" ", "")
  297. download_duration = follow_feeds_sheet[i][3]
  298. download_like_cnt = follow_feeds_sheet[i][4]
  299. download_share_cnt = follow_feeds_sheet[i][5]
  300. download_favorite_cnt = follow_feeds_sheet[i][6]
  301. download_comment_cnt = follow_feeds_sheet[i][7]
  302. download_username = follow_feeds_sheet[i][8]
  303. download_head_url = follow_feeds_sheet[i][9]
  304. download_cover_url = follow_feeds_sheet[i][10]
  305. download_video_url = follow_feeds_sheet[i][11]
  306. Common.logger(log_type).info("download_title:{}", download_title)
  307. Common.logger(log_type).info("download_username:{}", download_username)
  308. Common.logger(log_type).info("download_video_url:{}", download_video_url)
  309. if download_title is None or download_duration is None or download_video_url is None:
  310. Feishu.dimension_range(log_type, 'shipinhao', 'qzDljJ', 'ROWS', i + 1, i + 1)
  311. Common.logger(log_type).info('空行,删除成功\n')
  312. return
  313. else:
  314. # 下载封面
  315. Common.download_method(log_type=log_type, text="cover",
  316. d_name=str(download_title), d_url=str(download_cover_url))
  317. # 下载视频
  318. Common.download_method(log_type=log_type, text="video",
  319. d_name=str(download_title), d_url=str(download_video_url))
  320. # 保存视频信息至 "./videos/{download_video_title}/info.txt"
  321. with open("./videos/" + download_title
  322. + "/" + "info.txt", "a", encoding="UTF-8") as f_a:
  323. f_a.write('shipinhao' + str(int(time.time())) + "\n" +
  324. str(download_title) + "\n" +
  325. str(download_duration) + "\n" +
  326. str(download_favorite_cnt) + "\n" +
  327. str(download_comment_cnt) + "\n" +
  328. str(download_like_cnt) + "\n" +
  329. str(download_share_cnt) + "\n" +
  330. str(1920 * 1080) + "\n" +
  331. str(int(time.time())) + "\n" +
  332. str(download_username) + "\n" +
  333. str(download_head_url) + "\n" +
  334. str(download_video_url) + "\n" +
  335. str(download_cover_url) + "\n" +
  336. "SHIPINHAO" + str(int(time.time())))
  337. Common.logger(log_type).info("==========视频信息已保存至info.txt==========")
  338. Common.logger(log_type).info("开始上传视频:{}".format(download_title))
  339. our_video_id = Publish.upload_and_publish(log_type, env, "follow")
  340. if env == 'dev':
  341. our_video_link = "https://testadmin.piaoquantv.com/cms/post-detail/" + str(
  342. our_video_id) + "/info"
  343. else:
  344. our_video_link = "https://admin.piaoquantv.com/cms/post-detail/" + str(
  345. our_video_id) + "/info"
  346. Common.logger(log_type).info("视频上传完成:{}", our_video_link)
  347. # 视频ID工作表,插入首行
  348. Feishu.insert_columns(log_type, "shipinhao", "XxmRlE", "ROWS", 1, 2)
  349. # 视频ID工作表,首行写入数据
  350. upload_time = int(time.time())
  351. values = [[time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(upload_time)),
  352. "定向榜",
  353. str(download_title),
  354. our_video_link,
  355. download_duration,
  356. download_like_cnt,
  357. download_share_cnt,
  358. download_favorite_cnt,
  359. download_comment_cnt,
  360. download_username,
  361. str(download_head_url),
  362. str(download_cover_url),
  363. str(download_video_url)]]
  364. time.sleep(1)
  365. Feishu.update_values(log_type, "shipinhao", "XxmRlE", "F2:V2", values)
  366. # 删除行或列,可选 ROWS、COLUMNS
  367. time.sleep(1)
  368. Feishu.dimension_range(log_type, "shipinhao", "qzDljJ", "ROWS", i + 1, i + 1)
  369. Common.logger(log_type).info("下载/上传成功\n")
  370. return
  371. except Exception as e:
  372. Feishu.dimension_range(log_type, "shipinhao", "qzDljJ", "ROWS", 2, 2)
  373. Common.logger(log_type).error('download_publish异常,删除视频信息成功:{}\n', e)
  374. @classmethod
  375. def search_to_all_user_homepage(cls, log_type, env):
  376. user_list = cls.get_users_from_feishu(log_type)
  377. for user in user_list:
  378. cls.start_follow_wechat(log_type, user, env)
  379. Common.logger(log_type).info('所有用户已抓取完毕\n')
  380. if __name__ == '__main__':
  381. # print(Follow.get_users_from_feishu('follow'))
  382. # print(len(Follow.get_users_from_feishu('follow')))
  383. print(Follow.filter_words('follow'))
  384. # Follow.search_to_all_user_homepage('follow')
  385. pass