0

I am using FirePath to generate valid XPaths for Behat automation tests and frequently find myself with this issue:

I need to generate an XPath for the automation tests, i.e. to click on an element, but the path contains two parts that I need to check for to confirm it is the correct one

<div id="flash-success" class="alert-box with-icon info"> Operation note created. </div>

So in the above code I can use any of these valid XPaths that will result in one matching node:

//*[@id='flash-success']
//*[@class='alert-box with-icon info']
//*[contains(text(), 'Operation note created.')]

Ideally I want to confirm that the XPath checks two parts, the id/class AND the text, something like this:

//*[@class='alert-box with-icon info']//*[contains(text(), 'Operation note created.')]

But that is NOT a valid XPath. Can anyone shed any light here, I have tried reading up on W3 and questions on here but have yet to find a solution

Sebastian Zartner
  • 18,808
  • 10
  • 90
  • 132

1 Answers1

2

If you want to find an element were all 3 of your conditions must be true you can write:

//*[@id='flash-success'][@class='alert-box with-icon info'][contains(text(), 'Operation note created.')]

or

//*[@id='flash-success' and @class='alert-box with-icon info' and contains(text(), 'Operation note created.')]

If you want to find an element were ANY of your condtions are true you would write:

//*[@id='flash-success' or @class='alert-box with-icon info' or contains(text(), 'Operation note created.')]

As a sidenote, usually when checking against a class attribute in html you would do contains(@class,'alert-box') since there usually are mulitple classes that are space separated, which are often generated and do not have to be in any order.

Sebastian Zartner
  • 18,808
  • 10
  • 90
  • 132
Tobias Klevenz
  • 1,625
  • 11
  • 13
  • 2
    Or even `contains(concat(' ',@class,' '),' alert-box ')`, to avoid matching `blah-alert-box-blah`. – Ross Patterson Apr 03 '14 at 11:07
  • 1
    See also http://stackoverflow.com/questions/1604471/how-can-i-find-an-element-by-css-class-with-xpath. – Sebastian Zartner Apr 03 '14 at 11:39
  • I cant believe the answer was so simple!! The first solution is fine as the elements need to be definite. Behat/Selenium complains if you use AND OR in the x-path though with this error message TypeError: Failed to execute 'evaluate' on 'Document': The result is not a node set, and therefore cannot be converted to the desired type. – nocturnalsteve Apr 03 '14 at 12:05