How to read text from hidden element with Selenium WebDriver?

后端 未结 8 2187
难免孤独
难免孤独 2020-11-27 15:38

I\'m trying to read the example String 1000 out of a hidden

like this:

8条回答
  •  忘掉有多难
    2020-11-27 15:46

    I'm relatively new to Selenium (and to programming as whole), but I'm just sharing a solution that worked for me.

    Selenium 2 was not designed for handling elements with hidden visibility directly. You won't be able to find it's ID or CSS Selector, for example.

    I had a situation with a bot where I had a HTML table with lots of itens, and when clicking when of them, a dropdown with hidden visibility openned. It was even in another frame.

    It's a specific situation, but I couldn't find any solution, so I chose this (bad) one, but that works really consistently, despite the ugly code.

    First you should switchToDesiredFrame(); - enter your driver.switchTo.frame() logic here.

    Than:

    WebElement table = driver.findElements(By.tagName("table")).get(index_1);
    
    List dataCells= table .findElements(By.tagName("td"));
    
    WebElement spceificDataCellIWanted = dataCells.get(index_2);
    
    System.out.println(spceificDataCellIWanted.getText());
    

    The dataCells are literally the tags, and they become WebElements in a list just as 's are the elements in a list under the

    "container".

    It worked on Chrome and Firefox for me, but not on any headless browser, not sure exactly why. If you guys come across anything like that and have a more elegant solution (probably not so difficult to find it), please share!

    提交回复
    热议问题