无法使用appium java在chrome中定位元素

时间:2018-04-30 08:08:55

标签: java appium

我正在学习appium并尝试在appium java中执行基本的Google搜索操作。我写的代码是:

package com.MavenTest;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.Test;

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;

public class StartChrome {

    @Test
    public void test1() throws MalformedURLException, InterruptedException {

        DesiredCapabilities caps = new DesiredCapabilities();
        caps.setCapability("deviceName", "My Phone");
        caps.setCapability("udid", "790dc03c"); // Give Device ID of your mobile phone
        caps.setCapability("platformName", "Android");
        caps.setCapability("platformVersion", "5.1.1");
        caps.setCapability("browserName", "Chrome");
        caps.setCapability("noReset", true);

        // Create object of AndroidDriver class and pass the url and capability that we

        // System.setProperty("webdriver.chrome.driver",
        // "D:\\workspace\\AppiumTest\\driver\\chromedriver.exe");

        AppiumDriver<MobileElement> driver = null;
        try {
            driver = new AndroidDriver<MobileElement>(new URL("http://0.0.0.0:4723/wd/hub"), caps);

        } catch (MalformedURLException e) {
            System.out.println(e.getMessage());
        }

        // Open URL in Chrome Browser
        driver.get("http://www.google.com");

        System.out.println("Title " + driver.getTitle());

        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.name("Search")));

        driver.findElementByName("q").sendKeys("google");
        Thread.sleep(2000);
        driver.findElementByName("Gogle Search").click();
        driver.quit();

    }

}

我在尝试发送密码时遇到的错误是:

  

java.lang.ClassCastException:   org.openqa.selenium.remote.RemoteWebElement无法强制转换为   io.appium.java_client.MobileElement

2 个答案:

答案 0 :(得分:0)

MobileElement派生自RemoteWebElement。

如果您编写如下代码:

driver.findElementByName("q").sendKeys("google");

您正在尝试将RemoteWebElement强制转换为其子类之一MobileElement。

java.lang.ClassCastException如果您直接访问如下方法,则会出现问题:

driver.findElementByName("q").sendKeys("google");

WorkAround:您必须像以下一样投射到MobileElement:

MobileElement find = (MobileElement) driver.findElementByName("q").sendKeys("google");

答案 1 :(得分:0)

我遇到了同样的问题,升级Appium Client库可以解决此问题。

<!-- https://mvnrepository.com/artifact/io.appium/java-client -->

<dependency>
    <groupId>io.appium</groupId>
    <artifactId>java-client</artifactId>
    <version>5.0.4</version>
</dependency>