0

I am using selenium as a web scraper and would like to locate a number of tables and then for every table (by looping) locate an element inside that table (without going through the entire document again).

I am using the Iwebelement.FindElements(By.XPath) but keeps giving an error saying 'element no longer connected to DOM'

here is an excerpt from my code:

IList[IWebElement] elementsB = driver.FindElements(By.XPath("//*[@id=\"col_main\"]/table[@class='risultati']")); 

// which loads all tables with class 'risultati'

foreach (IWebElement iwe in elementsB)

{

IList[IWebElement] ppp = iwe.FindElements(By.XPath("//table"));

}

here I am trying to load inner tables from inside each table found in elements, but keeps giving me the error mentioned above.

pb2q
  • 58,613
  • 19
  • 146
  • 147
JeanPaul Galea
  • 113
  • 3
  • 11
  • check this [link](http://stackoverflow.com/questions/5709204/random-element-is-no-longer-attached-to-the-dom-staleelementreferenceexception) if you are also getting `StaleElementReferenceException`. – HemChe Apr 01 '13 at 17:44

2 Answers2

0

I believe the issue is with the double slashes in

IList[IWebElement] ppp = iwe.FindElements(By.XPath("//table"));

It shouldn't have any slashes so that the find begins with your iwe element. Double slashes mean look anywhere in the document.

should be

IList[IWebElement] ppp = iwe.FindElements(By.XPath("table"));
Bob
  • 81
  • 1
0

I would do it something like this:

By tableLocator = By.XPath("//table");
By itemLocator = By.XPath("//*[@id=\"col_main\"]/table[@class='risultati']");

for(WebElement iwe : elementsB) {
   List<WebElement> tableList = iwe.FindElements( tableLocator );
   for ( WebElement we : tableList ) {
       we.getElementByLocator( itemLocator );
       System.out.println( we.getText() );
   }
}

public static WebElement getElementByLocator( final By locator ) {
  LOGGER.info( "Get element by locator: " + locator.toString() );  
  final long startTime = System.currentTimeMillis();
  Wait<WebDriver> wait = new FluentWait<WebDriver>( driver )
    .withTimeout(30, TimeUnit.SECONDS)
    .pollingEvery(5, TimeUnit.SECONDS)
    .ignoring( StaleElementReferenceException.class ) ;
  int tries = 0;
  boolean found = false;
  WebElement we = null;
  while ( (System.currentTimeMillis() - startTime) < 91000 ) {
   LOGGER.info( "Searching for element. Try number " + (tries++) ); 
   try {
    we = wait.until( ExpectedConditions.visibilityOfElementLocated( locator ) );
    found = true;
    break;
   } catch ( StaleElementReferenceException e ) {      
    LOGGER.info( "Stale element: \n" + e.getMessage() + "\n");
   }
  }
  long endTime = System.currentTimeMillis();
  long totalTime = endTime - startTime;
  if ( found ) {
   LOGGER.info("Found element after waiting for " + totalTime + " milliseconds." );
  } else {
   LOGGER.info( "Failed to find element after " + totalTime + " milliseconds." );
  }
  return we;
}
djangofan
  • 28,471
  • 61
  • 196
  • 289