首页 > 解决方案 > 使用 Selenium Java 在本机应用程序中处理广告

问题描述

我正在自动化 Android 原生游戏应用程序,我们的应用程序呈现来自不同广告网络的广告。提交每个游戏后,您可能会看到静态广告和视频广告,或者您可能根本看不到广告。如果找到视频广告,它可能会在 30 秒到 1 分钟之间变化。重要的是,当我使用 Appium 检查器监视各种视频广告屏幕时,只能由 Class(android.webkit.WebView, android.widget.VideoView, android.widget.Button, android.view.View, android.widget.Image & android.widget.ImageView.)。广告播放完毕后,我们需要点击设备返回按钮并进行下一场比赛。您能建议任何使此类应用程序自动化的好方法吗?非常感谢任何示例代码。

标签: javaseleniumappiumappium-iosappium-android

解决方案


选项 I:您必须要求您的开发人员创建一个没有广告的应用程序版本。

优点 - 没有广告。

缺点 - 您将不会测试与您计划发布的完全相同的代码。

您只能禁用全屏广告。

我认为没有最好的方法来做到这一点。稳定的自动检查或检查与您计划发布的完全相同的代码。

选项二:是捕捉广告是否可见,然后按返回按钮。

例如(Android 示例):

protected boolean checkAdvert(AppiumDriver<WebElement> driver, int timeout) {
    By adTree = By.xpath("//hierarchy/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]");
    Map<String, Object> adParams = new HashMap<>();
    //trying to wait for the ad to come up and then click the Expense button
    driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
    driver.context("NATIVE_APP");           
    FluentWait<WebDriver> await = new FluentWait<WebDriver> (driver)
            .withTimeout(timeout, TimeUnit.SECONDS)
            .pollingEvery(500, TimeUnit.MILLISECONDS)
            .ignoring(NoSuchElementException.class);
    try {
        await.until (ExpectedConditions.visibilityOf(driver.findElement(adTree)));
        // go BACK to eliminate the popup
        adParams.clear();
        adParams.put("keySequence", "BACK");
        driver.executeScript("mobile:presskey", adParams);
        System.out.println("Press the back button to get out of ad");
        return true;
    } catch (Exception t) {
        System.out.println("no ad showed up");
        return false;
    }
}

并在页面对象类中使用它:

public void addExp(String desc, String amount) {
    do {
        try  {
            driver.context("WEBVIEW");
            driver.findElement(expDesc).sendKeys(desc);
            driver.findElement(expAmnt).sendKeys(amount);
            adClick = false;
        } catch (NoSuchElementException ne) {
            adClick = checkAdvert(driver, 1);
            if (!adClick) throw ne;
        }
    } while (adClick);
}

但你必须记住,广告可能会有所不同,你可以尝试找到一个通用的选择器。但我认为很难涵盖所有情况。

adTree = By.xpath("//hierarchy/android.widget.FrameLayout[1]/android.widget.LinearLayout[1]/android.widget.FrameLayout[1]/android.widget.RelativeLayout[1]");

推荐阅读