硒 :该表达式不是合法表达/ Xpath


Selenium : The expression is not a legal expression / Xpath

我正在使用Behat和Selenium服务器。我正在尝试根据特定标签在文档中的位置来定位该标签。

我使用AquaPath,一个GUI来玩XPath并且工作正常。我的问题是,当我在 Behat/Selenium 中尝试相同的表达式时,我收到"表达式不是合法表达式"错误消息。

这是我的Xpath:

(//label)[5]/@for

我正在寻找具有此属性的第五个标签元素的"for"属性。看起来很容易,但不起作用,我真的不知道为什么...

以下是完整的日志(请注意,//html 是自动添加的):

The given selector //html//(label)[1] is either invalid or does not result in a WebElement. The following error occurred:
[InvalidSelectorError] Unable to locate an element with the xpath expression //html//(label)[1] because of the following error:
[Exception... "The expression is not a legal expression."  code: "51" nsresult: "0x805b0033 (NS_ERROR_DOM_INVALID_EXPRESSION_ERR)"  location: "file:///var/folders/66/bv_nvdt97f33pm2qn78v_8qc0000gn/T/anonymous5419845357799771264webdriver-profile/extensions/fxdriver@googlecode.com/components/driver_component.js Line: 2621"]
Command duration or timeout: 6 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/invalid_selector_exception.html
Build info: version: '2.23.1', revision: '17143', time: '2012-06-08 18:59:04'
System info: os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.7.4', java.version: '1.6.0_33'
Driver info: driver.version: EventFiringWebDriver
Session ID: c3bdf2e6-5042-ac4a-95c5-4735f4318899

知道吗?

这是 HTML(标签并不总是在同一深度):

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <form action="" method="get" accept-charset="utf-8">
      <label for="label1"></label>
      <label for="label2"></label>
      <div>
        <label for="label3"></label>        
      </div>
      <fieldset>
        <div>
          <label for="label4"></label>
        </div>        
      </fieldset>
      <label for="label5"></label>
      <label for="label6"></label>
      <label for="label7"></label>
      <label for="label8"></label>
      <label for="label9"></label>
      <p><input type="submit" value="Continue &rarr;"></p>
    </form>
  </body>
</html>

尝试(//fieldset/label)[5]/@for而不是(//fieldset//label)[5]/@for

我的观点是带有"xpath"选择器的"find()"方法不能获得属性,只能获取元素。获取属性必须通过"getAttribute()"完成。