jixiangxingfu_recommend.py 26 KB

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