Selenium ChromeDriver: increasing time of getting

2019-02-16 02:57发布

I have a code in which I traverse table rows and columns, and I'd like to add it's values to a list.

It takes me a significant amount of time.

So I added a time measurement, and I noticed that for some reason the time increases from row to row.

I cannot understand why.

Can you advise please?

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);
        }
    }
}

Guys, I continued researching. First of all, Florent's kind answer did not help me because, at lease as I understand, It returned me an array list of strings which I had to parse, and I don't like this kind of solution too much...

So I nailed the problem in finding that the e.getText() call was increasing in time from call to call!!! I also tried e.getAttribute("innerText") instead but no change. Can't understand why. Any idea to solve?

            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...");
                }
            }

That is an graph of the time getText took...

enter image description here


08-May-18 Another source of growing execution time is this one:

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");

    }
}

Every functions has 5 iterations only, but still each call to the function increases its execution time. Is there a solution for this one as well?

2条回答
Summer. ? 凉城
2楼-- · 2019-02-16 03:02

The problem you are facing is because of the way Selenium works by design. Let's look at how a JavaScript get's executed or a operation is performed

tds.get(TABLE_COLUMNS.NAME_COL.getNumVal()).getText();

You have a collection of objects. Each object is assigned a unique ID on the browser side by the selenium driver

So when you do a getText() below is what happens

Your code -> HTTP Request -> Browser Driver -> Browser ->
                                                        |
           <---------------------------------------------

Now if you have a table of 400rx10c then it accounts to 4000 HTTP calls, even if one call takes 10ms, we are looking at a 40000ms~=40sec, which is a decent delay to read a table

So what you want to do is to get all the data in single go by executing a javascript which give you 2d array back. It is quite simple, I found a code on below site

http://cwestblog.com/2016/08/21/javascript-snippet-convert-html-table-to-2d-array/

function tableToArray(tbl, opt_cellValueGetter) {
  opt_cellValueGetter = opt_cellValueGetter || function(td) { return td.textContent || td.innerText; };
  var twoD = [];
  for (var rowCount = tbl.rows.length, rowIndex = 0; rowIndex < rowCount; rowIndex++) {
    twoD.push([]);
  }
  for (var rowIndex = 0, tr; rowIndex < rowCount; rowIndex++) {
    var tr = tbl.rows[rowIndex];
    for (var colIndex = 0, colCount = tr.cells.length, offset = 0; colIndex < colCount; colIndex++) {
      var td = tr.cells[colIndex], text = opt_cellValueGetter(td, colIndex, rowIndex, tbl);
      while (twoD[rowIndex].hasOwnProperty(colIndex + offset)) {
        offset++;
      }
      for (var i = 0, colSpan = parseInt(td.colSpan, 10) || 1; i < colSpan; i++) {
        for (var j = 0, rowSpan = parseInt(td.rowSpan, 10) || 1; j < rowSpan; j++) {
          twoD[rowIndex + j][colIndex + offset + i] = text;
        }
      }
    }
  }
  return twoD;
}

I assume you store the above script in a SCRIPT variable and then you can run it like below

WebDriver driver = ((RemoteWebElement)table).getWrappedDriver();
Object result = ((JavascriptExecutor)driver).executeScript(SCRIPT + "\n return tableToArray(arguments[0]);" , table);

This will get you a 2D array of the data and you can then process it the way you like it

查看更多
Animai°情兽
3楼-- · 2019-02-16 03:23

Calling the driver is an expensive operation. To significantly reduce the execution time, use a JavaScript injection with executeScript to read the whole table in a single call. Then process/filter the data on the client side with 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;
}
查看更多
登录 后发表回答