2

我有以下代码使用 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();
}
4

1 回答 1

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 + "\"]";

除了最后的部分之外,后者在“组件”之后有一个空格,而前者没有。

我怀疑使用 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 + "\"]";
于 2013-01-18T20:38:44.363 回答