我有一个代码,可以在其中遍历表格行和列,并且我想将其值添加到列表中。
这花费了我大量的时间。
所以我添加了一个时间测量,我注意到由于某种原因,时间从一行到另一行增加。
我不明白为什么。
您能给点建议吗?
private void buildTableDataMap() {
WebElement table = chromeWebDriver.findElement(By.id("table-type-1"));
List<WebElement> rows = table.findElements(By.tagName("tr"));
theMap.getInstance().clear();
String item;
for (WebElement row : rows) {
ArrayList<String> values = new ArrayList<>();
List<WebElement> tds = row.findElements(By.tagName("td"));
if(tds.size() > 0){
WebElement last = tds.get(tds.size() - 1);
long time = System.currentTimeMillis();
values.addAll(tds.stream().map(e->e.getText()).collect(Collectors.toList()));
System.out.println(System.currentTimeMillis() - time);
//remove redundant last entry:
values.remove(tds.size() - 1);
callSomeFunc(values, last);
item = tds.get(TABLE_COLUMNS.NAME_COL.getNumVal()).getText();
item = item.replaceAll("[^.\\- /'&A-Za-z0-9]", "").trim();//remove redundant chars
theMap.getInstance().getMap().put(item, values);
}
}
}
<小时/>
伙计们,我继续研究。 首先,弗洛伦特的善意回答对我没有帮助,因为至少据我了解,它返回了我必须解析的字符串数组列表,而且我不太喜欢这种解决方案......
所以我解决了这个问题,发现 e.getText() 调用在每次调用之间的时间都在增加! 我也尝试了 e.getAttribute("innerText") 但没有改变。 不明白为什么。有什么办法解决吗?
WebElement last = null;
for (WebElement e : tds){
last = e;
long tm1 = 0, tm2 = 0;
if(Settings.verboseYN) {
tm1 = System.currentTimeMillis();
}
s = e.getText(); //This action increases in time!!!
if(Settings.verboseYN) {
tm2 = System.currentTimeMillis();
}
values.add(s); //a 0 ms action!!!
if(Settings.verboseYN) {
System.out.println("e.getText()) took " + (tm2 - tm1) + " ms...");
}
}
这是 getText 花费时间的图表...
<小时/>2018 年 5 月 8 日 执行时间增长的另一个原因是:
void func(WebElement anchorsElement){
List<WebElement> anchors = anchorsElement.findElements(By.tagName("a"));
for (WebElement a : anchors) {
if (a.getAttribute("class").indexOf("a") > 0)
values.add("A");
else if (a.getAttribute("class").indexOf("b") > 0)
values.add("B");
else if (a.getAttribute("class").indexOf("c") > 0)
values.add("C");
}
}
每个函数只有 5 次迭代,但每次调用该函数仍然会增加其执行时间。 这个问题也有解决办法吗?
最佳答案
调用驱动程序是一项昂贵的操作。要显着减少执行时间,请使用带有 executeScript
的 JavaScript 注入(inject)在一次调用中读取整个表。然后在客户端用Java处理/过滤数据。
public ArrayList<?> readTable(WebElement table)
{
final String JS_READ_CELLS =
"var table = arguments[0]; " +
"return map(table.querySelectorAll('tr'), readRow); " +
"function readRow(row) { return map(row.querySelectorAll('td'), readCell) }; " +
"function readCell(cell) { return cell.innerText }; " +
"function map(items, fn) { return Array.prototype.map.call(items, fn) }; " ;
WebDriver driver = ((RemoteWebElement)table).getWrappedDriver();
Object result = ((JavascriptExecutor)driver).executeScript(JS_READ_CELLS, table);
return (ArrayList<?>)result;
}
关于java - Selenium ChromeDriver : increasing time of getting WebElement Text,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50097877/