Example – 1:
<div id="first-div"> <div id="text-1" name="A">Text</div> <div id="text-2" name="B">Random text</div> <div id="text-3">Random text</div> </div>
If you need element and it has id, standard text or name, it’s easy to find it by id or name:
.//div[@id=’text-1’]
.//*[name()=’A’]
By text:
.//*[contains(text(),’which will never change’)]
OR
.//*[contains(.,’which will never change’)]
OR
.//*[starts-with(.,’Text’)]
OR
.//*[ends-with(.,’change’)]
If you know full text:
.//*[text()=’Text for testing’]
OR
.//*[.=’Text for testing’]
Perhaps you want to find all divs or all elements which haven’t random text:
.//div[not(.=’Random text’)]
But now you need all elements which haven’t id and have random text, so:
.//div[.=’Random text’ and not(@id)]
Example – 2:
<div class="ui-dialog ui-widget" style="position: absolute; height: auto; width: 800px; top: 191px; left: 557px; display: block;" tabindex="-1"> <div class="ui-dialog-titlebar"> <span id="random1223">Window</span> <button> <span class="ui-button" /> <span class="ui-button-text">New</span> </button> </div> .... <div class="uidialog-buttonpane"> <div class="ui-dialog-buttonset"> <button> <span class="ui-button-text">New<span> </button> </div> </div> </div>
We can find main div by class attribute, but in case class changes, we need to rewrite our xpath.
BAD: .//span[@class=’ui-button-text’]
BAD: .//span[2][@class=’ui-button-text’]
You can see that span on the footer of the Window doesn’t have siblings, so we have rule which can be implemented: .//div[div[span=’Window’]] and find span with text() equals New.
.//div[div[span=’Window’]]//span[.=’New’]