# -*- coding: utf-8 -*- # @Author: wangkun # @Time: 2022/12/22 import os import sys import time import ffmpeg from appium import webdriver from appium.webdriver.extensions.android.nativekey import AndroidKey from appium.webdriver.webdriver import WebDriver from selenium.common import NoSuchElementException from selenium.webdriver.common.by import By sys.path.append(os.getcwd()) from main.common import Common from main.feishu_lib import Feishu from main.kdjsfq_publish import Publish class Recommend: # recommend_feed 翻页参数 i = 0 @classmethod def get_video_info_from_local(cls, log_type, video_path): probe = ffmpeg.probe(video_path) video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None) if video_stream is None: Common.logger(log_type).info('No video Stream found!') return width = int(video_stream['width']) height = int(video_stream['height']) duration = int(float(video_stream['duration'])) return width, height, duration @classmethod def search_elements(cls, log_type, driver: WebDriver, element): try: windowHandles = driver.window_handles for handle in windowHandles: driver.switch_to.window(handle) time.sleep(1) if len(driver.find_elements(By.XPATH, element)) != 0: return driver.find_elements(By.XPATH, element) else: pass except Exception as e: Common.logger(log_type).error(f'search_element异常:{e}\n') @classmethod def start_wechat(cls, log_type, env): try: Common.logger(log_type).info('启动微信') caps = { "platformName": "Android", # 手机操作系统 Android / iOS "deviceName": "a0a65126", # 连接的设备名(模拟器或真机),安卓可以随便写 "platforVersion": "11", # 手机对应的系统版本(Android 11) "appPackage": "com.tencent.mm", # 被测APP的包名,乐活圈 Android "appActivity": ".ui.LauncherUI", # 启动的Activity名 "autoGrantPermissions": "true", # 让 appium 自动授权 base 权限, # 如果 noReset 为 True,则该条不生效(该参数为 Android 独有),对应的值为 True 或 False "unicodekeyboard": True, # 使用自带输入法,输入中文时填True "resetkeyboard": True, # 执行完程序恢复原来输入法 "noReset": True, # 不重置APP "printPageSourceOnFailure": True, # 找不到元素时,appium log 会完整记录当前页面的 pagesource "newCommandTimeout": 6000, # 初始等待时间 "automationName": "UiAutomator2", # 使用引擎,默认为 Appium, # 其中 Appium、UiAutomator2、Selendroid、Espresso 用于 Android,XCUITest 用于 iOS "showChromedriverLog": True, 'enableWebviewDetailsCollection': True, 'setWebContentsDebuggingEnabled': True, 'recreateChromeDriverSessions': True, # 'chromedriverExecutable': '/Users/wangkun/Downloads/chromedriver/chromedriver_v86/chromedriver', 'chromedriverExecutable': '/Users/lieyunye/Downloads/chromedriver_v86/chromedriver', "chromeOptions": {"androidProcess": "com.tencent.mm:appbrand0"}, 'browserName': '' } driver = webdriver.Remote("http://localhost:4723/wd/hub", caps) driver.implicitly_wait(20) # 向下滑动页面,展示出小程序选择面板 for i in range(120): try: # 发现微信消息 TAB,代表微信已启动成功 if driver.find_elements(By.ID, 'com.tencent.mm:id/f2s'): break # 发现并关闭系统菜单栏 elif driver.find_element(By.ID, 'com.android.systemui:id/dismiss_view'): Common.logger(log_type).info('发现并关闭系统下拉菜单栏') driver.find_element(By.ID, 'com.android.systemui:id/dismiss_view').click() else: pass except NoSuchElementException: time.sleep(1) Common.logger(log_type).info('下滑,展示小程序选择面板') size = driver.get_window_size() driver.swipe(int(size['width'] * 0.5), int(size['height'] * 0.2), int(size['width'] * 0.5), int(size['height'] * 0.8), 200) # 打开小程序"看到就是福气" time.sleep(3) Common.logger(log_type).info('打开小程序"看到就是福气"') driver.find_elements(By.XPATH, '//*[@text="看到就是福气"]')[-1].click() cls.get_recommend(log_type, driver, env) cls.quit(log_type, driver) except Exception as e: Common.logger(log_type).error(f'start_wechat异常:{e}\n') cmd = "cd ~ && source .bash_profile && adb kill-server && adb start-server" os.system(cmd) @classmethod def quit(cls, log_type, driver: WebDriver): driver.quit() Common.logger(log_type).info('退出微信成功\n') @classmethod def get_recommend(cls, log_type, driver: WebDriver, env): try: driver.implicitly_wait(15) Common.logger(log_type).info('切换到小程序\n') time.sleep(5) webviews = driver.contexts driver.switch_to.context(webviews[1]) time.sleep(1) cls.search_elements(log_type, driver, '//wx-view[contains(text(),"视频")]')[-1].click() time.sleep(1) index = 0 while True: if cls.search_elements(log_type, driver, '//body[@is="pages/max/max"]') is None: Common.logger(log_type).info('窗口已销毁\n') else: Common.logger(log_type).info('获取视频列表\n') video_elements = cls.search_elements(log_type, driver, '//wx-view[@class="spt-2"]') if video_elements is None or len(video_elements) == 0: Common.logger(log_type).info(f'video_elements:{video_elements}') return video_elements = video_elements[index:] if len(video_elements) == 0: Common.logger(log_type).info('到底啦~~~~~~~~~~~~~\n') return for video_element in video_elements: if video_element is None: Common.logger(log_type).info('到底啦~\n') return cls.i += 1 cls.search_elements(log_type, driver, '//wx-view[@class="spt-2"]') Common.logger(log_type).info('拖动"视频"列表第{}个至屏幕中间', cls.i) time.sleep(3) driver.execute_script( "arguments[0].scrollIntoView({block:'center',inline:'center'})", video_element) video_title = cls.search_elements(log_type, driver, '//wx-view[@class="bt"]')[cls.i-1].get_attribute('innerHTML') cover_url = cls.search_elements(log_type, driver, '//wx-image[@class="spt-img"]')[cls.i-1].get_attribute('src') Common.logger(log_type).info(f'video_title:{video_title}') Common.logger(log_type).info(f'cover_url:{cover_url}') cls.download_publish(log_type, driver, video_element, video_title, cover_url, env) time.sleep(3) Common.logger(log_type).info('已抓取完一组视频,休眠10秒\n') time.sleep(10) index = index + len(video_elements) except Exception as e: Common.logger(log_type).error(f'get_recommend异常,重启APP:{e}\n') cls.i = 0 cls.quit(log_type, driver) cls.start_wechat(log_type, env) @classmethod def get_video_url(cls, log_type, driver: WebDriver, video_element): try: time.sleep(1) # Common.logger(log_type).info('进入视频详情') video_element.click() time.sleep(3) video_url_element = cls.search_elements(log_type, driver, '//wx-video[@id="myVideo"]') if video_url_element is None or len(video_url_element) == 0: Common.logger(log_type).info('未获取到视频 URL') return 0 else: return video_url_element[0].get_attribute('src') except Exception as e: Common.logger(log_type).error(f'get_video_info异常:{e}\n') @classmethod def download_publish(cls, log_type, driver: WebDriver, video_element, video_title, cover_url, env): try: if video_title == 0 or cover_url == 0: Common.logger(log_type).info('无效视频\n') elif video_title in [x for y in Feishu.get_values_batch(log_type, 'kdjsfq', 'ad3b6d') for x in y]: Common.logger(log_type).info('视频已下载\n') else: video_url = cls.get_video_url(log_type, driver, video_element) if video_url == 0: Common.logger(log_type).info('video_url:未获取到\n') driver.press_keycode(AndroidKey.BACK) time.sleep(1) else: Common.logger(log_type).info(f'video_url:{video_url}') # 下载视频 Common.download_method(log_type, 'video', video_title, video_url) # # 获取视频时长 # video_info = cls.get_video_info_from_local(log_type, "./videos/" + video_title + "/video.mp4") # video_width = str(video_info[0]) # video_height = str(video_info[1]) # duration = video_info[2] # 下载封面 Common.download_method(log_type, 'cover', video_title, cover_url) # 保存视频信息至 "./videos/{download_video_title}/info.txt" with open("./videos/" + video_title + "/" + "info.txt", "a", encoding="UTF-8") as f_a: f_a.write("kdjsfq" + str(int(time.time())) + "\n" + str(video_title) + "\n" + # str(int(float(duration))) + "\n" + '100' + "\n" + '0' + "\n" + '0' + "\n" + '0' + "\n" + '0' + "\n" + # str(video_width) + '*' + str(video_height) + "\n" + '1920*1080' + "\n" + str(int(time.time())) + "\n" + '看到就是福气小程序' + "\n" + str(cover_url) + "\n" + str(video_url) + "\n" + str(cover_url) + "\n" + "kandaojiushifuqi" + str(int(time.time()))) Common.logger(log_type).info("==========视频信息已保存至info.txt==========") # 上传视频 Common.logger(log_type).info(f"开始上传视频:{video_title}") if env == 'dev': our_video_id = Publish.upload_and_publish(log_type, env, "play") our_video_link = "https://testadmin.piaoquantv.com/cms/post-detail/" + str(our_video_id) + "/info" else: our_video_id = Publish.upload_and_publish(log_type, env, "play") our_video_link = "https://admin.piaoquantv.com/cms/post-detail/" + str(our_video_id) + "/info" Common.logger(log_type).info(f"视频上传完成:{video_title}") # 保存视频 ID 到已下载表 Common.logger(log_type).info(f"保存视频至已下载表:{video_title}") # 视频ID工作表,插入首行 Feishu.insert_columns(log_type, "kdjsfq", "ad3b6d", "ROWS", 1, 2) # 视频ID工作表,首行写入数据 upload_time = int(time.time()) values = [[time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(upload_time)), "推荐榜", video_title, our_video_link, # int(duration), # str(video_width) + '*' + str(video_height), '', '', cover_url, video_url]] time.sleep(1) Feishu.update_values(log_type, "kdjsfq", "ad3b6d", "F2:V2", values) driver.press_keycode(AndroidKey.BACK) time.sleep(1) Common.logger(log_type).info(f"视频:{video_title},下载/上传成功\n") except Exception as e: Common.logger(log_type).error(f'download_publish异常:{e}\n') if __name__ == '__main__': Recommend.start_wechat('recommend', 'dev')