我有以下代码使用 Xpath 定位元素,使用 Firebug 效果很好。当我运行我的程序时,出现以下异常:
线程“main” org.openqa.selenium.NoSuchElementException 中的异常:无法找到元素:{“method”:“xpath”,“selector”:“(//div [@class = \” x-ignore x-menu x -component \"]//div)/a[text()=\"ID\"]"}
如果我采用确切的 xpath 并坚持使用 Firebug,我可以发现我的元素没有问题。任何想法为什么 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();
}