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.

4

2 回答 2

0

我相信问题在于双斜杠

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

它不应该有任何斜线,以便查找以您的 iwe 元素开头。双斜杠表示查看文档中的任何位置。

应该

IList[IWebElement] ppp = iwe.FindElements(By.XPath("table"));
于 2013-04-01T17:53:26.230 回答
0

我会这样做:

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;
}
于 2013-04-01T18:10:52.897 回答