使用Appium+pytest简单实现抖音浏览、点赞和评论

import pytest
import time
from appium import webdriver
from appium.options.android import UiAutomator2Options
from appium.webdriver.common.appiumby import AppiumBy
from appium.webdriver.common.touch_action import TouchAction
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


@pytest.fixture(scope="function")
def driver():
    options = UiAutomator2Options()
    options.set_capability("platformName", "Android")
    options.set_capability("platformVersion", "13")
    options.set_capability("deviceName", "******")  # 填你的设备ID
    options.set_capability("appPackage", "com.ss.android.ugc.aweme")
    options.set_capability("appActivity", ".splash.SplashActivity")
    options.set_capability("noReset", True)
    options.set_capability("disableHiddenApiPolicyError", True)
    options.set_capability("unicodeKeyboard", True)
    options.set_capability("resetKeyboard", True)
    driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", options=options)
    yield driver
    driver.quit()


# 向下滑动视频
def slide_down(driver):
    # 模拟滑动几个视频
    # 初始化 TouchAction
    touch_action = TouchAction(driver)

    # 获取屏幕尺寸
    screen_size = driver.get_window_size()
    width = screen_size['width']
    height = screen_size['height']

    # 设置滑动起点和终点(从下往上滑)
    start_x = width // 2
    start_y = height * 3 // 4
    end_x = width // 2
    end_y = height // 4

    # 模拟滑动浏览视频
    touch_action.press(x=start_x, y=start_y).wait(ms=300).move_to(x=end_x, y=end_y).release().perform()


# 点赞
def thumbs_up(driver):
    # 定位点赞按钮点击
    # 等待按钮可点击,最多等待 5 秒
    element = WebDriverWait(driver, 5).until(
        EC.element_to_be_clickable((AppiumBy.ID, "com.ss.android.ugc.aweme:id/f2k"))
    )
    element.click()


# 评论
def comment(driver, text):
    # 等待按钮可点击,最多等待 5 秒
    element = WebDriverWait(driver, 5).until(
        EC.element_to_be_clickable((AppiumBy.ID, "com.ss.android.ugc.aweme:id/d_4"))
    )
    element.click()
    # 输入评论
    driver.find_element(AppiumBy.ID, "com.ss.android.ugc.aweme:id/d4q").click()
    driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().text("善语结善缘,恶言伤人心")').send_keys(text)
    # 点击发送
    driver.find_element(AppiumBy.ANDROID_UIAUTOMATOR, 'new UiSelector().text("发送")').click()


# 测试抖音
def test_douyin(driver):
    driver.implicitly_wait(10)
    slide_down(driver)
    thumbs_up(driver)
    comment(driver, "hahaha")
    time.sleep(10)
posted @ 2025-04-18 17:23  KFCVme50w  阅读(129)  评论(0)    收藏  举报