jixiangxingfu_recommend.py 22 KB

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