zhongmiaoyinxin_recommend.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/4/17
  4. import json
  5. import os
  6. import shutil
  7. import sys
  8. import time
  9. from hashlib import md5
  10. from appium import webdriver
  11. from appium.webdriver.common.touch_action import TouchAction
  12. from appium.webdriver.extensions.android.nativekey import AndroidKey
  13. from appium.webdriver.webdriver import WebDriver
  14. from selenium.common import NoSuchElementException
  15. from selenium.webdriver.common.by import By
  16. sys.path.append(os.getcwd())
  17. from common.common import Common
  18. from common.publish import Publish
  19. from common.feishu import Feishu
  20. from common.scheduling_db import MysqlHelper
  21. class ZhongmiaoyinxinRecommend:
  22. platform = "众妙音信"
  23. i = 0
  24. @classmethod
  25. def zhongmiaoyinxin_config(cls, log_type, crawler, text, env):
  26. select_sql = f"""select * from crawler_config where source="zhongmiaoyinxin" """
  27. contents = MysqlHelper.get_values(log_type, crawler, select_sql, env, action='')
  28. title_list = []
  29. filter_list = []
  30. for content in contents:
  31. config = content['config']
  32. config_dict = eval(config)
  33. for k, v in config_dict.items():
  34. if k == "title":
  35. title_list_config = v.split(",")
  36. for title in title_list_config:
  37. title_list.append(title)
  38. if k == "filter":
  39. filter_list_config = v.split(",")
  40. for filter_word in filter_list_config:
  41. filter_list.append(filter_word)
  42. if text == "title":
  43. return title_list
  44. elif text == "filter":
  45. return filter_list
  46. @classmethod
  47. def start_wechat(cls, log_type, crawler, env):
  48. # try:
  49. if env == "dev":
  50. chromedriverExecutable = "/Users/wangkun/Downloads/chromedriver/chromedriver_v107/chromedriver"
  51. else:
  52. chromedriverExecutable = '/Users/piaoquan/Downloads/chromedriver'
  53. Common.logger(log_type, crawler).info('启动微信')
  54. caps = {
  55. "platformName": "Android", # 手机操作系统 Android / iOS
  56. "deviceName": "a0a65126", # 连接的设备名(模拟器或真机),安卓可以随便写
  57. "platforVersion": "11", # 手机对应的系统版本(Android 11)
  58. "appPackage": "com.tencent.mm", # 被测APP的包名,乐活圈 Android
  59. "appActivity": ".ui.LauncherUI", # 启动的Activity名
  60. "autoGrantPermissions": "true", # 让 appium 自动授权 base 权限,
  61. # 如果 noReset 为 True,则该条不生效(该参数为 Android 独有),对应的值为 True 或 False
  62. "unicodekeyboard": True, # 使用自带输入法,输入中文时填True
  63. "resetkeyboard": True, # 执行完程序恢复原来输入法
  64. "noReset": True, # 不重置APP
  65. "printPageSourceOnFailure": True, # 找不到元素时,appium log 会完整记录当前页面的 pagesource
  66. "newCommandTimeout": 6000, # 初始等待时间
  67. "automationName": "UiAutomator2", # 使用引擎,默认为 Appium,
  68. # 其中 Appium、UiAutomator2、Selendroid、Espresso 用于 Android,XCUITest 用于 iOS
  69. "showChromedriverLog": True,
  70. 'enableWebviewDetailsCollection': True,
  71. 'setWebContentsDebuggingEnabled': True,
  72. 'recreateChromeDriverSessions': True,
  73. 'chromedriverExecutable': chromedriverExecutable,
  74. "chromeOptions": {"androidProcess": "com.tencent.mm:appbrand0"},
  75. # "chromeOptions": {"androidProcess": "com.tencent.mm:tools"},
  76. 'browserName': ''
  77. }
  78. driver = webdriver.Remote("http://localhost:4723/wd/hub", caps)
  79. driver.implicitly_wait(20)
  80. # 向下滑动页面,展示出小程序选择面板
  81. for i in range(120):
  82. try:
  83. # 发现微信消息 TAB,代表微信已启动成功
  84. if driver.find_elements(By.ID, 'com.tencent.mm:id/f2s'):
  85. break
  86. # 发现并关闭系统菜单栏
  87. elif driver.find_element(By.ID, 'com.android.systemui:id/dismiss_view'):
  88. Common.logger(log_type, crawler).info('发现并关闭系统下拉菜单栏')
  89. driver.find_element(By.ID, 'com.android.systemui:id/dismiss_view').click()
  90. else:
  91. pass
  92. except NoSuchElementException:
  93. time.sleep(1)
  94. Common.logger(log_type, crawler).info('下滑,展示小程序选择面板')
  95. size = driver.get_window_size()
  96. driver.swipe(int(size['width'] * 0.5), int(size['height'] * 0.2),
  97. int(size['width'] * 0.5), int(size['height'] * 0.8), 200)
  98. # 打开小程序"众妙之上"
  99. time.sleep(5)
  100. Common.logger(log_type, crawler).info('打开小程序"西瓜说说"')
  101. driver.find_elements(By.XPATH, '//*[@text="西瓜说说"]')[-1].click()
  102. time.sleep(5)
  103. cls.get_videoList(log_type, crawler, driver, env)
  104. cls.quit(log_type, crawler, driver)
  105. # except Exception as e:
  106. # Common.logger(log_type, crawler).error('start_wechat异常:{}\n', e)
  107. @classmethod
  108. def quit(cls, log_type, crawler, driver: WebDriver):
  109. driver.quit()
  110. Common.logger(log_type, crawler).info('退出 APP 成功\n')
  111. @classmethod
  112. def check_to_applet(cls, log_type, crawler, driver: WebDriver):
  113. while True:
  114. webview = driver.contexts
  115. Common.logger(log_type, crawler).info(f"webview:{webview}")
  116. driver.switch_to.context(webview[1])
  117. windowHandles = driver.window_handles
  118. for handle in windowHandles:
  119. driver.switch_to.window(handle)
  120. time.sleep(1)
  121. try:
  122. video_list = driver.find_element(By.XPATH, '//*[@class="index--navbar-list"]/*[1]')
  123. video_list.click()
  124. Common.logger(log_type, crawler).info('切换到小程序视频列表成功\n')
  125. return
  126. except NoSuchElementException:
  127. time.sleep(1)
  128. Common.logger(log_type, crawler).info("切换到小程序失败\n")
  129. break
  130. # 查找元素
  131. @classmethod
  132. def search_elements(cls, driver: WebDriver, xpath):
  133. time.sleep(1)
  134. windowHandles = driver.window_handles
  135. for handle in windowHandles:
  136. driver.switch_to.window(handle)
  137. time.sleep(1)
  138. try:
  139. elements = driver.find_elements(By.XPATH, xpath)
  140. if elements:
  141. # cls.find_ad(log_type, crawler, driver)
  142. return elements
  143. except NoSuchElementException:
  144. pass
  145. @classmethod
  146. def repeat_out_video_id(cls, log_type, crawler, out_video_id, env):
  147. sql = f""" select * from crawler_video where platform="{cls.platform}" and out_video_id="{out_video_id}"; """
  148. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  149. return len(repeat_video)
  150. @classmethod
  151. def repeat_video_url(cls, log_type, crawler, video_url, env):
  152. sql = f""" select * from crawler_video where platform="{cls.platform}" and video_url="{video_url}"; """
  153. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  154. return len(repeat_video)
  155. @classmethod
  156. def find_ad(cls, log_type, crawler, driver: WebDriver):
  157. windowHandles = driver.window_handles
  158. for handle in windowHandles:
  159. driver.switch_to.window(handle)
  160. time.sleep(1)
  161. try:
  162. Common.logger(log_type, crawler).info("寻找广告~~~~~~")
  163. ad_element = driver.find_element(By.XPATH, '//div[@class="ad-text"]')
  164. if ad_element:
  165. Common.logger(log_type, crawler).info("发现广告")
  166. for i in range(20):
  167. if driver.find_element(By.XPATH, '//div[@id="count_down_container"]/*[1]').text == "已完成浏览":
  168. Common.logger(log_type, crawler).info("广告播放完毕,点击返回")
  169. driver.press_keycode(AndroidKey.BACK)
  170. return
  171. else:
  172. Common.logger(log_type, crawler).info("广告未播放完毕,等待 1 秒")
  173. time.sleep(1)
  174. else:
  175. Common.logger(log_type, crawler).info("未发现广告, 退出")
  176. return
  177. except NoSuchElementException:
  178. time.sleep(1)
  179. @classmethod
  180. def get_video_url(cls, log_type, crawler, driver: WebDriver, video_element):
  181. video_element.click()
  182. time.sleep(5)
  183. windowHandles = driver.window_handles
  184. for handle in windowHandles:
  185. driver.switch_to.window(handle)
  186. time.sleep(1)
  187. try:
  188. video_url_element = driver.find_element(By.XPATH, '//wx-video[@class="videoh"]')
  189. video_url = video_url_element.get_attribute("src")
  190. cls.find_ad(log_type, crawler, driver)
  191. return video_url
  192. except NoSuchElementException:
  193. time.sleep(1)
  194. @classmethod
  195. def get_videoList(cls, log_type, crawler, driver: WebDriver, env):
  196. # 鼠标左键点击, 1为x坐标, 2为y坐标
  197. Common.logger(log_type, crawler).info('关闭广告')
  198. size = driver.get_window_size()
  199. TouchAction(driver).tap(x=int(size['width'] * 0.5), y=int(size['height'] * 0.1)).perform()
  200. # 切换到小程序
  201. cls.check_to_applet(log_type, crawler, driver)
  202. time.sleep(5)
  203. index = 0
  204. while True:
  205. try:
  206. if cls.search_elements(driver, '//*[@id="scrollContainer"]') is None:
  207. Common.logger(log_type, crawler).info('窗口已销毁\n')
  208. return
  209. Common.logger(log_type, crawler).info('获取视频列表\n')
  210. video_elements = cls.search_elements(driver, '//wx-view[@class="cover"]')
  211. if video_elements is None:
  212. Common.logger(log_type, crawler).warning(f'video_elements:{video_elements}')
  213. return
  214. video_element_temp = video_elements[index:]
  215. if len(video_element_temp) == 0:
  216. Common.logger(log_type, crawler).info('到底啦~~~~~~~~~~~~~\n')
  217. return
  218. for i, video_element in enumerate(video_element_temp):
  219. if video_element is None:
  220. Common.logger(log_type, crawler).info('到底啦~\n')
  221. return
  222. cls.i += 1
  223. cls.search_elements(driver, '//wx-view[@class="cover"]')
  224. Common.logger(log_type, crawler).info(f'拖动"视频"列表第{cls.i}个至屏幕中间')
  225. time.sleep(3)
  226. driver.execute_script("arguments[0].scrollIntoView({block:'center',inline:'center'})",
  227. video_element)
  228. # video_title = video_element.find_elements(By.XPATH, '//wx-view[@class="playImgs"]')[cls.i-1].text
  229. # cover_url = video_element.find_elements(By.XPATH, '//wx-image[@class="coverImg"]')[cls.i-1].get_attribute('src')
  230. # play_cnt = video_element.find_elements(By.XPATH, '//wx-image[@class="coverImg"]/span/*[2]')[cls.i-1].text
  231. video_title = video_element.find_elements(By.XPATH, '//wx-view[@class="playImgs"]')[index+i].text
  232. cover_url = video_element.find_elements(By.XPATH, '//wx-image[@class="coverImg"]')[index+i].get_attribute('src')
  233. play_cnt = video_element.find_elements(By.XPATH, '//wx-image[@class="coverImg"]/span/*[2]')[index+i].text
  234. if "万" in play_cnt:
  235. play_cnt = int(play_cnt.split("万")[0]) * 10000
  236. out_video_id = md5(video_title.encode('utf8')).hexdigest()
  237. video_dict = {
  238. 'video_title': video_title,
  239. 'video_id': out_video_id,
  240. 'play_cnt': play_cnt,
  241. 'comment_cnt': 0,
  242. 'like_cnt': 0,
  243. 'share_cnt': 0,
  244. 'publish_time_stamp': int(time.time()),
  245. 'publish_time_str': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()))),
  246. 'user_name': "zhongmiaoyinxin",
  247. 'user_id': "zhongmiaoyinxin",
  248. 'avatar_url': cover_url,
  249. 'cover_url': cover_url,
  250. 'session': f"zhongmiaoyinxin-{int(time.time())}"
  251. }
  252. for k, v in video_dict.items():
  253. Common.logger(log_type, crawler).info(f"{k}:{v}")
  254. if video_title is None or cover_url is None:
  255. Common.logger(log_type, crawler).info("无效视频\n")
  256. elif any(str(word) if str(word) in video_title else False for word in
  257. cls.zhongmiaoyinxin_config(log_type, crawler, "filter", env)) is True:
  258. Common.logger(log_type, crawler).info('已中过滤词\n')
  259. elif cls.repeat_out_video_id(log_type, crawler, out_video_id, env) != 0:
  260. Common.logger(log_type, crawler).info('视频已下载\n')
  261. else:
  262. video_url = cls.get_video_url(log_type, crawler, driver, video_element)
  263. if video_url is None:
  264. Common.logger(log_type, crawler).info("未获取到视频播放地址\n")
  265. driver.press_keycode(AndroidKey.BACK)
  266. elif cls.repeat_video_url(log_type, crawler, video_url, env) != 0:
  267. Common.logger(log_type, crawler).info('视频已下载\n')
  268. driver.press_keycode(AndroidKey.BACK)
  269. else:
  270. video_dict["video_url"] = video_url
  271. Common.logger(log_type, crawler).info(f"video_url:{video_url}\n")
  272. # driver.press_keycode(AndroidKey.BACK)
  273. cls.download_publish(log_type, crawler, video_dict, env, driver)
  274. Common.logger(log_type, crawler).info('已抓取完一组视频,休眠10秒\n')
  275. time.sleep(10)
  276. index = index + len(video_element_temp)
  277. except Exception as e:
  278. Common.logger(log_type, crawler).info(f"get_videoList:{e}\n")
  279. cls.i = 0
  280. @classmethod
  281. def download_publish(cls, log_type, crawler, video_dict, env, driver: WebDriver):
  282. # try:
  283. # 下载视频
  284. Common.download_method(log_type=log_type, crawler=crawler, text='video', title=video_dict['video_title'],
  285. url=video_dict['video_url'])
  286. ffmpeg_dict = Common.ffmpeg(log_type, crawler, f"./{crawler}/videos/{video_dict['video_title']}/video.mp4")
  287. if ffmpeg_dict is None:
  288. md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
  289. shutil.rmtree(f"./{crawler}/videos/{md_title}/")
  290. Common.logger(log_type, crawler).info("视频size=0,删除成功\n")
  291. return
  292. video_dict["duration"] = ffmpeg_dict["duration"]
  293. video_dict["video_width"] = ffmpeg_dict["width"]
  294. video_dict["video_height"] = ffmpeg_dict["height"]
  295. # 下载封面
  296. Common.download_method(log_type=log_type, crawler=crawler, text='cover', title=video_dict['video_title'],
  297. url=video_dict['cover_url'])
  298. # 保存视频信息至txt
  299. Common.save_video_info(log_type=log_type, crawler=crawler, video_dict=video_dict)
  300. # 上传视频
  301. Common.logger(log_type, crawler).info("开始上传视频...")
  302. our_video_id = Publish.upload_and_publish(log_type=log_type,
  303. crawler=crawler,
  304. strategy="推荐榜爬虫策略",
  305. our_uid="recommend",
  306. env=env,
  307. oss_endpoint="out")
  308. if env == 'dev':
  309. our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  310. else:
  311. our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  312. Common.logger(log_type, crawler).info("视频上传完成")
  313. if our_video_id is None:
  314. # 删除视频文件夹
  315. shutil.rmtree(f"./{crawler}/videos/{video_dict['video_title']}")
  316. return
  317. # 视频信息保存至飞书
  318. Feishu.insert_columns(log_type, crawler, "19c772", "ROWS", 1, 2)
  319. # 视频ID工作表,首行写入数据
  320. upload_time = int(time.time())
  321. values = [[time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(upload_time)),
  322. "推荐榜爬虫策略",
  323. video_dict["video_title"],
  324. video_dict["video_id"],
  325. video_dict["play_cnt"],
  326. video_dict["duration"],
  327. f'{video_dict["video_width"]}*{video_dict["video_height"]}',
  328. our_video_link,
  329. video_dict["cover_url"],
  330. video_dict["video_url"]]]
  331. time.sleep(1)
  332. Feishu.update_values(log_type, crawler, "19c772", "F2:V2", values)
  333. Common.logger(log_type, crawler).info(f"视频已保存至飞书文档\n")
  334. rule_dict = {}
  335. # 视频信息保存数据库
  336. insert_sql = f""" insert into crawler_video(video_id,
  337. out_user_id,
  338. platform,
  339. strategy,
  340. out_video_id,
  341. video_title,
  342. cover_url,
  343. video_url,
  344. duration,
  345. publish_time,
  346. play_cnt,
  347. crawler_rule,
  348. width,
  349. height)
  350. values({our_video_id},
  351. "{video_dict['user_id']}",
  352. "{cls.platform}",
  353. "推荐榜爬虫策略",
  354. "{video_dict['video_id']}",
  355. "{video_dict['video_title']}",
  356. "{video_dict['cover_url']}",
  357. "{video_dict['video_url']}",
  358. {int(video_dict['duration'])},
  359. "{video_dict['publish_time_str']}",
  360. {int(video_dict['play_cnt'])},
  361. '{json.dumps(rule_dict)}',
  362. {int(video_dict['video_width'])},
  363. {int(video_dict['video_height'])}) """
  364. Common.logger(log_type, crawler).info(f"insert_sql:{insert_sql}")
  365. MysqlHelper.update_values(log_type, crawler, insert_sql, env, action='')
  366. Common.logger(log_type, crawler).info('视频信息插入数据库成功!\n')
  367. driver.press_keycode(AndroidKey.BACK)
  368. # except Exception as e:
  369. # Common.logger(log_type, crawler).error(f'download_publish异常:{e}\n')
  370. if __name__ == '__main__':
  371. # print(ZhongmiaoyinxinRecommend.zhongmiaoyinxin_config('recommend', 'zhongmiaoyinxin', "filter", "dev"))
  372. ZhongmiaoyinxinRecommend.start_wechat("recommend", "zhongmiaoyinxin", "dev")
  373. pass