使用表格的时候,如果存在过多的行数,一般建议使用缓存的方式来处理。对于自动化测试来说,在不拖动滚动条的情况下,只能看到一部分的数据。针对这种情况,可以使用scrollTop来获取数据。
需要两部分的WebElement
String tableCss = "div.test > div > div.-table-body";
String rowsCss = "div.test > div > div.-table-body > div > tr";
WebElement table = driver.findElement(By.cssSelector(tableCss));
int top = 0;
int height = 0;
while (height >=0 && top <= height) {
String script = "document.querySelector(\"" + tableCss + "\").scrollTop=" + top;
((JavascriptExecutor)driver).executeScript(script);
Thread.sleep(500);
List<WebElement> rows = driver.findElements(By.cssSelector(rowsCss));
/*
* Hand the Rows data
*/
top = top + 300;
height = new BigDecimal(table.getAttribute("scrollTop")).intValue() + 300;
}
在这里,通过top来指定每次滚动条下滑的长度,通过height来获取滚动条现在位置与顶端的长度。如果top已经大于height的时候,说明滚动条已经到最底部了。
建议设置top的递加值的时候不要过大,虽然会导致数据重复,但是不会导致数据遗漏(建议每次滑动的时候保留最后两到三行,以适配不同的分辨率)。
如果获取数据的时候,不想获取重复的数据,可以使用下面的方式:
String tableCss = "div.test > div > div.-table-body";
String rowsCss = "div.test > div > div.-table-body > div > tr";
WebElement table = driver.findElement(By.cssSelector(tableCss));
int top = 0;
int height = 0;
List<String> keyList = new ArrayList<String>();
while (height >=0 && top <= height) {
String script = "document.querySelector(\"" + tableCss + "\").scrollTop=" + top;
((JavascriptExecutor)driver).executeScript(script);
Thread.sleep(500);
List<WebElement> rows = driver.findElements(By.cssSelector(rowsCss));
for (WebElement row:rows) {
String key = row.findElement(By.cssSelector("td.key_class")).getText().trim();
if (keyList.contains(target)) {
continue;
}
keyList.add(target);
/*
* Hand the single Row data
*/
}
top = top + 300;
height = new BigDecimal(table.getAttribute("scrollTop")).intValue() + 300;
}
PS:
取height值的时候,最好不要使用Integer.parseInt()方法,在chrome的某些版本中,获取到的值会携带小数部位,从而NumberFormatException抛出异常。