2

When I use the following XPath expression in Selenium, it works correctly. Its finds an ancestor div of the current element which contains a certain string in its class attribute:

inputEl.findElement(By.xpath("ancestor::div[contains(@class, 'x-form-item')]")).getAttribute("class")

The answer it gives is "x-form-item " (notice the trailing space).

However, I want ancestors which precisely have the x-form-item class, and not other classes like x-form-item-label. So I changed the expression as follows:

inputEl.findElement(By.xpath("ancestor::div[contains(concat(' ', @class, ' '), ' x-form-item ')]")).getAttribute("class")

However, once this in place, Selenium is unable to find the element. It gives this error:

org.openqa.selenium.NoSuchElementException: Unable to find element with xpath == ancestor::div[contains(concat(' ', @class, ' '), ' x-form-item ')] (WARNING: The server did not provide any stacktrace information)

At first I thought I had some kind of mistake, so to simplify, I removed the leading/trailing space. Presumably this is semantically the same as my very first, working query:

inputEl.findElement(By.xpath("ancestor::div[contains(concat('', @class, ''), 'x-form-item')]")).getAttribute("class")

However, this also fails:

org.openqa.selenium.NoSuchElementException: Unable to find element with xpath == ancestor::div[contains(concat('', @class, ''), 'x-form-item')] (WARNING: The server did not provide any stacktrace information)

So my fundamental question is, why are these two resulting in different strings?

  • @class
  • concat('', @class, '')

Note: I am using the IEDriver with IE9

4

1 回答 1

0

要实现你想要的,你甚至不需要 concat(' ', @class, ' ')。你应该可以使用

By.xpath("ancestor::div[contains(@class, ' x-form-item ')]")

因为您在“@class”标签中寻找“x-form-item”,而不是在“@class”标签中寻找。

于 2013-03-11T19:08:53.110 回答