zhongmiaoyinxin_recommend.py 21 KB

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