selenium - 如何使用父元素找到元素?

时间:2013-04-01 16:36:13

标签: xpath selenium webdriver selenium-webdriver

我使用selenium作为web scraper,并希望找到许多表,然后为每个表(通过循环)找到该表中的元素(不再遍历整个文档)。

我正在使用Iwebelement.FindElements(By.XPath),但一直发出错误信息'element no longer connected to DOM'

这是我的代码的摘录:

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

}

这里我试图从元素中找到的每个表中加载内部表,但一直给我上面提到的错误。

2 个答案:

答案 0 :(得分:0)

我认为问题在于

中的双斜线
IList[IWebElement] ppp = iwe.FindElements(By.XPath("//table"));

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

应该是

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

答案 1 :(得分: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;
}