jixiangxingfu_recommend.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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 uuid
  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 import AliyunLogger, PiaoQuanPipeline
  19. from common.feishu import Feishu
  20. from common.common import Common
  21. from common.publish import Publish
  22. from common.scheduling_db import MysqlHelper
  23. class JixiangxingfuRecommend:
  24. platform = "吉祥幸福"
  25. i = 0
  26. @classmethod
  27. def jixiangxingfu_config(cls, log_type, crawler, text, env):
  28. select_sql = f"""select * from crawler_config where source="jixiangxingfu" """
  29. contents = MysqlHelper.get_values(log_type, crawler, select_sql, env, action='')
  30. title_list = []
  31. filter_list = []
  32. for content in contents:
  33. config = content['config']
  34. config_dict = eval(config)
  35. for k, v in config_dict.items():
  36. if k == "title":
  37. title_list_config = v.split(",")
  38. for title in title_list_config:
  39. title_list.append(title)
  40. if k == "filter":
  41. filter_list_config = v.split(",")
  42. for filter_word in filter_list_config:
  43. filter_list.append(filter_word)
  44. if text == "title":
  45. return title_list
  46. elif text == "filter":
  47. return filter_list
  48. @classmethod
  49. def start_wechat(cls, log_type, crawler, env):
  50. try:
  51. if env == "dev":
  52. chromedriverExecutable = "/Users/piaoquan/Downloads/chromedriver"
  53. else:
  54. chromedriverExecutable = "/Users/piaoquan/Downloads/chromedriver"
  55. Common.logger(log_type, crawler).info("启动微信")
  56. # Common.logging(self.log_type, self.crawler, self.env, '启动微信')
  57. # 微信的配置文件
  58. caps = {
  59. "platformName": "Android",
  60. "devicesName": "Android",
  61. # "platformVersion": "11",
  62. # "udid": "emulator-5554",
  63. "appPackage": "com.tencent.mm",
  64. "appActivity": ".ui.LauncherUI",
  65. "autoGrantPermissions": "true",
  66. "noReset": True,
  67. "resetkeyboard": True,
  68. "unicodekeyboard": True,
  69. "showChromedriverLog": True,
  70. "printPageSourceOnFailure": True,
  71. "recreateChromeDriverSessions": True,
  72. "enableWebviewDetailsCollection": True,
  73. "setWebContentsDebuggingEnabled": True,
  74. "newCommandTimeout": 6000,
  75. "automationName": "UiAutomator2",
  76. "chromedriverExecutable": chromedriverExecutable,
  77. "chromeOptions": {"androidProcess": "com.tencent.mm:appbrand0"},
  78. }
  79. try:
  80. driver = webdriver.Remote("http://localhost:4723/wd/hub", caps)
  81. except:
  82. AliyunLogger.logging(
  83. code="3002",
  84. platform=JixiangxingfuRecommend.platform,
  85. mode=log_type,
  86. env=env,
  87. message="appium 启动异常"
  88. )
  89. return \
  90. driver.implicitly_wait(30)
  91. # 向下滑动页面,展示出小程序选择面板
  92. for i in range(120):
  93. try:
  94. # 发现微信消息 TAB,代表微信已启动成功
  95. if driver.find_elements(By.ID, 'com.tencent.mm:id/f2s'):
  96. AliyunLogger.logging(
  97. code="1000",
  98. platform=JixiangxingfuRecommend.platform,
  99. mode=log_type,
  100. env=env,
  101. message="微信启动成功"
  102. )
  103. break
  104. # 发现并关闭系统菜单栏
  105. elif driver.find_element(By.ID, 'com.android.systemui:id/dismiss_view'):
  106. Common.logger(log_type, crawler).info('发现并关闭系统下拉菜单栏')
  107. AliyunLogger.logging(
  108. code="1000",
  109. platform=JixiangxingfuRecommend.platform,
  110. mode=log_type,
  111. env=env,
  112. message="发现并关闭系统下拉菜单栏"
  113. )
  114. size = driver.get_window_size()
  115. driver.swipe(int(size['width'] * 0.5), int(size['height'] * 0.8),
  116. int(size['width'] * 0.5), int(size['height'] * 0.2), 100)
  117. # driver.find_element(By.ID, 'com.android.systemui:id/dismiss_view').click()
  118. else:
  119. pass
  120. except NoSuchElementException:
  121. time.sleep(1)
  122. Common.logger(log_type, crawler).info('下滑,展示小程序选择面板')
  123. AliyunLogger.logging(
  124. code="1000",
  125. platform=JixiangxingfuRecommend.platform,
  126. mode=log_type,
  127. env=env,
  128. message="下滑,展示小程序选择面板"
  129. )
  130. size = driver.get_window_size()
  131. driver.swipe(int(size['width'] * 0.5), int(size['height'] * 0.2), int(size['width'] * 0.5),
  132. int(size['height'] * 0.8), 100)
  133. # 打开小程序"祝福大家好才是真好"
  134. time.sleep(5)
  135. Common.logger(log_type, crawler).info('打开小程序"祝福每天好运来相伴"')
  136. driver.find_elements(By.XPATH, '//*[@text="祝福大家发财幸福噢"]')[-1].click()
  137. AliyunLogger.logging(
  138. code="1000",
  139. platform=JixiangxingfuRecommend.platform,
  140. mode=log_type,
  141. env=env,
  142. message='打开小程序"祝福每天好运来相伴"成功'
  143. )
  144. # 获取视频信息
  145. time.sleep(10)
  146. # time.sleep(60)
  147. cls.get_videoList(log_type, crawler, driver, env)
  148. # 退出微信
  149. cls.quit(log_type, crawler, driver)
  150. except Exception as e:
  151. Common.logger(log_type, crawler).error('start_wechat异常:{}\n', e)
  152. # 退出 APP
  153. @classmethod
  154. def quit(cls, log_type, crawler, driver: WebDriver):
  155. driver.quit()
  156. Common.logger(log_type, crawler).info('退出APP成功\n')
  157. @classmethod
  158. def check_to_applet(cls, log_type, crawler, driver: WebDriver):
  159. while True:
  160. webview = driver.contexts
  161. driver.switch_to.context(webview[1])
  162. windowHandles = driver.window_handles
  163. for handle in windowHandles:
  164. driver.switch_to.window(handle)
  165. time.sleep(1)
  166. try:
  167. # video_list = driver.find_element(By.XPATH, '//wx-view[text()="视频"]')
  168. driver.find_element(By.XPATH, '//wx-view[text()="为您精选"]')
  169. # video_list.click()
  170. # time.sleep(2)
  171. # # if len(cls.search_elements(driver, '//*[@class="customNavigationBar--titleBack2"]')) != 0:
  172. # # Common.logger(log_type, crawler).info("直接进入了视频详情,返回视频列表")
  173. # # cls.search_elements(driver, '//*[@class="customNavigationBar--titleBack2"]')[0].click()
  174. Common.logger(log_type, crawler).info('切换到小程序视频列表成功\n')
  175. return
  176. except NoSuchElementException:
  177. time.sleep(1)
  178. Common.logger(log_type, crawler).info("切换到小程序失败\n")
  179. break
  180. # 查找元素
  181. @classmethod
  182. def search_elements(cls,driver: WebDriver, xpath):
  183. windowHandles = driver.window_handles
  184. for handle in windowHandles:
  185. driver.switch_to.window(handle)
  186. time.sleep(1)
  187. try:
  188. elements = driver.find_elements(By.XPATH, xpath)
  189. if elements:
  190. return elements
  191. except NoSuchElementException:
  192. pass
  193. @classmethod
  194. def repeat_out_video_id(cls, log_type, crawler, out_video_id, env):
  195. sql = f""" select * from crawler_video where platform in ("众妙音信", "刚刚都传", "吉祥幸福", "知青天天看", "zhufuquanzi", "祝福圈子", "haitunzhufu", "海豚祝福") and out_video_id="{out_video_id}"; """
  196. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  197. return len(repeat_video)
  198. @classmethod
  199. def repeat_video_url(cls, log_type, crawler, video_url, env):
  200. sql = f""" select * from crawler_video where platform="{cls.platform}" and video_url="{video_url}"; """
  201. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  202. return len(repeat_video)
  203. @classmethod
  204. def find_ad(cls, log_type, crawler, driver: WebDriver):
  205. windowHandles = driver.window_handles
  206. # Common.logger(log_type, crawler).info('windowHandles:{}', windowHandles)
  207. # 遍历所有的handles,找到当前页面所在的handle:如果pageSource有包含你想要的元素,就是所要找的handle
  208. # 小程序的页面来回切换也需要:遍历所有的handles,切换到元素所在的handle
  209. for handle in windowHandles:
  210. driver.switch_to.window(handle)
  211. time.sleep(1)
  212. try:
  213. Common.logger(log_type, crawler).info("寻找广告~~~~~~")
  214. ad_element = driver.find_element(By.XPATH, '//div[@class="ad-text"]')
  215. if ad_element:
  216. Common.logger(log_type, crawler).info("发现广告")
  217. for i in range(20):
  218. if driver.find_element(By.XPATH, '//div[@id="count_down_container"]/*[1]').text == "已完成浏览":
  219. Common.logger(log_type, crawler).info("广告播放完毕,点击返回")
  220. driver.press_keycode(AndroidKey.BACK)
  221. return
  222. else:
  223. Common.logger(log_type, crawler).info("广告未播放完毕,等待 1 秒")
  224. time.sleep(1)
  225. else:
  226. Common.logger(log_type, crawler).info("未发现广告, 退出")
  227. return
  228. except NoSuchElementException:
  229. time.sleep(1)
  230. @classmethod
  231. def get_video_url(cls, log_type, crawler, driver: WebDriver, video_element):
  232. video_element.click()
  233. time.sleep(5)
  234. windowHandles = driver.window_handles
  235. for handle in windowHandles:
  236. driver.switch_to.window(handle)
  237. time.sleep(1)
  238. try:
  239. video_url_element = driver.find_element(By.XPATH, '//wx-video[@class="main-video-container"]')
  240. video_url = video_url_element.get_attribute("src")
  241. cls.find_ad(log_type, crawler, driver)
  242. return video_url
  243. except NoSuchElementException:
  244. time.sleep(1)
  245. @classmethod
  246. def get_videoList(cls, log_type, crawler, driver, env):
  247. driver.implicitly_wait(20)
  248. driver.press_keycode(AndroidKey.BACK)
  249. # 切换到小程序
  250. cls.check_to_applet(log_type, crawler, driver)
  251. time.sleep(5)
  252. index = 0
  253. while True:
  254. try:
  255. if cls.search_elements(driver, '//wx-view[@class="list-container"]') is None:
  256. Common.logger(log_type, crawler).info('窗口已销毁\n')
  257. AliyunLogger.logging(
  258. code="3000",
  259. platform=JixiangxingfuRecommend.platform,
  260. mode=log_type,
  261. env=env,
  262. message='窗口已销毁'
  263. )
  264. return
  265. Common.logger(log_type, crawler).info('获取视频列表\n')
  266. AliyunLogger.logging(
  267. code="1000",
  268. platform=JixiangxingfuRecommend.platform,
  269. mode=log_type,
  270. env=env,
  271. message='获取视频列表'
  272. )
  273. video_elements = cls.search_elements(driver, '//wx-view[@class="listCardVideo--video-title"]')
  274. if video_elements is None:
  275. Common.logger(log_type, crawler).warning(f'video_elements:{video_elements}')
  276. AliyunLogger.logging(
  277. code="2000",
  278. platform=JixiangxingfuRecommend.platform,
  279. mode=log_type,
  280. env=env,
  281. message=f'video_elements:{video_elements}'
  282. )
  283. return
  284. video_element_temp = video_elements[index:]
  285. if len(video_element_temp) == 0:
  286. AliyunLogger.logging(
  287. code="2000",
  288. platform=JixiangxingfuRecommend.platform,
  289. mode=log_type,
  290. env=env,
  291. message='到底啦~~~~~~~~~~~~~\n'
  292. )
  293. Common.logger(log_type, crawler).info('到底啦~~~~~~~~~~~~~\n')
  294. return
  295. for i, video_element in enumerate(video_element_temp):
  296. if video_element is None:
  297. Common.logger(log_type, crawler).info('到底啦~\n')
  298. AliyunLogger.logging(
  299. code="2000",
  300. platform=JixiangxingfuRecommend.platform,
  301. mode=log_type,
  302. env=env,
  303. message='到底啦~~~~~~~~~~~~~\n'
  304. )
  305. return
  306. cls.i += 1
  307. cls.search_elements(driver, '//wx-view[@class="listCardVideo--video-title"]')
  308. Common.logger(log_type, crawler).info(f'拖动"视频"列表第{cls.i}个至屏幕中间')
  309. AliyunLogger.logging(
  310. code="1000",
  311. platform=JixiangxingfuRecommend.platform,
  312. mode=log_type,
  313. env=env,
  314. message=f'拖动"视频"列表第{cls.i}个至屏幕中间'
  315. )
  316. time.sleep(3)
  317. driver.execute_script("arguments[0].scrollIntoView({block:'center',inline:'center'})", video_element)
  318. trace_id = crawler + str(uuid.uuid1())
  319. AliyunLogger.logging(
  320. code="1001",
  321. platform=JixiangxingfuRecommend.platform,
  322. mode=log_type,
  323. env=env,
  324. trace_id=trace_id,
  325. message="扫描到一条视频",
  326. )
  327. video_title = video_element.find_elements(By.XPATH, '//wx-view[@class="listCardVideo--video-title"]')[index+i].text
  328. cover_url = video_element.find_elements(By.XPATH, '//wx-image[@class="listCardVideo--cover-img"]')[index+i].get_attribute('src')
  329. play_cnt = video_element.find_elements(By.XPATH, '//wx-view[@class="listCardVideo--play-num"]')[index+i].text
  330. if "万" in play_cnt:
  331. play_cnt = int(play_cnt.split("万")[0])*10000
  332. out_video_id = md5(video_title.encode('utf8')).hexdigest()
  333. video_dict = {
  334. 'video_title': video_title,
  335. 'video_id': out_video_id,
  336. 'out_video_id': out_video_id,
  337. 'play_cnt': play_cnt,
  338. 'comment_cnt': 0,
  339. 'like_cnt': 0,
  340. 'share_cnt': 0,
  341. 'publish_time_stamp': int(time.time()),
  342. 'publish_time_str': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()))),
  343. 'update_time_stamp': int(time.time()),
  344. 'user_name': "jixiangxingfu",
  345. 'user_id': "jixiangxingfu",
  346. 'avatar_url': cover_url,
  347. 'cover_url': cover_url,
  348. 'session': f"jixiangxingfu-{int(time.time())}"
  349. }
  350. rule_dict = {}
  351. pipeline = PiaoQuanPipeline(
  352. platform=JixiangxingfuRecommend.platform,
  353. mode=log_type,
  354. item=video_dict,
  355. rule_dict=rule_dict,
  356. env=env,
  357. trace_id=trace_id
  358. )
  359. flag = pipeline.process_item()
  360. if flag:
  361. video_url = cls.get_video_url(log_type, crawler, driver, video_element)
  362. if video_url is None:
  363. Common.logger(log_type, crawler).info("未获取到视频播放地址\n")
  364. AliyunLogger.logging(
  365. code="2000",
  366. platform=JixiangxingfuRecommend.platform,
  367. mode=log_type,
  368. env=env,
  369. message="未获取到视频播放地址"
  370. )
  371. driver.press_keycode(AndroidKey.BACK)
  372. elif cls.repeat_video_url(log_type, crawler, video_url, env) != 0:
  373. Common.logger(log_type, crawler).info('视频已下载\n')
  374. AliyunLogger.logging(
  375. code="2000",
  376. platform=JixiangxingfuRecommend.platform,
  377. mode=log_type,
  378. env=env,
  379. message="视频已下载"
  380. )
  381. driver.press_keycode(AndroidKey.BACK)
  382. else:
  383. video_dict["video_url"] = video_url
  384. Common.logger(log_type, crawler).info(f"video_url:{video_url}\n")
  385. # driver.press_keycode(AndroidKey.BACK)
  386. cls.download_publish(log_type, crawler, video_dict, env, driver)
  387. Common.logger(log_type, crawler).info('已抓取完一组视频,休眠10秒\n')
  388. AliyunLogger.logging(
  389. code="1000",
  390. platform=JixiangxingfuRecommend.platform,
  391. mode=log_type,
  392. env=env,
  393. message="已抓取完一组,休眠 5 秒\n"
  394. )
  395. time.sleep(10)
  396. index = index + len(video_element_temp)
  397. except Exception as e:
  398. AliyunLogger.logging(
  399. code="3001",
  400. platform=JixiangxingfuRecommend.platform,
  401. mode=log_type,
  402. env=env,
  403. message=f"get_videoList:{e}\n"
  404. )
  405. Common.logger(log_type, crawler).info(f"get_videoList:{e}\n")
  406. cls.i = 0
  407. return
  408. @classmethod
  409. def download_publish(cls, log_type, crawler, video_dict, env, driver: WebDriver):
  410. # 下载视频
  411. download_res = Common.download_method(log_type=log_type, crawler=crawler, text='video', title=video_dict['video_title'], url=video_dict['video_url'])
  412. if download_res is False:
  413. driver.press_keycode(AndroidKey.BACK)
  414. return
  415. ffmpeg_dict = Common.ffmpeg(log_type, crawler, f"./{crawler}/videos/{video_dict['video_title']}/video.mp4")
  416. if ffmpeg_dict is None:
  417. md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
  418. shutil.rmtree(f"./{crawler}/videos/{md_title}/")
  419. Common.logger(log_type, crawler).info("视频size=0,删除成功\n")
  420. return
  421. video_dict["duration"] = ffmpeg_dict["duration"]
  422. video_dict["video_width"] = ffmpeg_dict["width"]
  423. video_dict["video_height"] = ffmpeg_dict["height"]
  424. # 下载封面
  425. Common.download_method(log_type=log_type, crawler=crawler, text='cover', title=video_dict['video_title'],
  426. url=video_dict['cover_url'])
  427. # 保存视频信息至txt
  428. Common.save_video_info(log_type=log_type, crawler=crawler, video_dict=video_dict)
  429. # 上传视频
  430. Common.logger(log_type, crawler).info("开始上传视频...")
  431. our_video_id = Publish.upload_and_publish(log_type=log_type,
  432. crawler=crawler,
  433. strategy="推荐榜爬虫策略",
  434. our_uid="recommend",
  435. env=env,
  436. oss_endpoint="out")
  437. if env == 'dev':
  438. our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  439. else:
  440. our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  441. Common.logger(log_type, crawler).info("视频上传完成")
  442. if our_video_id is None:
  443. # 删除视频文件夹
  444. shutil.rmtree(f"./{crawler}/videos/{video_dict['video_title']}")
  445. return
  446. # 视频信息保存至飞书
  447. Feishu.insert_columns(log_type, crawler, "d9e9b1", "ROWS", 1, 2)
  448. # 视频ID工作表,首行写入数据
  449. upload_time = int(time.time())
  450. values = [[time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(upload_time)),
  451. "推荐榜爬虫策略",
  452. video_dict["video_title"],
  453. video_dict["video_id"],
  454. video_dict["play_cnt"],
  455. video_dict["duration"],
  456. f'{video_dict["video_width"]}*{video_dict["video_height"]}',
  457. our_video_link,
  458. video_dict["cover_url"],
  459. video_dict["video_url"]]]
  460. time.sleep(1)
  461. Feishu.update_values(log_type, crawler, "d9e9b1", "F2:V2", values)
  462. Common.logger(log_type, crawler).info(f"视频已保存至飞书文档\n")
  463. rule_dict = {}
  464. # 视频信息保存数据库
  465. insert_sql = f""" insert into crawler_video(video_id,
  466. out_user_id,
  467. platform,
  468. strategy,
  469. out_video_id,
  470. video_title,
  471. cover_url,
  472. video_url,
  473. duration,
  474. publish_time,
  475. play_cnt,
  476. crawler_rule,
  477. width,
  478. height)
  479. values({our_video_id},
  480. "{video_dict['user_id']}",
  481. "{cls.platform}",
  482. "推荐榜爬虫策略",
  483. "{video_dict['video_id']}",
  484. "{video_dict['video_title']}",
  485. "{video_dict['cover_url']}",
  486. "{video_dict['video_url']}",
  487. {int(video_dict['duration'])},
  488. "{video_dict['publish_time_str']}",
  489. {int(video_dict['play_cnt'])},
  490. '{json.dumps(rule_dict)}',
  491. {int(video_dict['video_width'])},
  492. {int(video_dict['video_height'])}) """
  493. Common.logger(log_type, crawler).info(f"insert_sql:{insert_sql}")
  494. MysqlHelper.update_values(log_type, crawler, insert_sql, env, action='')
  495. Common.logger(log_type, crawler).info('视频信息插入数据库成功!\n')
  496. driver.press_keycode(AndroidKey.BACK)
  497. if __name__ == "__main__":
  498. JixiangxingfuRecommend.start_wechat('recommend', 'jixiangxingfu', 'prod')
  499. pass