我有以下代码来使用 Xpath 来定位元素,使用 Firebug 效果很好。当我运行程序时,出现以下异常:
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"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();
}
最佳答案
正如评论中提到的,这两个 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 + "\"]";
除了最后的部分之外,就是后者“组件”后面有一个空格,而前者没有。
我怀疑使用 normalize-space() 并删除比较值中的前导和尾随空格可能有助于消除 @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 + "\"]";
关于java - Selenium 无法使用 xpath 定位元素,但 firebug 可以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14402132/