2013-04-01 77 views
0

我使用硒作爲Web刮板,並希望找到多個表,然後爲每個表(通過循環)找到該表內的一個元素(而不再遍歷整個文檔)。selenium - 如何找到使用父元素的元素?

我使用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")); 

} 

在這裏,我想從每個表裏面加載內表在元素中,但不斷給我上面提到的錯誤。

+0

檢查此[鏈接](http://stackoverflow.com/questions/5709204/random-element-is -no-longer-attached-to-the-dom-staleelementreferenceexception)如果你還得到'StaleElementReferenceException'。 – Hemanth

回答

0

我相信這個問題是用雙斜槓在

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

它不應該有任何斜線,以便找到你的IWE元素開始。雙斜槓意思是看文檔中的任何地方。

應該

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

感謝你們......你說得對,它現在正在工作 –

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; 
} 
相關問題