3

im currently having a problem in getting the headers title of a table to make a validation, it work great until column 6, because when it goes to next one which isn't visible the .getText() is blank. I no the xpath is correct.

public void getAndSaveDataOfTable (final String tabla) throws FileNotFoundException{    
    WebElement element = driver.findElement(By.xpath(tabla)); 
    List<WebElement> elements = element.findElements(By.xpath("th"));
    Assert.assertTrue(elements.size() > 1);
    int cantelements = elements.size();

    for (int i = 1; i <= cantelements; i++) {   
        String data = driver.findElement(
            By.xpath(".//div[@class='ui-datatable-scrollable-header-box']//table/thead/tr/th["+ i + "]/span[1]")).getText();
        System.out.println("EL nombre del encabezado " + i + " " + data);
        datosFila.put(i, data);
    }

So between column 7and 20 I can't get the text of the header.

ddavison
  • 28,221
  • 15
  • 85
  • 110
elcharrua
  • 1,582
  • 6
  • 30
  • 50

2 Answers2

4

If you are going to be using the JavascriptExecutor several times (you said your issue is on multiple columns 7-20) I would suggest you can optimize by running JS only once and then iterating through in Java, rather than running JS again for every operation. The JavascriptExecutor is slow, and you'll save whole seconds on the total test time by avoiding even 12+ extra JS executions.

// JavaScript to get text from tHeads
String getTheadTexts =  
"var tHeads = []; " +
"for (i = o; i < 20; i++) { " +
    "var cssSelector = 'div.ui-datatable-scrollable-header-box table thead tr th' + i + ' span:nth-of-type(1)'; " +
    "var elem = document.querySelector(cssSelector); " +
    "var elemText = ''; " +
    "if ((elem.textContent) && (typeof (elem.textContent) != 'undefined')) { " +
        "tHeads.push(elem.textContent); " +
    "} else { " +
        "tHeads.push(elem.innerText); " +
    "} " +
"} " +
"return tHeads; ";

// Execute the JS to populate a List
List<String> tHeadTexts = (ArrayList<String>) js.executeScript(getTheadTexts);

// Do some operation on each List item
int i = 0;
for (String data: tHeadTexts){
    System.out.println("EL nombre del encabezado " + i + " " + data);
    datosFila.put(i, data);
    i++;
}
Dingredient
  • 2,191
  • 22
  • 47
3

I ran into what sounds like what you're running into. Take a look at my post on

WebElement getText() is an empty string in Firefox if element is not physically visible on the screen

I ended up solving it by using a little bit of JavaScript to columns "into view". Hopefully this helps you out.

private void scrollToElement(WebElement element){
    ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
}
Community
  • 1
  • 1
so cal cheesehead
  • 2,515
  • 4
  • 29
  • 50