Selenium-java(XML-元素管理篇)
有效的對頁面元素管理有利于腳本的維護,避免修改代碼引起不必要的麻煩。這里我使用到了xml對元素的管理。
<?xml version="1.0" encoding="UTF-8"?>
<!--登錄頁面元素-->
<LoginEleData>
<!--賬號輸入框-->
<property name="name_input" type="id" value="textfield-1009-inputEl"/>
<!--密碼輸入框-->
<property name="pwd_input" type="id" value="textfield-1010-inputEl"/>
<!--保存密碼勾選框-->
<property name="save_pwd" type="id" value="checkbox-1013-inputEl"/>
<!--登錄按鈕-->
<property name="login_button" type="id" value="loginBtn-btnEl"/>
</LoginEleData>
這是一個舉例的xml文件,我把各個元素信息寫入其中。開始解析首先需要導入dom4j包。在maven項目pom文件中導入jar包。
<!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
開始封裝獲得元素方法了。
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class Dom4j {
private String file;
public Document document;
private InputStream input = null;
private Map<String,String[]> eles;
public Dom4j(String file) {
this.file = file;
ClassLoader classLoader = Dom4j.class.getClassLoader();
URL resource = classLoader.getResource(file);
String path = resource.getPath();
try {
input = new FileInputStream(path);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("打開文件錯誤");
}
// 創(chuàng)建saxReader對象
SAXReader reader = new SAXReader();
// 通過read方法讀取一個文件 轉(zhuǎn)換成Document對象
try {
document = reader.read(input);
} catch (DocumentException e) {
e.printStackTrace();
}
}
/**
* 提供關(guān)閉文件方法
*/
public void close() {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("關(guān)閉文件錯誤");
}
}
/**
*提供一個從xml文件獲取ele數(shù)組的方法
* @return Map集合 通過name獲取數(shù)組values
* 數(shù)組第一位為類型 第二位為類型值
*/
private Map<String,String[]> setele() {
Iterator<Element> elements;
Element property = null;
eles = new HashMap<String, String[]>();
//獲取根節(jié)點元素對象
Element node = super.document.getRootElement();
//獲得一個element列表迭代器
elements = node.elements("property").iterator();
while (elements.hasNext()) {
property = elements.next();
String[] ele =new String[2];
ele[0] = property.attributeValue("type");
ele[1] = property.attributeValue("value");
eles.put(property.attributeValue("name"),ele);
}
close();
return eles;
}
/**
* 提供一個獲取element元素集合
* @return Map集合 通過name獲取數(shù)組values
* 數(shù)組第一位為類型 第二位為類型值
*/
public Map<String,String[]> getele() {
return this.setele();
}
然后讓我們開始獲取頁面的元素了。