2013-01-18 109 views
2

我有以下代碼來找到使用Xpath的元素,它使用Firebug它效果很好。當我運行我的程序,我得到以下異常:線程「main」 org.openqa.selenium.NoSuchElementException硒無法定位元素使用Xpath,但螢火蟲可以

異常:找不到元素:{「方法」:「的XPath」,「選擇」:」 (// div [@ class = \「x-ignore x-menu x-component \」] // div)/ a [text()= \「ID \」]「}

如果我在Firebug中確切的xpath和Stick我可以找到我的元素沒有問題。任何想法爲什麼Selenium找不到它?

這裏是我的代碼:

public static void displayColumn(String column) throws Exception { 
    String columnOptionsDropdownXpath = "(//div[@class=\"x-grid3-header\"]//span)[1]/../a"; 
    String columnXpath = "(//div[@class=\"x-grid3-header\"]//span)[1]"; 
    String columnsXpath = "(//div[@class=\" x-ignore x-menu x-component\"]//a)[3]"; 
    String columnToDisplayXpath = "(//div[@class=\" x-ignore x-menu x-component \"]//div)/a[text()=\"" + column + "\"]"; 

    // Because the 'column options' button doesn't appear until you hover over the column 
    WebElement col = null; 
    try { 
     col = driver.findElement(By.xpath(columnXpath)); 
    } catch (NoSuchElementException e) { 
     System.out.println("Column not found - is it displayed?"); 
    } 

    Actions builder = new Actions(driver); 
    builder.moveToElement(col).build().perform(); 
    WebElement element = driver.findElement(By.xpath(columnOptionsDropdownXpath)); 
    element.click(); 
    Thread.sleep(500); 

    element = driver.findElement(By.xpath(columnsXpath)); 
    builder.moveToElement(element).build().perform(); 
    Thread.sleep(2000); 
    WebDriverWait wait = new WebDriverWait(driver, 10); 
    try { 
     System.out.println("in try statement"); 
     wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(columnToDisplayXpath))); 
    } catch (TimeoutException e) {} 

    element = driver.findElement(By.xpath(columnToDisplayXpath)); 
    element.click(); 
} 
+0

怎麼樣,如果你更換在該XPath中使用'.text'或'normalize-space(。)'作爲文本()。 – JLRishe

+0

@JLRishe - 我試過但沒有區別 –

+0

你確定這個元素在運行時已經完全加載了嗎?嘗試在對columnsXpath元素調用findElement之前插入wait。 – CIGuy

回答

2

正如在評論中提到的,這兩個XPath之間的細微差別:

String columnsXpath = "(//div[@class=\" x-ignore x-menu x-component\"]//a)[3]"; 
String columnToDisplayXpath = "(//div[@class=\" x-ignore x-menu x-component \"]//div)/a[text()=\"" + column + "\"]"; 

除了在最後的部分,在於後者有空間之後的「組件」和前者沒有。

我懷疑是使用正常化空間(),並刪除了領先,並在比較值尾部的空格可以幫助化解矛盾在@class屬性值的間距:

String columnsXpath = "(//div[normalize-space(@class) = \"x-ignore x-menu x-component\"]//a)[3]"; 
String columnToDisplayXpath = 
    "(//div[normalize-space(@class) = \"x-ignore x-menu x-component\"]//div)/a[text()=\"" 
    + column + "\"]"; 
+0

我用normalize-space()進行了測試,直到我手動刪除了空白區域,除非我做得不正確,它纔會繼續失敗。下次遇到類似情況時,我一定要記住它。再次感謝。 –

+0

那麼,在我上面的例子中,你可以看到我已經手動移除了XPath中的_string values_的前導和尾隨空格,並且'normalize-space()'用來解釋實際屬性值中的空格。如果在'@ class'周圍放置'normalize-space()',並在XPath中的「x-ignore x-menu x-component」之前和之後留下空格,那肯定無法工作。 – JLRishe