我有以下代碼來找到使用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();
}
怎麼樣,如果你更換在該XPath中使用'.text'或'normalize-space(。)'作爲文本()。 – JLRishe
@JLRishe - 我試過但沒有區別 –
你確定這個元素在運行時已經完全加載了嗎?嘗試在對columnsXpath元素調用findElement之前插入wait。 – CIGuy