专题六:实现获取table元素的类
场景:html中存在很多
table类型的元素。表格就是一个很典型的,在第几行第几列存放一些内容。
思路:先找tr,再找td.
脚本:(JAVA实现)
public class Table extends pageSourceFiles{
public static int[] getIndex(String tableCellAddress){
//将传入的字符串转化成行和列
int index =tableCellAddress.trim().indexof('.');
int row=Integer.parseInt(tableCellAddress.substring(0,index));
int cell=Integer.parseInt(tableCellAddress.substring(index+1));
int[] a=new int[2];
a[0]=row;
a[1]=cell;
return a;
}
public static WebElement getRow(final By,int row){
//找到tr元素
WebDriverWait wait=new WebDriverWait(getDriver(),60);
List<WebElement>rows=wait.until(new ExpectedCondition<List<WebElement>>{
List<WebELement> apply(WebDriver d){
return d.findElement(by).findElements(By.tagName("tr"));
}});
WebElement Row=rows.get(row);
return Row;
}
//通过行元素,找到cell元素
public static WebElement getCell(final By by,int row,int cell){
//找到tr元素对象
WebDriver wait =new WebDriverWait(getDriver(),60);
List<WebElement> rows=wait.until(new ExpectedCondition<List<WebElement>>(){
public List<WebElemen> apply(WebDriver d){
return d.findElement(by).findElements(By.tagName("tr"));
} });
//取第几行
WebElement Row=rows.get(row);
List<WebElement>cells=Row.findElements(By.tagName("td"));
WebElement target=null;
//取cell元素(tr行td列)
if(cells.isEmpty()){
cells=Row.findElements(By.tagName("th"));
target=cells.get(cell);}
else target=cells.get(cell);
return target;
}
//获取某列下的子元素
public static WebElement Ele(String index,By by1,By by2){
int[] a=new int[2];
a=getIndex(index);
WebElement td=getCell(by1,a[0],a[1]);
return td.findElement(by2);
}
//获取cell元素的text
public static String getText(By by,int row,int cell){
String text=getCell(by,row,cell).getText();
return text;
}
//根据单元格的文本获取所在表格的位置
public static int[] tablePosition (final By by,String menuName)
//找到tr元素对象
WebDriverWait wait=new WebDriverWait(getDriver(),60);
List<WebElement> rows=wait.until(new ExpectedCondition<List<WebElement>>()){
public List<WebElement> apply(WebDriver d){
return d.findElement(by).findElements(By.tagName)("tr"));
}});
int[] a=new int[2];
int i=0;
for(WebElement row:rows){
//得到当前tr里td的集合
List<WebElement>cols=row.findElements(By.tagName("td"));
int j=0;
for(WebElement col:cols){
if(col.getText().trim().equasl(menuName)){
a[0]=i+1;
a[1]=j+1;
break;}
j++;}
i++;}
return a;
}
}