標籤:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class Table {
// 通過JS動態擷取到的Html的TagName
String tagname = "";
//
String text = "";
// 用於存放Map的key值
List<String> Key = new ArrayList<String>();
// 用於存放Map的value值
List<String> Value = new ArrayList<String>();
// 將在頁面擷取的table裡面的資料以索引值對的方式存放到map中
Map<String, String> LinkMap = new LinkedHashMap<String, String>();
// selector:css選取器 :定位table下的所有tr標籤
public void tableValue(WebDriver driver, By selector) {
JavascriptExecutor JS = (JavascriptExecutor) driver;
// 首先得到表格中所有tr標籤的集合
List<WebElement> rows = driver.findElements(selector);
for (WebElement row : rows) {
// 然後得到當前所有tr裡td標籤的集合
List<WebElement> cols = row.findElements(By.tagName("td"));
for (WebElement col : cols) {
if (col.isDisplayed()) {// 防止得到最下方的隱藏的td儲存格(多餘的一部分,應為設計失誤)
// 如果executeScript()方法中執行的結果有傳回值,則需要將其返回,如果僅僅是action或者改變屬性值,則不需要返回,此處為了返回td下的子節點的標籤名,用於後續的判斷
tagname = (String) JS.executeScript(
"return arguments[0].children[0]?arguments[0].children[0].tagName:arguments[0].tagName;",
col);
if (tagname.equals("SPAN")) {
// 使用Regex,處理掉不需要的字元"*"與":"
text = col.getText().replaceAll("[*:]", "");
Key.add(text);
} else if (tagname.equals("INPUT")) {
text = col.findElement(By.tagName("input")).getAttribute("value");
Value.add(text);
} else if (tagname.equals("TD")) {
// 使用Regex,處理掉不需要的字元"*"與":"
text = col.getText().replaceAll("[*:]", "");
Key.add(text);
} else if (tagname.equals("DIV")) {
text = col.findElement(By.tagName("input")).getAttribute("value");
Value.add(text);
} else if (tagname.equals("SELECT")) {
// 擷取當前select下拉框被選中的文本的index值,僅僅只是index值,並不是其innerHTML值
text = JS.executeScript("return arguments[0].children[0].selectedIndex;", col).toString();
int index = Integer.parseInt(text);
// 通過被選中的index擷取其innerHTML值
text = (String) JS.executeScript(
"return arguments[0].children[0].children[" + index + "].innerHTML;", col);
Value.add(text);
} else {
return;
}
}
}
}
// 將key和value值存入map中,並做了對應的關聯關係
for (int i = 0; i < Value.size(); i++) {
LinkMap.put(Key.get(i), Value.get(i));
}
Iterator it = LinkMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entity = (Entry) it.next();
System.out.println("key=" + entity.getKey() + ",value=" + entity.getValue());
}
}
}
WebDriver擷取table的內容(通過動態擷取Table儲存格的TagName對其innerHTML值進行擷取)