代码如下:
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.service.local.AppiumDriverLocalService;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
public class Main {
private String xpath = "";
private AndroidDriver driver;
private static Logger logger = LoggerFactory.getLogger(Main.class);
private AppiumDriverLocalService service = AppiumDriverLocalService.buildDefaultService();
@BeforeClass
public void setUp() throws MalformedURLException {
service.start();
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
capabilities.setCapability(CapabilityType.VERSION, "4.4.4");
capabilities.setCapability("deviceName", "192.168.57.101:5555");
capabilities.setCapability("appPackage", "com.jane.businessevents");
capabilities.setCapability("appActivity", "jane.util.MainActivity");
capabilities.setCapability("noReset", "true");
capabilities.setCapability("unicodeKeyboard", true);
capabilities.setCapability("resetKeyboard", true);
driver = new AndroidDriver(new URL("http://localhost:4723/wd/hub"), capabilities);
}
@Test
public void testElement() throws DocumentException {
String content = driver.getPageSource();
try {
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new ByteArrayInputStream(content.getBytes("utf-8")));
Element rootElement = document.getRootElement();
findElement(rootElement, "text", "android.widget.Button", "sms(不带自动回复)");
logger.info("xpath = " + xpath);
if (null != xpath) {
driver.findElement(By.xpath(xpath)).click();
}
} catch (IOException e) {
e.printStackTrace();
}
}
@AfterClass
public void tearDown() {
driver.quit();
service.stop();
}
private void findElement(Element element, String attr, String qName, String value) {
List elements = element.elements();
for (Object element1 : elements) {
if (element1 instanceof Element) {
if (null != ((Element) element1).attributeValue(attr)) {
if (((Element) element1).getQName().getName().equals(qName)
&& ((Element) element1).attributeValue(attr).equalsIgnoreCase(value)) {
logger.info("path = " + ((Element) element1).getUniquePath());
xpath = ((Element) element1).getUniquePath();
} else {
findElement((Element) element1, attr, qName, value);
}
}
}
}
}
}
原本是想,拿到一个属性,可以自动生成xpath,但是考虑可能当前存在多个xpath,还是需要属性组合:
因为总是遇到同一个页面,同一套xpath,但是莫名其妙就会出现元素认不到的情况,所以想能不能自动生成xpath。。诶